Skip to content

Domain

CLASS DESCRIPTION
CodedValueDomain

Domain with a CodedValue component

Domain

General Domain object

RangeDomain

Domain with a Range component

BaseDomain

BaseDomain(
    wrapped: Domain, workspace: str | Path | Dataset
)

Base class for interacting with Domains.

General setup structure is pulled from pathlib.Path since

METHOD DESCRIPTION
sync

Sync the domain with the workspace

Source code in src/arcpie/schema/domain.py
133
134
135
136
137
138
139
140
141
def __init__(self, wrapped: da.Domain, workspace: str | Path | Dataset) -> None:
    from ..database import Dataset
    self._domain = wrapped
    if not isinstance(workspace, Dataset):
        self.dataset = Dataset(workspace)
        self.workspace = str(workspace)
    else:
        self.dataset = workspace
        self.workspace = str(workspace)

sync

sync() -> None

Sync the domain with the workspace

Source code in src/arcpie/schema/domain.py
143
144
145
146
147
148
def sync(self) -> None:
    """Sync the domain with the workspace"""
    matches = [d for d in da.ListDomains(self.workspace) if d.name == self.name]
    if not matches:
        raise LookupError(f'Domain {self.name} no longer exists in the parent workspace {self.workspace}')
    self._domain = matches.pop()

CodedValueDomain

CodedValueDomain(
    wrapped: Domain, workspace: str | Path | Dataset
)

Bases: Domain

Domain with a CodedValue component

METHOD DESCRIPTION
add_to

Add the domain to a root workspace/Dataset

assign_to

Assign the domain to a Field

create

Create a new domain

delete

Delete the domain

from_dict

Create a Domain object from a system domain definition

from_table

Create a CodedValue domain from a Table

sync

Sync the domain with the workspace

to_dict

Use with json.dump/dumps

to_table

Convert the domain to a Table in its workspace

used_by

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
133
134
135
136
137
138
139
140
141
def __init__(self, wrapped: da.Domain, workspace: str | Path | Dataset) -> None:
    from ..database import Dataset
    self._domain = wrapped
    if not isinstance(workspace, Dataset):
        self.dataset = Dataset(workspace)
        self.workspace = str(workspace)
    else:
        self.dataset = workspace
        self.workspace = str(workspace)

add_to

add_to(workspace: Dataset) -> None

Add the domain to a root workspace/Dataset

Source code in src/arcpie/schema/domain.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def add_to(self, workspace: Dataset) -> None:
    """Add the domain to a root workspace/Dataset"""
    if workspace.parent is not None:
        raise ValueError(f'Domains can only be added to the root Dataset!')
    CreateDomain(
        in_workspace=str(workspace.conn.resolve()), 
        domain_name=self.name, 
        domain_description=self.description,
        field_type=_DOMAIN_FIELD_TYPE_MAP[self.type],
        domain_type=_DOMAIN_TYPE_MAP[self.domainType],
        split_policy=_DOMAIN_SPLIT_POLICY_MAP[self.splitPolicy],
        merge_policy=_DOMAIN_MERGE_POLICY_MAP[self.mergePolicy],
    )
    if isinstance(self, CodedValueDomain):
        for code, value in self.codedValues.items():
            AddCodedValueToDomain(str(workspace), self.name, code, value)
    if isinstance(self, RangeDomain):
        SetValueForRangeDomain(str(workspace), self.name, *self.range)

assign_to

assign_to(
    table: Table | FeatureClass,
    field: str,
    *,
    subtype_code: int | None = None,
) -> None

Assign the domain to a Field

PARAMETER DESCRIPTION

table

The table to apply the domain to

TYPE: Table | FeatureClass

field

The field in the table to apply the domain to

TYPE: str

subtype_code

An optional subtype to apply the domain to

TYPE: int | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def assign_to(self, table: Table | FeatureClass, field: str,
             *,
             subtype_code: int | None = None,
             ) -> None:
    """Assign the domain to a Field

    Args:
        table: The table to apply the domain to
        field: The field in the table to apply the domain to
        subtype_code: An optional subtype to apply the domain to
    """
    field_info = table.field_defs.get(field)
    if not field_info:
        raise ValueError(f'{table.name}: {field} not found!')
    if field_info.get('field_type') not in VALID_FIELD_TYPES_FOR.get(self.type, set()):
        msg = (
            f'Domain of type {self.type} cannot be assigned to '
            f'field {field} of type {field_info.get('field_type')}'
        )
        raise ValueError(msg)

    AssignDomainToField(
        in_table=str(table),
        field_name=field,
        domain_name=self.name,
        subtype_code=subtype_code,
    )

create classmethod

create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["CodedValue"],
    field_type: DomainFieldType,
    coded_values: CodedValues,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> CodedValueDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["Range"],
    field_type: DomainFieldType,
    domain_range: RangeValue,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> RangeDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: DomainType,
    field_type: DomainFieldType,
    description: str = "",
    split_policy: SplitPolicy = "Duplicate",
    merge_policy: MergePolicy = "DefaultValue",
    domain_range: RangeValue | None = None,
    coded_values: CodedValues | None = None,
) -> CodedValueDomain | RangeDomain

