def alter_domain_name():
    soucedomain = domain_dictionary('SPDM2_201803.gdb','Short')
    for dmname, alias_codesc in soucedomain.items():
        new_dmname = dmname[0:2]+'_' + dmname[2:]
        #if del_nm == dmname:
        if dmname[2] != '_':
            arcpy.CreateDomain_management(outdataset, new_dmname, alias_codesc[0], 'Short', 'CODED')
            print "创建域值"
            for cod, desc in alias_codesc[1].items():
                try:
                    arcpy.AddCodedValueToDomain_management(outdataset, new_dmname, int(cod), desc)
                except arcpy.ExecuteError:
                    print arcpy.GetMessages()
                    print cod, desc
                    print type(cod)
            arcpy.DeleteDomain_management(outdataset,dmname)
def alter_domiantype_single():

    outdataset = r'D:\智能化管线项目\新气\新气数据处理\新气数据入库_0916\新库0910.gdb'

    save_domain = domain_dictionary(outdataset, 'LONG')  #
    print save_domain

    arcpy.DeleteDomain_management(outdataset, "gn_Reportstatus")
    for dmname, alias_codesc in save_domain.items():
        # if del_nm == dmname:
            arcpy.CreateDomain_management(outdataset, "gn_Reportstatus", alias_codesc[0], 'Short', 'CODED')
            print "创建域值"
            for cod, desc in alias_codesc[1].items():
                try:
                    arcpy.AddCodedValueToDomain_management(outdataset, "gn_Reportstatus", int(cod), desc)
                except arcpy.ExecuteError:
                    print arcpy.GetMessages()
                    print cod, desc
                    print type(cod)
Пример #3
0
def PrepFeatClassForLibrary(featPath, logger, lstErrCnt):
    # get all subtype codes in order to remove domains from subtypes
    subtypeCodes = []
    subtypes = arcpy.da.ListSubtypes(featPath)
    for stcode, stdict in list(subtypes.items()):
        subtypeCodes.append(stcode)  # append subtype codes to a list

    # Remove domains from subtypes and fields
    lstDomains = []
    ndx = featPath.rfind('/')
    featWrkspc = featPath[0:ndx]  # get just the workspace part of the featPath
    featName = featPath.split('/')[-2] + '/' + featPath.split('/')[
        -1]  # geodatabase/name for log
    lstFields = arcpy.ListFields(featPath)
    for fld in lstFields:
        if len(fld.domain) > 0:
            if fld.domain not in lstDomains:
                lstDomains.append(fld.domain)
            try:
                arcpy.RemoveDomainFromField_management(
                    featPath, fld.name,
                    subtypeCodes)  # remove domain from all subtypes
            except Exception as e:
                logger.warning(
                    '\tUnable to remove domain from subtype on field ' +
                    fld.name)
                #lstErrCnt[1] += 1 # Don't count warning so that email notification will ignore
            try:
                arcpy.RemoveDomainFromField_management(
                    featPath, fld.name)  # remove domain from field
            except Exception as e:
                logger.warning('\tUnable to remove domain from field ' +
                               fld.name)
                #lstErrCnt[1] += 1 # Don't count warning so that email notification will ignore
    # delete the domains from the workspace
    for dmn in lstDomains:
        try:
            arcpy.DeleteDomain_management(featWrkspc, dmn)
        except Exception as e:
            logger.warning('\tUnable to delete domain ' + dmn + ' on ' +
                           featName)
Пример #4
0
 def detruireDomaineAttribut(self, workspace, classe):
 #-------------------------------------------------------------------------------------
     """
     Permet de détruire tous les domaines existants dans la Géodatabase.
     
     Paramètres:
     -----------
     workspace   : Nom de la géodatabase ou les domaines seront détruits.
     classe      : Liste des noms de classe contenus dans la géodatabase utilisés pour créer les domaines.
     
     """
     
     #Définir le workspace par défaut
     arcpy.env.workspace = workspace
     
     #Extraire les FeatureClass de la Géodatabase
     for fc in arcpy.ListFeatureClasses():
         #Vérifier si la classe est présente dans la liste des classes
         if fc.upper() in classe:
             #Afficher le message pour détruire les domaines de la classe traité
             arcpy.AddMessage(" ")
             arcpy.AddMessage(u"- Détruire les subtypes de la classe : " + fc)
             #Définir tous les Subtypes
             subtypes = arcpy.da.ListSubtypes(fc)
             #Vérifier si un Subtype est présent
             if subtypes.values()[0]['SubtypeField'] <> "":
                 #Afficher le message
                 arcpy.AddMessage("SetSubtypeField_management('" + fc + "', #, True)")
                 #Enlever les subtypes d'une classe
                 arcpy.SetSubtypeField_management(fc, "#", True)
                 
                 #Afficher les subtypes
                 #for stcode, stdict in list(subtypes.items()):
                     #Afficher le message
                     #arcpy.AddMessage(" RemoveSubtype_management('" + fc + "', '" + str(stcode) + "')")
                     #Détruire un subtype d'une classe
                     #arcpy.RemoveSubtype_management(fc, stcode)
             
             #Afficher le message pour détruire les domaines de la classe traité
             arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la classe : " + fc)
             #Traiter tous les fields
             for field in arcpy.ListFields(fc):
                 #Vérifier la présence d'un domaine
                 if field.domain <> "":
                     #Afficher le message
                     arcpy.AddMessage("RemoveDomainFromField_management('" + fc + "', '" + field.name + "')")
                     #Détruire un domaine dans un attribut d'une classe
                     arcpy.RemoveDomainFromField_management(fc, field.name)
                 
                 #Vérifier si une valeur par défaut est présente
                 if field.defaultValue <> None:
                     #Afficher le message
                     arcpy.AddMessage("AssignDefaultToField_management('" + fc + "', '" + field.name + "' # # True)")
                     #Détruire la valeur par défaut de l'attribut d'une classe
                     arcpy.AssignDefaultToField_management(fc, field.name, "#", "#", True)
                 
     #Extraire les tables de la Géodatabase
     for tbl in arcpy.ListTables():
         #Vérifier si la table est présente dans la liste des classes
         if tbl.upper() in classe:
             #Afficher le message pour détruire les domaines de la classe traité
             arcpy.AddMessage(" ")
             arcpy.AddMessage(u"- Détruire les subtypes de la table : " + tbl)
             #Définir tous les Subtypes
             subtypes = arcpy.da.ListSubtypes(tbl)
             #Vérifier si un Subtype est présent
             if subtypes.values()[0]['SubtypeField'] <> "":
                 #Afficher le message
                 arcpy.AddMessage("SetSubtypeField_management('" + tbl + "', #, True)")
                 #Enlever les subtypes d'une classe
                 arcpy.SetSubtypeField_management(tbl, "#", True)
                 
                 #Afficher les subtypes
                 #for stcode, stdict in list(subtypes.items()):
                     #Afficher le message
                     #arcpy.AddMessage(" RemoveSubtype_management('" + tbl + "', '" + str(stcode) + "')")
                     #Détruire un subtype d'une table
                     #arcpy.RemoveSubtype_management(tbl, stcode)
             
             #Afficher le message pour détruire les domaines de la classe traité
             arcpy.AddMessage(u"- Détruire le domaine et la valeur par défaut pour chaque attribut de la table : " + tbl)
             #Traiter tous les fields
             for field in arcpy.ListFields(tbl):
                 #Vérifier la présence d'un domaine
                 if field.domain <> "":
                     #Afficher le message
                     arcpy.AddMessage("RemoveDomainFromField_management('" + tbl + "', '" + field.name + "')")
                     #Détruire un domaine dans un attribut d'une classe
                     arcpy.RemoveDomainFromField_management(tbl, field.name)
                 
                 #Vérifier si une valeur par défaut est présente
                 if field.defaultValue <> None:
                     #Afficher le message
                     arcpy.AddMessage("AssignDefaultToField_management('" + tbl + "', '" + field.name + "' # # True)")
                     #Détruire la valeur par défaut de l'attribut d'une table
                     arcpy.AssignDefaultToField_management(tbl, field.name, "#", "#", True)
     
     #Envoyer un message
     arcpy.AddMessage(" ")
     arcpy.AddMessage(u"- Détruire les domaines non-utilisés dans la Géodatabase")
     
     #Extraire la description de la Géodatabase
     desc = arcpy.Describe(workspace)
     
     #Extraire tous les domaines existants de la Géodatabase
     domains = desc.domains
     
     #Traiter tous les domaines
     for domain in domains:
         try:
             #Détruire un domaine
             arcpy.DeleteDomain_management(workspace, domain)
             #Afficher le message
             arcpy.AddMessage("DeleteDomain_management('" + workspace + "', '" + domain + "')")
         #Gestion des erreurs
         except Exception, err:
             #Afficher l'erreur
             arcpy.AddWarning(u"Le domaine est encore utilisé et ne peut être détruit : " + domain)