Create a new domain

Source code in src/arcpie/schema/domain.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@classmethod
def create(cls, workspace: str, name: str, 
           *,
           domain_type: DomainType,
           field_type: DomainFieldType,
           description: str = '', 
           split_policy: SplitPolicy = 'Duplicate',
           merge_policy: MergePolicy = 'DefaultValue',

           # Required by overload
           domain_range: RangeValue | None = None,
           coded_values: CodedValues | None = None) -> CodedValueDomain | RangeDomain:
    """Create a new domain"""
    assert domain_type in ['CodedValue', 'Range'], f'Invalid domain type {domain_type}'

    CreateDomain(
        in_workspace=workspace,
        domain_name=name,
        domain_description=description,
        field_type=_DOMAIN_FIELD_TYPE_MAP.get(field_type),
        domain_type=_DOMAIN_TYPE_MAP.get(domain_type),
        split_policy=_DOMAIN_SPLIT_POLICY_MAP.get(split_policy),
        merge_policy=_DOMAIN_MERGE_POLICY_MAP.get(merge_policy),
    )
    new_domain, *_ = [d for d in da.ListDomains(workspace) if d.name == name] or [None]
    if new_domain is None:
        raise ValueError(f'Something went wrong creating the Domain...')
    if domain_type == 'CodedValue':
        domain = CodedValueDomain(new_domain, workspace)
        if coded_values:
            domain.codedValues = {k: v for k, v in coded_values.items()}
        return domain
    elif domain_type == 'Range':
        domain = RangeDomain(new_domain, workspace)
        if domain_range:
            domain.range = domain_range
        return domain

delete

delete() -> None

Delete the domain

Source code in src/arcpie/schema/domain.py
267
268
269
def delete(self) -> None:
    """Delete the domain"""
    DeleteDomain(self.workspace, self.name)

from_dict classmethod

from_dict(
    definition: SystemDomain, workspace: str | None = None
) -> Domain

Create a Domain object from a system domain definition

Source code in src/arcpie/schema/domain.py
439
440
441
442
443
@classmethod
def from_dict(cls, definition: SystemDomain, workspace: str| None = None) -> Domain:
    """Create a Domain object from a system domain definition"""
    dom: da.Domain = type(f'__domain', (object,), {k: v for k,v in definition.items()})
    return cls(dom, workspace)

from_table classmethod

Create a CodedValue domain from a Table

PARAMETER DESCRIPTION

table

The table or featureclass to create the domain from

TYPE: FeatureClass | Table

name

The name of the domain

TYPE: str

code_field

The field to use for codes

TYPE: str

description_field

The field to use for descriptions

TYPE: str

workspace

The workspace to create the domain in (default: table.workspace)

TYPE: str | None DEFAULT: None

description

An optional description for the new domain

TYPE: str | None

overwrite_existing

If set to True, any existing domains with the name will be replaced,
otherwise new values are appended to the existing domain

TYPE: bool DEFAULT: False

Source code in src/arcpie/schema/domain.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@classmethod
def from_table(cls, table: FeatureClass | Table, name: str,
               *,
               code_field: str,
               description_field: str,
               workspace: str | None = None,
               description: str | None,
               overwrite_existing: bool = False,
               ) -> CodedValueDomain:
    """Create a CodedValue domain from a Table

    Args:
        table: The table or featureclass to create the domain from
        name: The name of the domain
        code_field: The field to use for codes
        description_field: The field to use for descriptions
        workspace: The workspace to create the domain in (default: table.workspace)
        description: An optional description for the new domain
        overwrite_existing: If set to `True`, any existing domains with the name will be replaced,<br> 
            otherwise new values are appended to the existing domain
    """
    if code_field not in table.fields or description_field not in table.fields:
        msg = (
            f'Invalid {code_field} or {description_field} not in table fields, '
            f'must be one of {table.fields}'
        )
        raise ValueError(msg)

    workspace = workspace or table.workspace
    TableToDomain(
        in_table=str(table),
        code_field=code_field,
        description_field=description_field,
        in_workspace=workspace or table.workspace,
        domain_name=name,
        domain_description=description,
        update_option='REPLACE' if overwrite_existing else 'APPEND'
    )
    return CodedValueDomain([d for d in da.ListDomains(workspace) if d.name == name].pop(), workspace)

sync

sync() -> None

Sync the domain with the workspace

Source code in src/arcpie/schema/domain.py
143
144
145
146
147
148
def sync(self) -> None:
    """Sync the domain with the workspace"""
    matches = [d for d in da.ListDomains(self.workspace) if d.name == self.name]
    if not matches:
        raise LookupError(f'Domain {self.name} no longer exists in the parent workspace {self.workspace}')
    self._domain = matches.pop()

to_dict

to_dict() -> DomainSchema

Use with json.dump/dumps