Пример #5
0
  
# Get domains that are assigned to a field  
domains_used = []  
for dirpath, dirnames, filenames in arcpy.da.Walk(myGDB, datatype=["FeatureClass", "Table"]):  
    for filename in filenames:  
        print "Checking {}".format(os.path.join(dirpath, filename))
        print arcpy.GetMessages()  
        try:  
            ## Check for normal field domains  
            for field in arcpy.ListFields(os.path.join(dirpath, filename)):  
                if field.domain:  
                    domains_used.append(field.domain)  
            ## Check for domains used in a subtype field  
            subtypes = arcpy.da.ListSubtypes(os.path.join(dirpath, filename))  
            for stcode, stdict in subtypes.iteritems():  
                if stdict["SubtypeField"] != u'':  
                    for field, fieldvals in stdict["FieldValues"].iteritems():  
                        if not fieldvals[1] is None:  
                            domains_used.append(fieldvals[1].name)  
        except Exception, err:  
            print "Error:", err  
  
# Get domains that exist in the geodatabase  
domains_existing = [dom.name for dom in arcpy.da.ListDomains(myGDB)]  
  
# Find existing domains that are not assigned to a field  
domains_unused = set(domains_existing) ^ set(domains_used)  
print "{} unused domains in {}".format(len(domains_unused), myGDB)  
for domain in domains_unused:  
    arcpy.DeleteDomain_management(myGDB, domain)  
    print "{} deleted".format(domain) 
Пример #6
0
    edit.stopEditing(True)

    ###Join all active domains table to the all domains table
    ###Those domains in the all domains table that do not have a match are inactive

    arcpy.AddJoin_management(allDomainsView, "dom_name", activeDomainsView,
                             "name", "KEEP_ALL")

    with arcpy.da.SearchCursor(
            allDomainsView,
        ["UUSD.DBO.domain_active.name", "UUSD.DBO.domain_all.dom_name"]) as sc:
        for row in sc:
            if row[0] == None:
                inactiveDomains.append(row[1])
                try:
                    arcpy.DeleteDomain_management(workspace, row[1])
                except:
                    infile.write("\nCould not delete " + row[1] + ".\n" +
                                 arcpy.GetMessages(2) + "\n")

    #print inactiveDomains
    inactiveDomains.sort()
    print "\nLENGTH: " + str(len(inactiveDomains)) + "\n"
    infile.write("INACTIVE DOMAINS\n")
    for dom in inactiveDomains:
        print dom
        infile.write(dom + "\n")

    infile.close()
    sendEmail()