Source code in src/arcpie/schema/domain.py
221
222
223
224
225
226
227
228
229
230
231
232
233
def to_dict(self) -> DomainSchema:
    """Use with json.dump/dumps"""
    return {
        'name': self.name,
        'domainType': self.domainType,
        'type': self.type,
        'description': self.description,
        'codedValues': self.codedValues,
        'range': self.range,
        'mergePolicy': self.mergePolicy,
        'splitPolicy': self.splitPolicy,
        'owner': self.owner,
    }

to_table

to_table(
    table_name: str,
    *,
    code_field: str = "code",
    description_field: str = "description",
    configuration_keyword: str | None = None,
) -> Table

Convert the domain to a Table in its workspace

PARAMETER DESCRIPTION

table_name

The name of the output table

TYPE: str

code_field

The field name for the codes

TYPE: str DEFAULT: 'code'

description_field

The field name for the descriptions

TYPE: str DEFAULT: 'description'

configuration_keyword

An optional config keyword for the database

TYPE: str | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def to_table(self, table_name: str, 
             *,
             code_field: str = 'code',
             description_field: str = 'description',
             configuration_keyword: str | None = None
             ) -> Table:
    """Convert the domain to a Table in its workspace

    Args:
        table_name: The name of the output table
        code_field: The field name for the codes
        description_field: The field name for the descriptions
        configuration_keyword: An optional config keyword for the database
    """
    if self.domainType != 'CodedValue':
        raise TypeError(f'Only `CodedValue` domains can be converted to a table')
    return Table(
        *DomainToTable(
            in_workspace=self.workspace, 
            domain_name=self.name, 
            out_table=table_name,
            code_field=code_field,
            description_field=description_field,
            configuration_keyword=configuration_keyword,
        )
    )

used_by

used_by() -> FieldUsage

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
235
236
237
def used_by(self) -> FieldUsage:
    """Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain"""
    return self.dataset.domains.usage(self.name)[self.name]

Domain

Domain(wrapped: Domain, workspace: str | Path | Dataset)

Bases: BaseDomain

General Domain object

METHOD DESCRIPTION
add_to

Add the domain to a root workspace/Dataset

assign_to

Assign the domain to a Field

create

Create a new domain

delete

Delete the domain

from_dict

Create a Domain object from a system domain definition

from_table

Create a CodedValue domain from a Table

sort

CodedValue Only

sync

Sync the domain with the workspace

to_dict

Use with json.dump/dumps

to_table

Convert the domain to a Table in its workspace

used_by

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
133
134
135
136
137
138
139
140
141
def __init__(self, wrapped: da.Domain, workspace: str | Path | Dataset) -> None:
    from ..database import Dataset
    self._domain = wrapped
    if not isinstance(workspace, Dataset):
        self.dataset = Dataset(workspace)
        self.workspace = str(workspace)
    else:
        self.dataset = workspace
        self.workspace = str(workspace)

add_to

add_to(workspace: Dataset) -> None

Add the domain to a root workspace/Dataset

Source code in src/arcpie/schema/domain.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def add_to(self, workspace: Dataset) -> None:
    """Add the domain to a root workspace/Dataset"""
    if workspace.parent is not None:
        raise ValueError(f'Domains can only be added to the root Dataset!')
    CreateDomain(
        in_workspace=str(workspace.conn.resolve()), 
        domain_name=self.name, 
        domain_description=self.description,
        field_type=_DOMAIN_FIELD_TYPE_MAP[self.type],
        domain_type=_DOMAIN_TYPE_MAP[self.domainType],
        split_policy=_DOMAIN_SPLIT_POLICY_MAP[self.splitPolicy],
        merge_policy=_DOMAIN_MERGE_POLICY_MAP[self.mergePolicy],
    )
    if isinstance(self, CodedValueDomain):
        for code, value in self.codedValues.items():
            AddCodedValueToDomain(str(workspace), self.name, code, value)
    if isinstance(self, RangeDomain):
        SetValueForRangeDomain(str(workspace), self.name, *self.range)

assign_to

assign_to(
    table: Table | FeatureClass,
    field: str,
    *,
    subtype_code: int | None = None,
) -> None

Assign the domain to a Field

PARAMETER DESCRIPTION

table

The table to apply the domain to

TYPE: Table | FeatureClass

field

The field in the table to apply the domain to

TYPE: str

subtype_code

An optional subtype to apply the domain to

TYPE: int | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def assign_to(self, table: Table | FeatureClass, field: str,
             *,
             subtype_code: int | None = None,
             ) -> None:
    """Assign the domain to a Field

    Args:
        table: The table to apply the domain to
        field: The field in the table to apply the domain to
        subtype_code: An optional subtype to apply the domain to
    """
    field_info = table.field_defs.get(field)
    if not field_info:
        raise ValueError(f'{table.name}: {field} not found!')
    if field_info.get('field_type') not in VALID_FIELD_TYPES_FOR.get(self.type, set()):
        msg = (
            f'Domain of type {self.type} cannot be assigned to '
            f'field {field} of type {field_info.get('field_type')}'
        )
        raise ValueError(msg)

    AssignDomainToField(
        in_table=str(table),
        field_name=field,
        domain_name=self.name,
        subtype_code=subtype_code,
    )