Пример #7
0
def main():
    try:
        # Connection path to geodatabse (as administrator if SDE)
        myGDB = r"C:\GISConnections\[email protected]"

        # Get domains that are assigned to a field
        domainsUsed_names = []
        for dirpath, dirnames, filenames in arcpy.da.Walk(myGDB, datatype=["FeatureClass", "Table"]):
            for filename in filenames:
                print "Checking {}".format(os.path.join(dirpath, filename))

                ## Check for normal field domains
                for field in arcpy.ListFields(os.path.join(dirpath, filename)):
                    if field.domain:
                        domainsUsed_names.append(field.domain)

                ## Check for domains used in a subtype field
                subtypes = arcpy.da.ListSubtypes(os.path.join(dirpath, filename))
                for stcode, stdict in subtypes.iteritems():
                    if stdict["SubtypeField"] != u'':
                        for field, fieldvals in stdict["FieldValues"].iteritems():
                            if not fieldvals[1] is None:
                                domainsUsed_names.append(fieldvals[1].name)
                ## end for subtypes
            ## end for filenames
        ## end for geodatabase Walk

        # List of all existing domains (as domain objects)
        domainsExisting = arcpy.da.ListDomains(myGDB)

        # Find existing domain names that are not in use (using set difference)
        domainsUnused_names = (
            set([dom.name for dom in domainsExisting]) - set(domainsUsed_names)
        )

        # Get domain objects for unused domain names
        domainsUnused = [
            dom for dom in domainsExisting
            if dom.name in domainsUnused_names
        ]
        print "{} unused domains in {}".format(len(domainsUnused), myGDB)

        # Cleanup
        del domainsExisting
        del domainsUnused_names

        # Delete unused domains by owner
        ## For local geodatabses, owner is an empty string ('')
        with makeTempDir() as temp_dir:
            descGDB = arcpy.Describe(myGDB)
            for owner in set([dom.owner for dom in domainsUnused]):
                if descGDB.workspaceType == "RemoteDatabase":
                    ## Use temporary SDE connection as owner
                    myGDB = arcpy.CreateDatabaseConnection_management(
                        temp_dir,  ## out_folder_path
                        owner+".sde",  ## out_name
                        "ORACLE",  ## database_platform
                        "GISTEST.WORLD",  ## instance
                        "DATABASE_AUTH",  ## account_authentication
                        owner,  ## username
                        "myuserpass",  ## password
                    )
                    print arcpy.GetMessages()

                    ## Format result object as string for path to connection file
                    myGDB = str(myGDB)

                # Get unused domains for current owner
                domainsUnused_currentOwner = [
                    dom.name for dom in domainsUnused
                    if dom.owner == owner
                ]
                for domain in domainsUnused_currentOwner:
                    arcpy.DeleteDomain_management(myGDB, domain)
                    print "\t{} deleted".format(domain)
            ## end for domainsExisting_owners
        ## end with temp_dir

    finally:
        # Cleanup
        arcpy.ClearWorkspaceCache_management()
Пример #8
0
def obliterate(group, dataIn, inputGDB=None):
    """
    Function to remove all feature classes, domain values, feature datasets,  
    & SDE tables from an Enterprise GDB.
    
    Parameter 1 = The kind of input data. 
    Parameter 2 = A list of input data. 
    Parameter 3 (Optional) = An input GDB
    """

    if group == 'feature classes':

        arcpy.AddMessage('Deleting Feature Classes')
        arcpy.AddMessage('\n')
        if not dataIn:
            arcpy.AddMessage('Empty input for feature classes')
        else:
            for el in dataIn:
                arcpy.AddMessage(el)
                arcpy.Delete_management(el)

    elif group == 'tables':

        arcpy.AddMessage('Deleting Tables')
        arcpy.AddMessage('\n')
        if not dataIn:
            arcpy.AddMessage('Empty input for tables')
        else:
            for el in dataIn:
                arcpy.AddMessage(el)
                arcpy.Delete_management(el)

    elif group == 'domains':

        arcpy.AddMessage('Deleting Domains')
        arcpy.AddMessage('\n')
        if not dataIn:
            arcpy.AddMessage('Empty input for domains')
        else:
            for el in dataIn:
                name = el.name
                arcpy.AddMessage(name)
                arcpy.DeleteDomain_management(inputGDB, name)

    elif group == 'datasets':

        arcpy.AddMessage('Deleting Datasets')
        arcpy.AddMessage('\n')
        if not dataIn:
            arcpy.AddMessage('Empty input for datasets')
        else:
            for el in dataIn:
                arcpy.AddMessage('Feature dataset: ' + el)
                # print('Feature classes:')
                # for fc in arcpy.ListFeatureClasses(feature_dataset=el):
                #     arcpy.AddMessage(fc)
                #     arcpy.Delete_management(fc)
                arcpy.Delete_management(el)

    else:

        arcpy.AddMessage('Bad input into function...')
Пример #9
0
        "UNIT['Meter',1.0]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119522E-09;0.001;0.001;"
        "IsHighPrecision", "", "0", "0", "0")
else:
    pass

#______________________________________________________________________________#
#
# Adding Survey Fields
#______________________________________________________________________________#

DomGDB = arcpy.Describe(Geodatabase)
domains = DomGDB.Domains
dmCount = len(domains)
if dmCount > 0:
    for domain in domains:
        arcpy.DeleteDomain_management(Geodatabase, domain)
else:
    pass
if CameraInput == "Associate Photo with Parcel":
    arcpy.AddMessage("Step 8:  Adding survey questions")
else:
    arcpy.AddMessage("Step 2:  Adding Survey questions")

try:
    config = ConfigParser.ConfigParser()
except NameError:
    config = configparser.ConfigParser()

config.read(config_file)

Domain1 = config.get('DOMAINS', "Domain1")
Пример #10
0
    "WHITEOAK": "WHITEOAK",
    "WILDCAT": "WILDCAT",
    "X2": "X2",
    "X4": "X4",
    "X6": "X6",
    "X7": "X7"
}

isDomain = False
#check if domain exists
desc = arcpy.Describe(gdb)
domains = desc.domains
for domain in domains:
    if domain == domName:
        # isDomain = True
        print("Domain already exists.")
        arcpy.DeleteDomain_management(gdb, domain)
        print("Domain has been deleted.")

if isDomain <> True:
    #create domain
    arcpy.CreateDomain_management(gdb, domName, domName, "TEXT", "CODED")
    print("Domain " + domName + " has been created")

    #add coded value to domain
    for code in domDict:
        arcpy.AddCodedValueToDomain_management(gdb, domName, code,
                                               domDict[code])
        print(code + ", " + domDict[code])
else:
    print("Domain already exists.")
Пример #11
0
    recreate_domain(
        workspace=workspace,
        csv_path=csv_path,
        code_field=code,
        desc_field=desc,
        domain_name= target_domain+'_1',
        old_domain_obj = old_domain_obj)

    replace_domain(
        workspace=workspace,
        old_domain=target_domain,
        new_domain=target_domain+'_1')

    arcpy.DeleteDomain_management(
        in_workspace = workspace,
        domain_name = target_domain)

    recreate_domain(
        workspace=workspace,
        csv_path=csv_path,
        code_field=code,
        desc_field=desc,
        domain_name= target_domain,
        old_domain_obj = old_domain_obj)

    replace_domain(
        workspace=workspace,
        old_domain=target_domain+'_1',
        new_domain=target_domain)
Пример #12
0
def del_all_domains():
    _domains = arcpy.da.ListDomains(get_workspace())
    for _domain in _domains:
        arcpy.DeleteDomain_management(get_workspace(), _domain.name)
        print("Domain deleted: " + _domain.name)
 def detruireDomaineAttribut(self, workspace):
 #-------------------------------------------------------------------------------------
     """
     Permet de détruire tous les domaines existants dans la Géodatabase.
     
     Paramètres:
     -----------
     workspace   : Nom de la géodatabase ou les domaines seront détruits.
     
     """
     
     #Envoyer un message
     arcpy.AddMessage(" ")
     arcpy.AddMessage("- Détruire tous les domaines existants dans les classes de la Géodatabase")
     
     #Définir le workspace par défaut
     arcpy.env.workspace = workspace
     
     #Extraire la description de la Géodatabase
     #for fc in classe.split(","):
     for fc in arcpy.ListFeatureClasses():
         #Extraire les fields
         fields = arcpy.ListFields(fc)
         
         #Traiter tous les fields
         for field in fields:
             #Vérifier la présence d'un domaine
             if len(field.domain) > 0:
                 #Vérifier si l'attribut est présent dans la liste des attribut
                 #if field.name in attribut:
                 
                 #Afficher le message
                 arcpy.AddMessage(" RemoveDomainFromField_management('" + fc + "', '" + field.name + "')")
                 
                 #Détruire un domaine dans un attribut d'une classe
                 arcpy.RemoveDomainFromField_management(fc, field.name)
     
     #Envoyer un message
     arcpy.AddMessage(" ")
     arcpy.AddMessage("- Détruire tous les domaines existants dans la Géodatabase")
     
     #Extraire la description de la Géodatabase
     desc = arcpy.Describe(workspace)
     
     #Extraire tous les domaines existants de la Géodatabase
     domains = desc.domains
     
     #Traiter tous les domaines
     for domain in domains:
         #Vérifier si c'est un domaine
         #if "DOM_" in domain:
         
         #Afficher le message
         arcpy.AddMessage(" DeleteDomain_management('" + workspace + "', '" + domain + "')")
         
         try:
             #Détruire un domaine
             arcpy.DeleteDomain_management(workspace, domain)
         #Gestion des erreurs
         except Exception, err:
             #Afficher l'erreur
             arcpy.AddWarning(err.message)