create classmethod

create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["CodedValue"],
    field_type: DomainFieldType,
    coded_values: CodedValues,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> CodedValueDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["Range"],
    field_type: DomainFieldType,
    domain_range: RangeValue,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> RangeDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: DomainType,
    field_type: DomainFieldType,
    description: str = "",
    split_policy: SplitPolicy = "Duplicate",
    merge_policy: MergePolicy = "DefaultValue",
    domain_range: RangeValue | None = None,
    coded_values: CodedValues | None = None,
) -> CodedValueDomain | RangeDomain

Create a new domain

Source code in src/arcpie/schema/domain.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@classmethod
def create(cls, workspace: str, name: str, 
           *,
           domain_type: DomainType,
           field_type: DomainFieldType,
           description: str = '', 
           split_policy: SplitPolicy = 'Duplicate',
           merge_policy: MergePolicy = 'DefaultValue',

           # Required by overload
           domain_range: RangeValue | None = None,
           coded_values: CodedValues | None = None) -> CodedValueDomain | RangeDomain:
    """Create a new domain"""
    assert domain_type in ['CodedValue', 'Range'], f'Invalid domain type {domain_type}'

    CreateDomain(
        in_workspace=workspace,
        domain_name=name,
        domain_description=description,
        field_type=_DOMAIN_FIELD_TYPE_MAP.get(field_type),
        domain_type=_DOMAIN_TYPE_MAP.get(domain_type),
        split_policy=_DOMAIN_SPLIT_POLICY_MAP.get(split_policy),
        merge_policy=_DOMAIN_MERGE_POLICY_MAP.get(merge_policy),
    )
    new_domain, *_ = [d for d in da.ListDomains(workspace) if d.name == name] or [None]
    if new_domain is None:
        raise ValueError(f'Something went wrong creating the Domain...')
    if domain_type == 'CodedValue':
        domain = CodedValueDomain(new_domain, workspace)
        if coded_values:
            domain.codedValues = {k: v for k, v in coded_values.items()}
        return domain
    elif domain_type == 'Range':
        domain = RangeDomain(new_domain, workspace)
        if domain_range:
            domain.range = domain_range
        return domain

delete

delete() -> None

Delete the domain

Source code in src/arcpie/schema/domain.py
267
268
269
def delete(self) -> None:
    """Delete the domain"""
    DeleteDomain(self.workspace, self.name)

from_dict classmethod

from_dict(
    definition: SystemDomain, workspace: str | None = None
) -> Domain

Create a Domain object from a system domain definition

Source code in src/arcpie/schema/domain.py
439
440
441
442
443
@classmethod
def from_dict(cls, definition: SystemDomain, workspace: str| None = None) -> Domain:
    """Create a Domain object from a system domain definition"""
    dom: da.Domain = type(f'__domain', (object,), {k: v for k,v in definition.items()})
    return cls(dom, workspace)

from_table classmethod

Create a CodedValue domain from a Table

PARAMETER DESCRIPTION

table

The table or featureclass to create the domain from

TYPE: FeatureClass | Table

name

The name of the domain

TYPE: str

code_field

The field to use for codes

TYPE: str

description_field

The field to use for descriptions

TYPE: str

workspace

The workspace to create the domain in (default: table.workspace)

TYPE: str | None DEFAULT: None

description

An optional description for the new domain

TYPE: str | None

overwrite_existing

If set to True, any existing domains with the name will be replaced,
otherwise new values are appended to the existing domain

TYPE: bool DEFAULT: False

Source code in src/arcpie/schema/domain.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@classmethod
def from_table(cls, table: FeatureClass | Table, name: str,
               *,
               code_field: str,
               description_field: str,
               workspace: str | None = None,
               description: str | None,
               overwrite_existing: bool = False,
               ) -> CodedValueDomain:
    """Create a CodedValue domain from a Table

    Args:
        table: The table or featureclass to create the domain from
        name: The name of the domain
        code_field: The field to use for codes
        description_field: The field to use for descriptions
        workspace: The workspace to create the domain in (default: table.workspace)
        description: An optional description for the new domain
        overwrite_existing: If set to `True`, any existing domains with the name will be replaced,<br> 
            otherwise new values are appended to the existing domain
    """
    if code_field not in table.fields or description_field not in table.fields:
        msg = (
            f'Invalid {code_field} or {description_field} not in table fields, '
            f'must be one of {table.fields}'
        )
        raise ValueError(msg)

    workspace = workspace or table.workspace
    TableToDomain(
        in_table=str(table),
        code_field=code_field,
        description_field=description_field,
        in_workspace=workspace or table.workspace,
        domain_name=name,
        domain_description=description,
        update_option='REPLACE' if overwrite_existing else 'APPEND'
    )
    return CodedValueDomain([d for d in da.ListDomains(workspace) if d.name == name].pop(), workspace)

sort

sort(
    by: Literal["code", "value"],
    order: Literal["asc", "desc"],
) -> None