Пример #14
0
def AddRangeDomain(feature, workspace, domain_name, range_low, range_high):
    """
    Applies the range domain to the feature. Removes domain from any existing
    features if necessary.
    :param feature: a feature class
    :param workspace: the project's unique gdb
    :param domain_name: the name of the domain as a string
    :param range_low: integer or float
    :param range_high: integer or float
    :return: None
    """
    # Check for existence of domain; update domain if present, add domain if
    # not
    desc = arcpy.Describe(workspace)
    domains = desc.domains

    if domain_name in domains:
        arcpy.AddMessage(domain_name + " is already specified as a domain")
        try:
            # try removing from all fields in all feature classes
            existingFeatures = arcpy.ListFeatureClasses()
            for existingFeature in existingFeatures:
                fields = arcpy.ListFields(existingFeature)
                for field in fields:
                    if field.domain == domain_name:
                        table = os.path.join(workspace, existingFeature)
                        arcpy.RemoveDomainFromField_management(
                            table, field.name)
                        arcpy.AddMessage(domain_name +
                                         " domain removed from " +
                                         existingFeature + " " + field.name +
                                         " field")
                # try removing from all fields in all subtypes
                subtypes = arcpy.da.ListSubtypes(existingFeature)
                for stcode, stdict in list(subtypes.items()):
                    for stkey in list(stdict.keys()):
                        # if there is a Subtype Field
                        if not stdict['SubtypeField'] == '':
                            st_code = "'{}: {}'".format(stcode, stdict['Name'])
                        # if no Subtype Field, use "#" in RemoveDomainFromField
                        # for subtype_code
                        else:
                            st_code = "#"
                        if stkey == 'FieldValues':
                            fields = stdict[stkey]
                            for field, fieldvals in list(fields.items()):
                                # if field has a domain
                                if not fieldvals[1] is None:
                                    # and the domain is in our list
                                    if fieldvals[1].name == domain_name:
                                        # remove the domain
                                        arcpy.AddMessage(fieldvals[1].name +
                                                         " domain removed " +
                                                         "from " +
                                                         existingFeature +
                                                         " field: " + field +
                                                         " subtype: " +
                                                         st_code)
                                        arcpy.RemoveDomainFromField_management(
                                            existingFeature, field, st_code)
            arcpy.DeleteDomain_management(workspace, domain_name)
            arcpy.CreateDomain_management(workspace, domain_name,
                                          domain_name + " must be integer",
                                          "SHORT", "RANGE")
            arcpy.SetValueForRangeDomain_management(workspace, domain_name,
                                                    range_low, range_high)
            arcpy.AssignDomainToField_management(feature, domain_name,
                                                 domain_name)
            arcpy.AddMessage(domain_name + " domain updated")
        except arcpy.ExecuteError:
            arcpy.AddMessage(domain_name + " domain could not be updated")
    else:
        arcpy.CreateDomain_management(workspace, domain_name,
                                      domain_name + " must be integer",
                                      "SHORT", "RANGE")
        arcpy.SetValueForRangeDomain_management(workspace, domain_name,
                                                range_low, range_high)
        arcpy.AssignDomainToField_management(feature, domain_name, domain_name)
        arcpy.AddMessage(domain_name + " domain updated")