CodedValue Only

Source code in src/arcpie/schema/domain.py
333
334
def sort(self, by: Literal['code', 'value'], order: Literal['asc', 'desc']) -> None:
    """CodedValue Only"""

sync

sync() -> None

Sync the domain with the workspace

Source code in src/arcpie/schema/domain.py
143
144
145
146
147
148
def sync(self) -> None:
    """Sync the domain with the workspace"""
    matches = [d for d in da.ListDomains(self.workspace) if d.name == self.name]
    if not matches:
        raise LookupError(f'Domain {self.name} no longer exists in the parent workspace {self.workspace}')
    self._domain = matches.pop()

to_dict

to_dict() -> DomainSchema

Use with json.dump/dumps

Source code in src/arcpie/schema/domain.py
221
222
223
224
225
226
227
228
229
230
231
232
233
def to_dict(self) -> DomainSchema:
    """Use with json.dump/dumps"""
    return {
        'name': self.name,
        'domainType': self.domainType,
        'type': self.type,
        'description': self.description,
        'codedValues': self.codedValues,
        'range': self.range,
        'mergePolicy': self.mergePolicy,
        'splitPolicy': self.splitPolicy,
        'owner': self.owner,
    }

to_table

to_table(
    table_name: str,
    *,
    code_field: str = "code",
    description_field: str = "description",
    configuration_keyword: str | None = None,
) -> Table

Convert the domain to a Table in its workspace

PARAMETER DESCRIPTION

table_name

The name of the output table

TYPE: str

code_field

The field name for the codes

TYPE: str DEFAULT: 'code'

description_field

The field name for the descriptions

TYPE: str DEFAULT: 'description'

configuration_keyword

An optional config keyword for the database

TYPE: str | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def to_table(self, table_name: str, 
             *,
             code_field: str = 'code',
             description_field: str = 'description',
             configuration_keyword: str | None = None
             ) -> Table:
    """Convert the domain to a Table in its workspace

    Args:
        table_name: The name of the output table
        code_field: The field name for the codes
        description_field: The field name for the descriptions
        configuration_keyword: An optional config keyword for the database
    """
    if self.domainType != 'CodedValue':
        raise TypeError(f'Only `CodedValue` domains can be converted to a table')
    return Table(
        *DomainToTable(
            in_workspace=self.workspace, 
            domain_name=self.name, 
            out_table=table_name,
            code_field=code_field,
            description_field=description_field,
            configuration_keyword=configuration_keyword,
        )
    )

used_by

used_by() -> FieldUsage

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
235
236
237
def used_by(self) -> FieldUsage:
    """Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain"""
    return self.dataset.domains.usage(self.name)[self.name]

DomainManager

DomainManager(dataset: Dataset[Any])

Container for managing dataset domains

METHOD DESCRIPTION
export_module

Export the workspace domain to a Python module that contains literals and dictionary mappings.

import_domains

Import domains from a domain mapping (DOMAINS global in exported module)

to_dict

Use with json.dump/dumps

usage

A mapping of domains to features to fields that shows usage of a domain in a dataset

Source code in src/arcpie/schema/domain.py
533
534
535
536
537
def __init__(self, dataset: Dataset[Any]) -> None:
    if dataset.parent is not None:
        dataset = dataset.parent
    self.dataset = dataset
    self.workspace = str(dataset)

export_module

export_module(path: str | Path) -> None

Export the workspace domain to a Python module that contains literals and dictionary mappings.

PARAMETER DESCRIPTION

path

The export path to the module file

TYPE: str | Path

Source code in src/arcpie/schema/domain.py
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
def export_module(self, path: str | Path) -> None:
    """Export the workspace domain to a Python module that contains literals and dictionary mappings.

    Args:
        path: The export path to the module file
    """

    path = Path(path)
    _domains = self.to_dict()

    if not path.suffix.endswith('.py'):
        path = (path / 'domains.py')

    path.parent.mkdir(exist_ok=True, parents=True)

    def _(val: Any) -> str:
        if val is None:
            return 'None'
        return repr(val)

    with path.open('wt', encoding='utf-8') as fl:
        fl.write(f'"""{self.dataset.name} domains module"""')
        fl.write('\n\n')
        fl.write('from typing import Literal, TYPE_CHECKING')
        fl.write('\n\n')
        fl.write('if TYPE_CHECKING:\n')
        fl.write('    from arcpie._types import SystemDomain\n')
        fl.write('else:\n')
        fl.write('    SystemDomain = None\n')
        fl.write('\n\n')
        fl.write('DomainName = Literal[\n')
        for domain in _domains:
            fl.write(f"\n    '{domain}',")
        fl.write('\n]\n\n')
        fl.write('DOMAINS: dict[DomainName, SystemDomain] = {')
        for domain, domain_val in _domains.items():
            fl.write("\n"f"    '{domain}': ""{")
            fl.write(f"\n        'name': {_(domain_val['name'])},")
            fl.write(f"\n        'domainType': {_(domain_val['domainType'])},")
            fl.write("\n        'codedValues': {\n")
            if domain_val['codedValues']:
                fl.write('            ')
                fl.write('\n            '.join(f"'{k}': '{v}'," for k, v in domain_val['codedValues'].items()))
                fl.write('\n        },')
            else:
                fl.write('},')
            fl.write(f"\n        'range': {_(domain_val['range'])},")
            fl.write(f"\n        'type': {_(domain_val['type'])},")
            fl.write(f"\n        'description': {_(domain_val['description'])},")
            fl.write(f"\n        'splitPolicy': {_(domain_val['splitPolicy'])},")
            fl.write(f"\n        'mergePolicy': {_(domain_val['mergePolicy'])},")
            fl.write(f"\n        'owner': {_(domain_val['owner'])},")
            fl.write('\n    },')
        fl.write('\n}\n')

import_domains

import_domains(
    domains: dict[str, SystemDomain],
    *,
    overwrite: bool = False,
) -> None

Import domains from a domain mapping (DOMAINS global in exported module)

Source code in src/arcpie/schema/domain.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def import_domains(self, domains: dict[str, SystemDomain], *, overwrite: bool = False) -> None:
    """Import domains from a domain mapping (DOMAINS global in exported module)"""

    for d_name, d_vals in domains.items():
        if d_name in self:
            if overwrite:
                self[d_name].delete()
            else:
                continue
        if d_vals['domainType'] == 'CodedValue':
            dom = CodedValueDomain.from_dict(d_vals, self.workspace)       
        elif d_vals['domainType'] == 'Range':
            dom = RangeDomain.from_dict(d_vals, self.workspace)
        else:
            raise ValueError(f'Invalid domain type {d_vals["domainType"]}')
        dom.add_to(self.dataset)

to_dict

to_dict() -> dict[str, DomainSchema]

Use with json.dump/dumps

Source code in src/arcpie/schema/domain.py
623
624
625
def to_dict(self) -> dict[str, DomainSchema]:
    """Use with json.dump/dumps"""
    return {d.name: d.to_dict() for d in self.domains}

usage

usage(*domain_names: str) -> DomainUsageMap

A mapping of domains to features to fields that shows usage of a domain in a dataset

PARAMETER DESCRIPTION

*domain_names

Varargs of all domain names to include in the output mapping

TYPE: str DEFAULT: ()

RETURNS DESCRIPTION
DomainUsageMap

A Nested mapping of Domain Name -> Feature Class -> [Field Name, ...]

Source code in src/arcpie/schema/domain.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
def usage(self, *domain_names: str) -> DomainUsageMap:
    """A mapping of domains to features to fields that shows usage of a domain in a dataset

    Args:
        *domain_names: Varargs of all domain names to include in the output mapping

    Returns:
        A Nested mapping of `Domain Name -> Feature Class -> [Field Name, ...]`
    """

    if not domain_names:
        domain_names = tuple(self.domain_names)

    schema = self.dataset.schema
    fc_usage: DomainUsageMap = {}
    for dataset in schema['datasets']:
        features = dataset.get('datasets') or [dataset]
        for feature in features:
            if 'fields' not in feature:
                continue
            for field in feature['fields']['fieldArray']:
                if 'domain' not in field:
                    continue
                field_domain = field['domain']['domainName']
                fc_usage.setdefault(field_domain, {})
                if field_domain in domain_names:
                    fc_usage[field_domain].setdefault(feature['name'], [])
                    fc_usage[field_domain][feature['name']].append(field.get('name', '...'))
    return fc_usage

RangeDomain

RangeDomain(
    wrapped: Domain, workspace: str | Path | Dataset
)

Bases: Domain

Domain with a Range component

METHOD DESCRIPTION
add_to

Add the domain to a root workspace/Dataset

assign_to

Assign the domain to a Field

create

Create a new domain

delete

Delete the domain

from_dict

Create a Domain object from a system domain definition

from_table

Create a CodedValue domain from a Table

sort

CodedValue Only

sync

Sync the domain with the workspace

to_dict

Use with json.dump/dumps

to_table

Convert the domain to a Table in its workspace

used_by

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
133
134
135
136
137
138
139
140
141
def __init__(self, wrapped: da.Domain, workspace: str | Path | Dataset) -> None:
    from ..database import Dataset
    self._domain = wrapped
    if not isinstance(workspace, Dataset):
        self.dataset = Dataset(workspace)
        self.workspace = str(workspace)
    else:
        self.dataset = workspace
        self.workspace = str(workspace)

add_to

add_to(workspace: Dataset) -> None

Add the domain to a root workspace/Dataset