Пример #15
0
def AddCodedTextDomain(feature_list,
                       workspace,
                       domain_name,
                       code_list,
                       assign_default=False,
                       populate_default=False):
    """
    Applies the code_list as a domain to the list of feature classes.
    Domain must be the same as the field name to which it is being applied.
    :param feature_list: list of feature classes
    :param workspace: the project's unique gdb
    :param domain_name: name of the domain as a string, must be same as name
    of field to which it is applied
    :param code_list: list of codes as strings
    :param assign_default: True to assign the first code in the code_list as
    default
    :param populate_default: True to populate existing features with the
    default code
    :return: None
    """
    # Create unique list from provided
    uniqueCodes = []
    for code in code_list:
        if code not in uniqueCodes:
            uniqueCodes.append(code)
    # Check for existence of domain; update domain if present, add domain if not
    desc = arcpy.Describe(workspace)
    domains = desc.domains
    if domain_name in domains:
        arcpy.AddMessage(domain_name + " is already specified as a domain")
        try:
            # try removing from all fields in all feature classes
            existingFeatures = arcpy.ListFeatureClasses()
            for existingFeature in existingFeatures:
                fields = arcpy.ListFields(existingFeature)
                for field in fields:
                    if field.domain == domain_name:
                        arcpy.RemoveDomainFromField_management(
                            existingFeature, field.name)
                        arcpy.AddMessage(domain_name +
                                         " domain removed from " +
                                         existingFeature + " " + field.name +
                                         " field")
                # try removing from all fields in all subtypes
                # Credit to:(https://community.esri.com/thread/
                # 198384-how-to-remove-domain-from-field-for-gdb)
                subtypes = arcpy.da.ListSubtypes(existingFeature)
                for stcode, stdict in list(subtypes.items()):
                    for stkey in list(stdict.keys()):
                        # if there is a Subtype Field
                        if not stdict['SubtypeField'] == '':
                            st_code = "'{}: {}'".format(stcode, stdict['Name'])
                        # if no Subtype Field, use "#" in RemoveDomainFromField
                        # for subtype_code
                        else:
                            st_code = "#"
                        if stkey == 'FieldValues':
                            fields = stdict[stkey]
                            for field, fieldvals in list(fields.items()):
                                # if field has a domain
                                if not fieldvals[1] is None:
                                    # and the domain is in our list
                                    if fieldvals[1].name == domain_name:
                                        # remove the domain
                                        arcpy.AddMessage(fieldvals[1].name +
                                                         " domain removed " +
                                                         "from " +
                                                         existingFeature +
                                                         " field: " + field +
                                                         " subtype: " +
                                                         st_code)
                                        arcpy.RemoveDomainFromField_management(
                                            existingFeature, field, st_code)

            arcpy.DeleteDomain_management(workspace, domain_name)
            arcpy.CreateDomain_management(workspace, domain_name,
                                          "Valid " + domain_name + "s", "TEXT",
                                          "CODED")

            for code in uniqueCodes:
                arcpy.AddCodedValueToDomain_management(workspace, domain_name,
                                                       code, code)
            for feature in feature_list:
                try:
                    arcpy.AssignDomainToField_management(
                        feature, domain_name, domain_name)
                    # Check to make sure subtypes exist
                    subtypes = arcpy.da.ListSubtypes(feature)
                    if len(subtypes
                           ) == 1 and subtypes[0]['SubtypeField'] == '':
                        pass
                    else:
                        st_codes = [
                            str(stcode)
                            for stcode, stdict in list(subtypes.items())
                        ]
                        arcpy.AssignDomainToField_management(
                            feature, domain_name, domain_name, st_codes)

                except arcpy.ExecuteError:
                    arcpy.AddMessage("--------------------------------"
                                     "\n" + domain_name +
                                     " domain for feature \n\n" +
                                     str(feature) + "\n\n" +
                                     "could not be updated. Use "
                                     "caution when populating attribute\n"
                                     "---------------------------------")
            arcpy.AddMessage(domain_name + " domain updated")

        except arcpy.ExecuteError:
            arcpy.AddMessage(domain_name + " domain could not be updated. Use "
                             "caution when populating attribute")
    else:
        arcpy.CreateDomain_management(workspace, domain_name,
                                      "Valid " + domain_name + "s", "TEXT",
                                      "CODED")
        for code in uniqueCodes:
            arcpy.AddCodedValueToDomain_management(workspace, domain_name,
                                                   code, code)
        for feature in feature_list:
            try:
                arcpy.AssignDomainToField_management(feature, domain_name,
                                                     domain_name)
                # Check to make sure subtypes exist
                subtypes = arcpy.da.ListSubtypes(feature)
                if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
                    pass
                else:
                    st_codes = [
                        str(stcode)
                        for stcode, stdict in list(subtypes.items())
                    ]
                    arcpy.AssignDomainToField_management(
                        feature, domain_name, domain_name, st_codes)

            except arcpy.ExecuteError:
                arcpy.AddMessage(domain_name +
                                 " domain could not be updated. Use "
                                 "caution when populating attribute")

        arcpy.AddMessage(domain_name + " domain updated")

    # Assign the first value as the default
    if assign_default:
        for feature in feature_list:
            subtypes = arcpy.da.ListSubtypes(feature)
            if len(subtypes) == 1 and subtypes[0]['SubtypeField'] == '':
                arcpy.AssignDefaultToField_management(feature, domain_name,
                                                      uniqueCodes[0])
            else:
                st_codes = [
                    str(stcode) for stcode, stdict in list(subtypes.items())
                ]
                arcpy.AssignDefaultToField_management(feature, domain_name,
                                                      uniqueCodes[0], st_codes)

    # Populate field with default values if Null
    if populate_default:
        arcpy.AddMessage("Populating default values")
        for feature in feature_list:
            where_clause = "{0} = '' OR {0} IS NULL".format(
                arcpy.AddFieldDelimiters(feature, domain_name))
            with arcpy.da.UpdateCursor(feature, domain_name,
                                       where_clause) as cursor:
                for row in cursor:
                    row[0] = uniqueCodes[0]
                    cursor.updateRow(row)