Source code in src/arcpie/schema/domain.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
def add_to(self, workspace: Dataset) -> None:
    """Add the domain to a root workspace/Dataset"""
    if workspace.parent is not None:
        raise ValueError(f'Domains can only be added to the root Dataset!')
    CreateDomain(
        in_workspace=str(workspace.conn.resolve()), 
        domain_name=self.name, 
        domain_description=self.description,
        field_type=_DOMAIN_FIELD_TYPE_MAP[self.type],
        domain_type=_DOMAIN_TYPE_MAP[self.domainType],
        split_policy=_DOMAIN_SPLIT_POLICY_MAP[self.splitPolicy],
        merge_policy=_DOMAIN_MERGE_POLICY_MAP[self.mergePolicy],
    )
    if isinstance(self, CodedValueDomain):
        for code, value in self.codedValues.items():
            AddCodedValueToDomain(str(workspace), self.name, code, value)
    if isinstance(self, RangeDomain):
        SetValueForRangeDomain(str(workspace), self.name, *self.range)

assign_to

assign_to(
    table: Table | FeatureClass,
    field: str,
    *,
    subtype_code: int | None = None,
) -> None

Assign the domain to a Field

PARAMETER DESCRIPTION

table

The table to apply the domain to

TYPE: Table | FeatureClass

field

The field in the table to apply the domain to

TYPE: str

subtype_code

An optional subtype to apply the domain to

TYPE: int | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def assign_to(self, table: Table | FeatureClass, field: str,
             *,
             subtype_code: int | None = None,
             ) -> None:
    """Assign the domain to a Field

    Args:
        table: The table to apply the domain to
        field: The field in the table to apply the domain to
        subtype_code: An optional subtype to apply the domain to
    """
    field_info = table.field_defs.get(field)
    if not field_info:
        raise ValueError(f'{table.name}: {field} not found!')
    if field_info.get('field_type') not in VALID_FIELD_TYPES_FOR.get(self.type, set()):
        msg = (
            f'Domain of type {self.type} cannot be assigned to '
            f'field {field} of type {field_info.get('field_type')}'
        )
        raise ValueError(msg)

    AssignDomainToField(
        in_table=str(table),
        field_name=field,
        domain_name=self.name,
        subtype_code=subtype_code,
    )

create classmethod

create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["CodedValue"],
    field_type: DomainFieldType,
    coded_values: CodedValues,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> CodedValueDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: Literal["Range"],
    field_type: DomainFieldType,
    domain_range: RangeValue,
    description: str,
    split_policy: SplitPolicy = ...,
    merge_policy: MergePolicy = ...,
) -> RangeDomain
create(
    workspace: str,
    name: str,
    *,
    domain_type: DomainType,
    field_type: DomainFieldType,
    description: str = "",
    split_policy: SplitPolicy = "Duplicate",
    merge_policy: MergePolicy = "DefaultValue",
    domain_range: RangeValue | None = None,
    coded_values: CodedValues | None = None,
) -> CodedValueDomain | RangeDomain

Create a new domain

Source code in src/arcpie/schema/domain.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
@classmethod
def create(cls, workspace: str, name: str, 
           *,
           domain_type: DomainType,
           field_type: DomainFieldType,
           description: str = '', 
           split_policy: SplitPolicy = 'Duplicate',
           merge_policy: MergePolicy = 'DefaultValue',

           # Required by overload
           domain_range: RangeValue | None = None,
           coded_values: CodedValues | None = None) -> CodedValueDomain | RangeDomain:
    """Create a new domain"""
    assert domain_type in ['CodedValue', 'Range'], f'Invalid domain type {domain_type}'

    CreateDomain(
        in_workspace=workspace,
        domain_name=name,
        domain_description=description,
        field_type=_DOMAIN_FIELD_TYPE_MAP.get(field_type),
        domain_type=_DOMAIN_TYPE_MAP.get(domain_type),
        split_policy=_DOMAIN_SPLIT_POLICY_MAP.get(split_policy),
        merge_policy=_DOMAIN_MERGE_POLICY_MAP.get(merge_policy),
    )
    new_domain, *_ = [d for d in da.ListDomains(workspace) if d.name == name] or [None]
    if new_domain is None:
        raise ValueError(f'Something went wrong creating the Domain...')
    if domain_type == 'CodedValue':
        domain = CodedValueDomain(new_domain, workspace)
        if coded_values:
            domain.codedValues = {k: v for k, v in coded_values.items()}
        return domain
    elif domain_type == 'Range':
        domain = RangeDomain(new_domain, workspace)
        if domain_range:
            domain.range = domain_range
        return domain

delete

delete() -> None

Delete the domain

Source code in src/arcpie/schema/domain.py
267
268
269
def delete(self) -> None:
    """Delete the domain"""
    DeleteDomain(self.workspace, self.name)

from_dict classmethod

from_dict(
    definition: SystemDomain, workspace: str | None = None
) -> Domain

Create a Domain object from a system domain definition

Source code in src/arcpie/schema/domain.py
439
440
441
442
443
@classmethod
def from_dict(cls, definition: SystemDomain, workspace: str| None = None) -> Domain:
    """Create a Domain object from a system domain definition"""
    dom: da.Domain = type(f'__domain', (object,), {k: v for k,v in definition.items()})
    return cls(dom, workspace)

from_table classmethod

Create a CodedValue domain from a Table

PARAMETER DESCRIPTION

table

The table or featureclass to create the domain from

TYPE: FeatureClass | Table

name

The name of the domain

TYPE: str

code_field

The field to use for codes

TYPE: str

description_field

The field to use for descriptions

TYPE: str

workspace

The workspace to create the domain in (default: table.workspace)

TYPE: str | None DEFAULT: None

description

An optional description for the new domain

TYPE: str | None

overwrite_existing

If set to True, any existing domains with the name will be replaced,
otherwise new values are appended to the existing domain

TYPE: bool DEFAULT: False

Source code in src/arcpie/schema/domain.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
@classmethod
def from_table(cls, table: FeatureClass | Table, name: str,
               *,
               code_field: str,
               description_field: str,
               workspace: str | None = None,
               description: str | None,
               overwrite_existing: bool = False,
               ) -> CodedValueDomain:
    """Create a CodedValue domain from a Table

    Args:
        table: The table or featureclass to create the domain from
        name: The name of the domain
        code_field: The field to use for codes
        description_field: The field to use for descriptions
        workspace: The workspace to create the domain in (default: table.workspace)
        description: An optional description for the new domain
        overwrite_existing: If set to `True`, any existing domains with the name will be replaced,<br> 
            otherwise new values are appended to the existing domain
    """
    if code_field not in table.fields or description_field not in table.fields:
        msg = (
            f'Invalid {code_field} or {description_field} not in table fields, '
            f'must be one of {table.fields}'
        )
        raise ValueError(msg)

    workspace = workspace or table.workspace
    TableToDomain(
        in_table=str(table),
        code_field=code_field,
        description_field=description_field,
        in_workspace=workspace or table.workspace,
        domain_name=name,
        domain_description=description,
        update_option='REPLACE' if overwrite_existing else 'APPEND'
    )
    return CodedValueDomain([d for d in da.ListDomains(workspace) if d.name == name].pop(), workspace)

sort

sort(
    by: Literal["code", "value"],
    order: Literal["asc", "desc"],
) -> None

CodedValue Only

Source code in src/arcpie/schema/domain.py
333
334
def sort(self, by: Literal['code', 'value'], order: Literal['asc', 'desc']) -> None:
    """CodedValue Only"""

sync

sync() -> None

Sync the domain with the workspace

Source code in src/arcpie/schema/domain.py
143
144
145
146
147
148
def sync(self) -> None:
    """Sync the domain with the workspace"""
    matches = [d for d in da.ListDomains(self.workspace) if d.name == self.name]
    if not matches:
        raise LookupError(f'Domain {self.name} no longer exists in the parent workspace {self.workspace}')
    self._domain = matches.pop()

to_dict

to_dict() -> DomainSchema

Use with json.dump/dumps

Source code in src/arcpie/schema/domain.py
221
222
223
224
225
226
227
228
229
230
231
232
233
def to_dict(self) -> DomainSchema:
    """Use with json.dump/dumps"""
    return {
        'name': self.name,
        'domainType': self.domainType,
        'type': self.type,
        'description': self.description,
        'codedValues': self.codedValues,
        'range': self.range,
        'mergePolicy': self.mergePolicy,
        'splitPolicy': self.splitPolicy,
        'owner': self.owner,
    }

to_table

to_table(
    table_name: str,
    *,
    code_field: str = "code",
    description_field: str = "description",
    configuration_keyword: str | None = None,
) -> Table

Convert the domain to a Table in its workspace

PARAMETER DESCRIPTION

table_name

The name of the output table

TYPE: str

code_field

The field name for the codes

TYPE: str DEFAULT: 'code'

description_field

The field name for the descriptions

TYPE: str DEFAULT: 'description'

configuration_keyword

An optional config keyword for the database

TYPE: str | None DEFAULT: None

Source code in src/arcpie/schema/domain.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def to_table(self, table_name: str, 
             *,
             code_field: str = 'code',
             description_field: str = 'description',
             configuration_keyword: str | None = None
             ) -> Table:
    """Convert the domain to a Table in its workspace

    Args:
        table_name: The name of the output table
        code_field: The field name for the codes
        description_field: The field name for the descriptions
        configuration_keyword: An optional config keyword for the database
    """
    if self.domainType != 'CodedValue':
        raise TypeError(f'Only `CodedValue` domains can be converted to a table')
    return Table(
        *DomainToTable(
            in_workspace=self.workspace, 
            domain_name=self.name, 
            out_table=table_name,
            code_field=code_field,
            description_field=description_field,
            configuration_keyword=configuration_keyword,
        )
    )

used_by

used_by() -> FieldUsage

Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain

Source code in src/arcpie/schema/domain.py
235
236
237
def used_by(self) -> FieldUsage:
    """Get a mapping of FeatureClass/Table -> [Field, ...] usage for the domain"""
    return self.dataset.domains.usage(self.name)[self.name]

map_args

map_args(fr: Any, to: Any) -> dict[Any, Any]

Map two literals

Source code in src/arcpie/schema/domain.py
61
62
63
def map_args(fr: Any, to: Any) -> dict[Any, Any]:
    """Map two literals"""
    return dict(zip(get_args(fr), get_args(to)))