def mainFunction(
    geodatabase, configFile
):  # Get parameters from ArcGIS Desktop tool by seperating by comma e.g. (var1 is 1st parameter,var2 is 2nd parameter,var3 is 3rd parameter)
    try:
        # Logging
        if (enableLogging == "true"):
            # Setup logging
            logger, logMessage = setLogging(logFile)
            # Log start of process
            logger.info("Process started.")

        # --------------------------------------- Start of code --------------------------------------- #

        # Get a list of assigned domains
        assignedDomains = []

        # Get a list of the feature datasets in the database
        arcpy.env.workspace = geodatabase
        featureDatasetList = arcpy.ListDatasets("", "Feature")
        # FUNCTION - Get the domains for these feature datasets
        assignedDomains = assignedDomains + getDomains(
            geodatabase, featureDatasetList, configFile, "Feature Dataset")

        # Get a list of the feature classes in the database
        featureClassList = arcpy.ListFeatureClasses()
        # FUNCTION - Get the domains for these feature calsses
        assignedDomains = assignedDomains + getDomains(
            geodatabase, featureClassList, configFile, "Feature Class")

        # Get a list of the tables in the database
        mosaicList = arcpy.ListDatasets("", "Mosaic")
        # FUNCTION - Get the domains for these tables
        assignedDomains = assignedDomains + getDomains(geodatabase, mosaicList,
                                                       configFile, "Mosaic")

        # Get a list of mosaic rasters in the database
        tableList = arcpy.ListTables()
        # FUNCTION - Get the domains for these tables
        assignedDomains = assignedDomains + getDomains(
            geodatabase, featureClassList, configFile, "Table")

        # Get a list of domains on the geodatabase
        geodatabaseDomains = arcpy.da.ListDomains(geodatabase)
        # For each of the domains
        for domain in geodatabaseDomains:
            usedDomainCount = 0
            # Check it is being used by looking at the assigned domains list
            for assignedDomain in assignedDomains:
                if (domain.name == assignedDomain):
                    usedDomainCount = usedDomainCount + 1

            # If domain is not being used
            if (usedDomainCount == 0):
                # Don't remove domains on wcc_encroachments feature class (Wellington City Council) as there are subtypes and it's causing issues in this script
                if ("Encroach" not in domain.name):
                    # Remove the domain from the geodatabase
                    arcpy.AddMessage("Removing domain " + domain.name +
                                     " as not being used...")
                    # Logging
                    if (enableLogging == "true"):
                        logger.info("Removing domain " + domain.name +
                                    " as not being used...")
                    arcpy.DeleteDomain_management(geodatabase, domain.name)

        # --------------------------------------- End of code --------------------------------------- #

        # If called from gp tool return the arcpy parameter
        if __name__ == '__main__':
            # Return the output if there is any
            if output:
                arcpy.SetParameterAsText(1, output)
        # Otherwise return the result
        else:
            # Return the output if there is any
            if output:
                return output
        # Logging
        if (enableLogging == "true"):
            # Log end of process
            logger.info("Process ended.")
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        pass
    # If arcpy error
    except arcpy.ExecuteError:
        # Build and show the error message
        errorMessage = arcpy.GetMessages(2)
        arcpy.AddError(errorMessage)
        # Logging
        if (enableLogging == "true"):
            # Log error
            logger.error(errorMessage)
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)
    # If python error
    except Exception as e:
        errorMessage = ""
        # Build and show the error message
        for i in range(len(e.args)):
            if (i == 0):
                errorMessage = str(e.args[i])
            else:
                errorMessage = errorMessage + " " + str(e.args[i])
        arcpy.AddError(errorMessage)
        # Logging
        if (enableLogging == "true"):
            # Log error
            logger.error(errorMessage)
            # Remove file handler and close log file
            logging.FileHandler.close(logMessage)
            logger.removeHandler(logMessage)
        if (sendErrorEmail == "true"):
            # Send email
            sendEmail(errorMessage)