dwgen 2.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. dwgen/__init__.py +2 -0
  2. dwgen/__main__.py +43 -0
  3. dwgen/common/__init__.py +1 -0
  4. dwgen/common/catalogitem.py +26 -0
  5. dwgen/common/checks.py +30 -0
  6. dwgen/common/datawarehouse_entity.py +59 -0
  7. dwgen/common/entity_attribute.py +236 -0
  8. dwgen/common/generator_entity.py +88 -0
  9. dwgen/common/jinja_filter.py +31 -0
  10. dwgen/common/layer.py +52 -0
  11. dwgen/common/performance.py +52 -0
  12. dwgen/common/project.py +226 -0
  13. dwgen/common/properties.py +27 -0
  14. dwgen/common/query.py +122 -0
  15. dwgen/common/registry.py +8 -0
  16. dwgen/common/utils.py +66 -0
  17. dwgen/configs/__init__.py +5 -0
  18. dwgen/configs/configuration.py +11 -0
  19. dwgen/configs/sys_specification.py +47 -0
  20. dwgen/configs/template.py +48 -0
  21. dwgen/configs/templatemapping.py +46 -0
  22. dwgen/dag/__init__.py +0 -0
  23. dwgen/dag/dag.py +82 -0
  24. dwgen/dag/subdag.py +61 -0
  25. dwgen/dwgen.py +44 -0
  26. dwgen/dwsync.py +56 -0
  27. dwgen/entities/__init__.py +0 -0
  28. dwgen/entities/datavault/__init__.py +7 -0
  29. dwgen/entities/datavault/hub.py +54 -0
  30. dwgen/entities/datavault/link.py +52 -0
  31. dwgen/entities/datavault/pit.py +66 -0
  32. dwgen/entities/datavault/reference.py +29 -0
  33. dwgen/entities/datavault/sal.py +30 -0
  34. dwgen/entities/datavault/satellite.py +38 -0
  35. dwgen/entities/datawarehouse/__init__.py +7 -0
  36. dwgen/entities/datawarehouse/dataset.py +36 -0
  37. dwgen/entities/datawarehouse/delivery.py +83 -0
  38. dwgen/entities/datawarehouse/domain.py +19 -0
  39. dwgen/entities/datawarehouse/domainmap.py +36 -0
  40. dwgen/entities/datawarehouse/source.py +35 -0
  41. dwgen/entities/datawarehouse/sourcesystem.py +34 -0
  42. dwgen/entities/dimensional/__init__.py +3 -0
  43. dwgen/entities/dimensional/dimension.py +12 -0
  44. dwgen/entities/dimensional/dimensional.py +60 -0
  45. dwgen/entities/dimensional/fact.py +11 -0
  46. dwgen/entities/generic/__init__.py +5 -0
  47. dwgen/entities/generic/generic_object.py +26 -0
  48. dwgen/entities/generic/generic_table.py +20 -0
  49. dwgen/entities/generic/generic_task.py +26 -0
  50. dwgen/entities/generic/generic_transformation.py +26 -0
  51. dwgen/mapping/__init__.py +3 -0
  52. dwgen/mapping/mapping.py +140 -0
  53. dwgen/mapping/mapping_object.py +24 -0
  54. dwgen/mixins/__init__.py +0 -0
  55. dwgen/mixins/attributes_support.py +40 -0
  56. dwgen/mixins/catalogitem_support.py +11 -0
  57. dwgen/mixins/mapping_source.py +72 -0
  58. dwgen/mixins/mapping_target.py +12 -0
  59. dwgen/mixins/materialization_support.py +21 -0
  60. dwgen/mixins/reference_support.py +70 -0
  61. dwgen/repository/__init__.py +0 -0
  62. dwgen/repository/database.py +12 -0
  63. dwgen/repository/db_repository.py +40 -0
  64. dwgen/repository/file_repository.py +135 -0
  65. dwgen/repository/mock_repository.py +25 -0
  66. dwgen/repository/repository.py +49 -0
  67. dwgen/repository/test_repository.py +25 -0
  68. dwgen/schema.py +17 -0
  69. dwgen/terminal_ui.py +122 -0
  70. dwgen-2.1.1.dist-info/METADATA +369 -0
  71. dwgen-2.1.1.dist-info/RECORD +75 -0
  72. dwgen-2.1.1.dist-info/WHEEL +5 -0
  73. dwgen-2.1.1.dist-info/entry_points.txt +3 -0
  74. dwgen-2.1.1.dist-info/licenses/LICENSE +73 -0
  75. dwgen-2.1.1.dist-info/top_level.txt +1 -0
dwgen/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __version__='2.1.1'
2
+ __min_version__='2.1.0'
dwgen/__main__.py ADDED
@@ -0,0 +1,43 @@
1
+ _A=None
2
+ import argparse,logging,sys
3
+ from dwgen import __version__
4
+ from dwgen.common import performance
5
+ from dwgen.dwgen import Dwgen
6
+ from dwgen.terminal_ui import TerminalUI
7
+ from dwgen.terminal_ui import MessageCategory
8
+ from dwgen import schema
9
+ class ProjectParserError(Exception):0
10
+ class ProjectValidationError(Exception):0
11
+ class ProjectRenderError(Exception):0
12
+ def parse_env_var(value):
13
+ A=value
14
+ if'='not in A:raise argparse.ArgumentTypeError(f"'{A}' has not the format KEY=VALUE")
15
+ B,C=A.split('=',1)
16
+ if not B:raise argparse.ArgumentTypeError(f"'{A}' contains no key")
17
+ return B,C
18
+ def main(argv=_A):
19
+ L='store_true';K='dwgen';G='';F=False
20
+ if argv is _A:argv=sys.argv[1:]
21
+ E=argparse.ArgumentParser(prog=K,description=K);E.add_argument('project',nargs='?',default='dwgen.yaml',help='Path of project file');E.add_argument('-l','--loglevel',default='INFO',help='Loglevel: CRITICAL, ERROR, WARNING, INFO, DEBUG (default: %(default)s)');E.add_argument('-lf','--logfile',default='dwgen.log',help='Logfilename (default: %(default)s)');E.add_argument('--perf',help='Show performance stats',action=L);E.add_argument('--warn',help='Show warnings',action=L);E.add_argument('--schema',nargs='?',const='dwgen.schema.json',help='Create json-schema (default: dwgen.schema.json)');E.add_argument('--version',action='version',version=f"dwgen version {__version__}");E.add_argument('--tplm',nargs='*',default=[],metavar='TEMPLATEMAPPING',help='Templatemapping(s) to use');E.add_argument('-e','--env',type=parse_env_var,action='append',default=[],metavar='KEY=VALUE',help='Environment Variables (KEY=VALUE)');D=E.parse_args();M=getattr(logging,D.loglevel.upper(),_A);logging.basicConfig(filename=D.logfile,filemode='w',level=M,format='%(asctime)s %(levelname)s: %(message)s',datefmt='%Y-%m-%d %I:%M:%S');A=TerminalUI(__version__);N=dict(A for A in D.env)
22
+ if D.schema is not _A:schema.create_json_schema(D.schema,__version__);A.show_message(f":white_check_mark: Created json-schema file for version {__version__}: {D.schema}");sys.exit(2)
23
+ C=Dwgen(D.project,type='file',env_vars=N)
24
+ if C._errors:
25
+ for O in C._errors:I={MessageCategory.PROJECT_PARSER_ERROR:{D.project:O.errors}};A.show_message_table(I)
26
+ sys.exit(2)
27
+ B=C.get_project(D.project);C.repo.set_project_context(B.config.repo);C.repo.load_build_metadata();A.start()
28
+ try:
29
+ P=A.progress.add_task('[blue]Loading Repository:',start=F,total=1,details=G);Q=A.progress.add_task('[blue]Loading Project:',start=F,total=1,details=G);R=A.progress.add_task('[blue]Resolving Dependencies:',start=F,total=1,details=G);J=A.progress.add_task('[blue]Validating Project:',start=F,total=1,details=G);S=A.progress.add_task('[blue]Building Dag:',start=F,total=1,details=G);T=A.progress.add_task('[blue]Generating: ',start=F,total=1,details=G);A.run_task(P,C.repo.load_objects_parallel());A.run_task(Q,B._load_all_objects())
30
+ if any([C.repo.has_parser_errors(),B._has_parser_errors()]):raise ProjectParserError('Parsing errors detected. Stopping execution.')
31
+ A.run_task(R,B._resolve_dependencies());A.run_task(J,B._validate_entities());C.repo.check_build_integrity(fix=True);B._post_validate();H=0
32
+ if B._has_validation_warnings():H=B._get_num_validation_warnings();A.progress.update(J,advance=0,details=':small_orange_diamond:')
33
+ if C.repo.has_parser_warnings():H+=len(C.repo._get_parser_warnings())
34
+ if B._has_validation_errors():raise ProjectValidationError('Validation errors detected. Stopping execution.')
35
+ A.run_task(S,B._build_dag());A.run_task(T,B._generate_entities(D.tplm))
36
+ if H>0:A.show_num_warnings(H)
37
+ if B._has_render_errors():raise ProjectRenderError('Render errors detected. Stopping execution.')
38
+ A.stop();A.show_statistics(C.repo.build,project=B);C.repo.detect_build_deletes_or_renames();A.show_changes(C.repo.build);C.repo.save_build_metadata()
39
+ except(ProjectParserError,ProjectValidationError,ProjectRenderError)as U:logging.error(U);I={MessageCategory.REPOSITORY_PARSER_ERROR:C.repo._get_parser_errors(),MessageCategory.PROJECT_PARSER_ERROR:B._get_parser_errors(),MessageCategory.PROJECT_VALIDATION_ERROR:B._get_validation_errors(),MessageCategory.PROJECT_GENERATION_ERROR:B._get_render_errors()};A.stop();A.show_message_table(I)
40
+ finally:A.stop()
41
+ if D.warn:V={MessageCategory.ENTITY_VALIDATION_WARNING:B._get_validation_warnings()};A.show_message_table(V,type='warning')
42
+ if D.perf:A.show_perf_stat(performance.stats())
43
+ if __name__=='__main__':main()
@@ -0,0 +1 @@
1
+ from.import jinja_filter
@@ -0,0 +1,26 @@
1
+ _A=None
2
+ from dwgen.common.generator_entity import GeneratorEntity
3
+ from pydantic import AliasChoices,BaseModel,Field
4
+ from dwgen.common.properties import Properties
5
+ class CatalogItemDefinition(BaseModel,extra='allow'):name:str=Field(description='The name of the catalog item. eg. database entity.',default=_A);catalog:str=Field(description='The catalog of the catalog item.',validation_alias=AliasChoices('catalog','database'),default=_A);schema_:str=Field(description='The schema of the catalog item.',alias='schema',default=_A);qualifier:str=Field(description='The qualifier of the catalog item.',default=_A);properties:dict=Field(description='A dictionary of custom properties.',default={})
6
+ class CatalogItem:
7
+ __slots__=['entity','_definition','_properties']
8
+ def __init__(A,entity,entityitemdefinition=CatalogItemDefinition()):A.entity=entity;A._definition=entityitemdefinition or CatalogItemDefinition();A._properties=Properties(A.entity,A._definition.properties or{})
9
+ @property
10
+ def name(self):return self._definition.name or self.entity.name
11
+ @property
12
+ def database(self):return self._definition.catalog or''
13
+ @property
14
+ def catalog(self):return self._definition.catalog or''
15
+ @property
16
+ def schema(self):return self._definition.schema_ or''
17
+ @property
18
+ def qualifier(self):return self._definition.qualifier or''
19
+ @property
20
+ def properties(self):return self._properties
21
+ def get_qualifier(A,parent=_A,alias='',name_for=_A,query_context=_A):
22
+ B=name_for;B=A.entity.name_for(B)if B else _A
23
+ if A.entity.sys_specification:return A.entity.sys_specification.table_qualifier.render(catalogitem=A,parent=parent,alias=alias,name_for=B,query_context=query_context)if not A.qualifier else A.qualifier
24
+ else:return'DUMMY_TABLE_DUE_TO_MISSSING_SYS_SPEC'
25
+ def get_dialect(A):
26
+ if A.entity.sys_specification:return A.entity.sys_specification.sql_dialect
dwgen/common/checks.py ADDED
@@ -0,0 +1,30 @@
1
+ _H='expression'
2
+ _G='freshness'
3
+ _F='rowcount'
4
+ _E='pattern'
5
+ _D='values'
6
+ _C='not_null'
7
+ _B='unique'
8
+ _A=None
9
+ from enum import Enum
10
+ from pydantic import BaseModel
11
+ from typing import Annotated,Any,Literal,Union
12
+ from pydantic import Field
13
+ class Severity(str,Enum):info='info';warning='warning';error='error'
14
+ class ThresholdDefinition(BaseModel):max_percentage:float|_A=Field(default=.0,description='The maximum percentage of failures allowed before the check fails. If not specified, the check fails on the first failure.');max_failures:int|_A=Field(default=0,description='The maximum number of failures allowed before the check fails. If not specified, the check fails on the first failure.')
15
+ class CheckDefinition(BaseModel):
16
+ description:str=Field(default=_A,description='A description of the check.');severity:Severity=Field(default=Severity.error,description="The severity of the check. If not specified, the default is 'error'.");threshold:ThresholdDefinition=Field(default=ThresholdDefinition(),description='The threshold for the check. If not specified, the check fails on the first failure.')
17
+ @property
18
+ def type(self):return self.check
19
+ class NotNullCheckDefinition(CheckDefinition):check:Literal[_C]=Field(default=_C,description='A not null check that ensures that the attribute value is not null.')
20
+ class UniqueAttributeCheckDefinition(CheckDefinition):check:Literal[_B]=Field(default=_B,description='A unique attribute check that ensures that the attribute value is unique.')
21
+ class ValuesCheckDefinition(CheckDefinition):check:Literal[_D]=Field(default=_D,description='A values check that ensures that the attribute value is one of the allowed values.');allowed:list[Any]|_A=Field(default=_A,description='A list of allowed values for the attribute. If not specified, any value is allowed.');not_allowed:list[Any]|_A=Field(default=_A,description='A list of not allowed values for the attribute. If not specified, any value is allowed.')
22
+ class RangeCheckDefinition(CheckDefinition):check:Literal['range']=Field(default='range',description='A range check that ensures that the attribute value is within a specified range.');min:Any|_A=Field(default=_A,description='The minimum value for the range. If not specified, there is no minimum.');max:Any|_A=Field(default=_A,description='The maximum value for the range. If not specified, there is no maximum.')
23
+ class PatternCheckDefinition(CheckDefinition):check:Literal[_E]=Field(default=_E,description='A pattern check that ensures that the attribute value matches a specified regex pattern.');pattern:str=Field(description='A regex pattern that the attribute value must match. If not specified, any value is allowed.')
24
+ AttributeChecks=Annotated[Union[NotNullCheckDefinition,UniqueAttributeCheckDefinition,ValuesCheckDefinition,RangeCheckDefinition,PatternCheckDefinition],Field(discriminator='check')]
25
+ class UniqueConstraintDefinition(CheckDefinition):check:Literal[_B]=Field(default=_B,description='A unique constraint that ensures that the combination of attributes is unique across all rows in the dataset.');attributes:list[str]=Field(description='A list of attribute names that must be unique together.')
26
+ class RowCountConstraintDefinition(CheckDefinition):check:Literal[_F]=Field(default=_F,description='A row count constraint that ensures that the number of rows in the dataset is within a specified range.');min:int|_A=Field(default=_A,description='The minimum number of rows for the constraint. If not specified, there is no minimum.');max:int|_A=Field(default=_A,description='The maximum number of rows for the constraint. If not specified, there is no maximum.')
27
+ class FreshnessConstraintDefinition(CheckDefinition):check:Literal[_G]=Field(default=_G,description='A freshness constraint that ensures that the data is fresh within a specified time range.');max_age:int=Field(description="The maximum age of the data for the constraint. This should be a string representing a time duration, e.g., '1 day', '2 hours', etc.");interval:str=Field(description="The interval at which the freshness check should be performed. This should be a string representing a time duration, e.g., '1 day', '2 hours', etc.");attribute:str=Field(description='The attribute that represents the timestamp of the data.')
28
+ class ExpressionConstraintDefinition(CheckDefinition):check:Literal[_H]=Field(default=_H,description='An expression constraint that ensures that a boolean expression evaluates to True for the constraint to pass.');scope:Literal['row','dataset']=Field(default='row',description="The scope of the expression. If 'row', the expression is evaluated for each row. If 'dataset', the expression is evaluated for the entire dataset.");expression:str=Field(description='A boolean expression that must evaluate to True for the constraint to pass. For row scope, this is a boolean expression that should evaluate to True for each row. For dataset scope, this is a boolean expression that should evaluate to True for the entire dataset.')
29
+ Constraint=Annotated[Union[UniqueConstraintDefinition,RowCountConstraintDefinition,FreshnessConstraintDefinition,ExpressionConstraintDefinition],Field(discriminator='check')]
30
+ class Checks(BaseModel):attributes:dict[str,list[AttributeChecks]]=Field(default_factory=dict);entity:list[Constraint]=Field(default_factory=list)
@@ -0,0 +1,59 @@
1
+ _E='{this}'
2
+ _D='dataset'
3
+ _C='expression'
4
+ _B='unique'
5
+ _A=None
6
+ from dwgen.common.catalogitem import CatalogItemDefinition
7
+ from dwgen.common.checks import Checks,Constraint
8
+ from dwgen.configs.sys_specification import SystemSpecification
9
+ from dwgen.common.utils import Folders
10
+ from dwgen.mixins.catalogitem_support import CatalogItemSupport
11
+ from pydantic import AliasChoices,Field
12
+ from dwgen.common.layer import Layer
13
+ from dwgen.common.entity_attribute import EntityAttributeDefinition
14
+ from dwgen.common.generator_entity import GeneratorEntity,GeneratorEntityDefinition
15
+ from dwgen.mixins.attributes_support import AttributeSupport
16
+ from dwgen.repository.repository import RepositoryObject
17
+ class DataWarehouseEntityDefinition(GeneratorEntityDefinition):attributes:list[EntityAttributeDefinition]=Field(description='List of attributes.',default=[]);excludecommonattribute:list[str]=Field(description='List of attributes to exclude from the common attributes.',default=[]);layer:str=Field(description='The layer of the entity. The layer must be defined in configuration.',default=_A);catalogitem:CatalogItemDefinition=Field(description='Definition of the database entity',validation_alias=AliasChoices('catalogitem','dbentity'),default=_A);sql_pre_hook:str=Field(description='SQL placed before the entity-template output.',default='',examples=['DROP TABLE IF EXISTS [{{this.catalogitem.schema}}].[{{this.catalogitem.name}}]']);sql_post_hook:str=Field(description='SQL placed after the entity-template output.',default='',examples=['GRANT SELECT ON {{this.catalogitem.name}} TO user1']);checks:Checks=Field(description='Attribute-checks and entity-checks.',default=_A)
18
+ class DataWarehouseEntity(GeneratorEntity,AttributeSupport,CatalogItemSupport):
19
+ def __init__(A,project,repo_object):
20
+ GeneratorEntity.__init__(A,project,repo_object);AttributeSupport.__init__(A,A._definition.attributes,A._definition.excludecommonattribute);A._checks=[]
21
+ if A._definition.checks:
22
+ for(C,D)in A._definition.checks.attributes.items():
23
+ if not A.get_attribute(C):continue
24
+ for E in D:A.attributes[C]._checks.append(E)
25
+ for B in A._definition.checks.entity:
26
+ if B.type==_B:
27
+ for C in B.attributes:
28
+ if not A.get_attribute(C):continue
29
+ if B.type==_C:
30
+ if B.scope==_D:B.expression=B.expression.replace(_E,A.catalogitem.name)
31
+ A._checks.append(B)
32
+ @property
33
+ def _folder_id(self):return self.layer.id if self.layer else Folders.LAYER_DEFAULT
34
+ @property
35
+ def layer(self):A=self;return A.project.get_layer(A._definition.layer or A.defaults.layer)
36
+ @property
37
+ def sys_specification(self):return self.layer.sys_specification if self.layer else _A
38
+ @property
39
+ def sql_pre_hook(self):A=self;return A.project.templateEnvironment.from_string(A._definition.sql_pre_hook).render(this=A)
40
+ @property
41
+ def sql_post_hook(self):A=self;return A.project.templateEnvironment.from_string(A._definition.sql_post_hook).render(this=A)
42
+ @property
43
+ def checks(self):return self._checks
44
+ def _validate(A):
45
+ H='entity';G='layer';F='checks';D='invalid';GeneratorEntity._validate(A);AttributeSupport._validate(A)
46
+ if not A.layer:
47
+ if A._definition.layer:E=A._definition.layer;A._add_error([G],D,f"invalid layer: {E}")
48
+ else:E=A.project._get_entity_defaults(A.type).layer;A._add_error([G],D,f"invalid layer was set in project config: {E}")
49
+ if A._definition.checks:
50
+ for C in A._definition.checks.attributes.keys():
51
+ if A.get_attribute(C)is _A:A._add_error([F,'attributes'],D,f"check for non-existing attribute: <{C}>")
52
+ for B in A._definition.checks.entity:
53
+ if B.type==_B:
54
+ for C in B.attributes:
55
+ if A.get_attribute(C)is _A:A._add_error([F,H,B.type],D,f"unique constraint for non-existing attribute: <{C}>")
56
+ if B.type==_C:
57
+ if B.scope==_D:B.expression=B.expression.replace(_E,A.catalogitem.name)
58
+ if B.type=='freshness':
59
+ if A.get_attribute(B.attribute)is _A:A._add_error([F,H,B.type],D,f"freshness constraint for non-existing attribute: <{B.attribute}>")
@@ -0,0 +1,236 @@
1
+ _G='nvarchar(10)'
2
+ _F='Datatype'
3
+ _E='Attribute Name'
4
+ _D='get_attribute'
5
+ _C='other'
6
+ _B=False
7
+ _A=None
8
+ import re
9
+ from typing import Literal
10
+ from pydantic import BaseModel,Field
11
+ from dwgen.common.generator_entity import GeneratorEntity
12
+ from dwgen.common.utils import EntityValidationMessage
13
+ from dwgen.common.properties import Properties
14
+ from dwgen.mixins.reference_support import EntityReferenceType as ERT
15
+ class EntityAttributeDataType:
16
+ __slots__=['_name','_type','_length_def','_precision','_scale','_length']
17
+ def __init__(A,name):
18
+ D='(';B=name;A._name=B;A._type=B[:B.find(D)].strip().lower()if B.find(D)!=-1 else B;A._length_def=B[B.find(D)+1:B.find(')')].strip()if B.find(D)!=-1 else'';A._scale=_A;A._precision=_A;A._length=_A
19
+ if A._length_def:
20
+ C=A._length_def.split(',')
21
+ try:
22
+ if len(C)==2:A._precision=int(C[0]);A._scale=int(C[1])
23
+ else:A._precision=int(C[0]);A._scale=0;A._length=int(C[0])
24
+ except ValueError:A._precision=-1;A._scale=-1;A._length=-1
25
+ @property
26
+ def name(self):return self._name
27
+ @property
28
+ def type(self):return self._type
29
+ @property
30
+ def length(self):return self._length
31
+ @property
32
+ def length_def(self):return self._length_def
33
+ @property
34
+ def precision(self):return self._precision
35
+ @property
36
+ def scale(self):return self._scale
37
+ def __str__(A):return A.name
38
+ class EntityAttributeClassifier:
39
+ __slots__=['_classifier_with_label','source']
40
+ def __init__(A,classifier_with_label,source):A._classifier_with_label=classifier_with_label;A.source=source
41
+ def __repr__(A):return A.classifier_label
42
+ @property
43
+ def classifier_label(self):return self._classifier_with_label
44
+ @property
45
+ def name(self):return self._classifier_with_label.split('.')[0]
46
+ @property
47
+ def label(self):return self._classifier_with_label.split('.')[1]
48
+ @property
49
+ def is_deletion(self):return self.name.startswith('!')
50
+ @property
51
+ def _delete(self):return self.name[1:]
52
+ def _validate(A):
53
+ if len(A._classifier.split('.'))!=2:return'classifier nicht in format CLASSIFIER.label'
54
+ class _EntityAttributeDefinition(BaseModel,extra='allow'):name:str=Field(description=_E,default=_A);type:str=Field(description=_F,examples=[_G,'int','date'],default=_A);mandatory:bool=Field(description='Attribute is mandatory',default=_B);description:str=Field(description='attribute description',default='');default:str=Field(description='Attribute default value',default=_A);ghost:str=Field(description='Ghost Record Value',default=_A);unk:str=Field(description='Value set for missing information. E.g.: "Unknown"',default=_A,examples=['Unknown']);na:str=Field(description='Value set for not applicable information. E.g.: "n/a"',default=_A,examples=['n/a']);role:str|list[str]=Field(description='Attribute Role',default=_A);order:int=Field(description='Attributes ordinal position',default=0);properties:dict=Field(description='Additional attribute properties defined as dictionary.',default={},alias='props');fk_name:str=Field(description='Name or template-string for use as foreign-key',default=_A);reference:str=Field(description='reference to an attribute on another entity. Pattern: "entityname.attributename"',default='');referencetype:str=Field(description='reference type',default='',examples=['1:n','m:n']);components:list=Field(description='list of underlying attributes this attribute is made of. Pattern: [entityalias.attributename]',default=[]);pii:bool=Field(description='`True` if the attribute contains personal identifiable information (pii), else `False`. When not explitly set, then the configuration of the underlying component-attributes is used.',default=_A);dataclass:list=Field(description='list of data classification/ category',alias='class',default=[],examples=['PII.name']);auto_increment:bool=Field(description='`True` if the attribute is an auto increment column',default=_B);extra_ddl:str=Field(description='Extra DDL added to attribute definition',default=_A,examples=['IDENTIY(1,1)']);change_tracking:Literal['hash','custom','ignore','single']=Field(description='Change tracking strategy for this attribute: `hash`, `custom`, `ignore`, `single`',default=_A)
55
+ class EntityAttributeDefinition(_EntityAttributeDefinition):name:str=Field(description=_E);type:str=Field(description=_F,examples=[_G,'int','date'])
56
+ class EntityAttribute:
57
+ __slots__=['_definition','entity','_datatype','_role','added_by_source','_is_pii','_fk_instance','_properties','_ref_attribute','_checks'];_ALLOWED_ATTRIBUTE_ROLES=['base','pk','fk','sal_src','sal_main','parent']
58
+ def __init__(A,entity,definition,added_by_source=_A):A._definition=definition;A.entity=entity;A.added_by_source=added_by_source;A._datatype=EntityAttributeDataType(A._definition.type);B=A.entity.defaults.attribute_role if A.entity else _A;A._set_role(A._definition.role or B);A._properties=Properties(A.entity,A._definition.properties or{});A._ref_attribute=_A;A._checks=[]
59
+ def _set_role(B,role):
60
+ A=role
61
+ if isinstance(A,str):B._role=[A]
62
+ elif isinstance(A,(list,tuple,set)):B._role=list(dict.fromkeys(A))
63
+ else:raise TypeError(f"Invalid type for role: {type(A).__name__}")
64
+ def has_role(C,role):
65
+ A=role;B=set(C._role)
66
+ if isinstance(A,str):return A in B
67
+ elif isinstance(A,(list,tuple,set)):return bool(B.intersection(A))
68
+ else:raise TypeError(f"Invalid type for role: {type(A).__name__}")
69
+ def has_roles(C,roles):
70
+ A=roles;B=set(C._role)
71
+ if isinstance(A,str):return A in B
72
+ elif isinstance(A,(list,tuple,set)):return set(A).issubset(B)
73
+ else:raise TypeError(f"Invalid type for roles: {type(A).__name__}")
74
+ @property
75
+ def checks(self):return self._checks
76
+ @property
77
+ def role(self):return self._role
78
+ def get_fk_instance(A):
79
+ if not hasattr(A,'_fk_instance'):
80
+ B=A.name
81
+ if A._definition.fk_name:B=A.entity.project.templateEnvironment.from_string(A._definition.fk_name).render(this=A)
82
+ A._fk_instance=A._copy(B)
83
+ return A._fk_instance
84
+ @property
85
+ def datatype(self):return self._datatype
86
+ @property
87
+ def properties(self):return self._properties
88
+ @property
89
+ def is_pii(self):
90
+ A=self
91
+ if not hasattr(A,'_is_pii'):
92
+ if A._definition.pii is _A:B=[B for B in A.get_components()if B is not A];A._is_pii=any(A.is_pii for A in B)
93
+ else:A._is_pii=A._definition.pii
94
+ return A._is_pii
95
+ @property
96
+ def name(self):return self._definition.name
97
+ @name.setter
98
+ def name(self,value):self._definition.name=value
99
+ @property
100
+ def is_mandatory(self):return self._definition.mandatory
101
+ @property
102
+ def ghostvalue(self):A=self;return A._definition.ghost or A.entity.project.config.datavault.ghostrecord.get(A.datatype.type.lower(),A.entity.project.config.datavault.ghostrecord.get(_C,''))
103
+ @property
104
+ def not_applicable_value(self):
105
+ A=self
106
+ if A._definition.na:return A._definition.na
107
+ B=A.referenced_attribute
108
+ if B and B.not_applicable_value:return B.not_applicable_value
109
+ C=A.entity.project.config.datawarehouse.not_applicable_record;return C.get(A.datatype.type.lower(),C.get(_C,''))
110
+ @property
111
+ def unknown_value(self):
112
+ A=self
113
+ if A._definition.unk:return A._definition.unk
114
+ B=A.referenced_attribute
115
+ if B and B.unknown_value:return B.unknown_value
116
+ C=A.entity.project.config.datawarehouse.unknown_record;return C.get(A.datatype.type.lower(),C.get(_C,''))
117
+ @property
118
+ def column_definition(self):
119
+ A=self
120
+ if not A.entity.sys_specification:return A.name
121
+ return A.entity.sys_specification.column_ddl.render(attribute=A)
122
+ @property
123
+ def qualifier(self):
124
+ A=self
125
+ if not A.entity.sys_specification:return A.name
126
+ return A.entity.sys_specification.column_qualifier.render(attribute=A)
127
+ @property
128
+ def description(self):return self._definition.description
129
+ @property
130
+ def ghost(self):return self._definition.ghost
131
+ @property
132
+ def reference(self):return self._definition.reference
133
+ @property
134
+ def referencetype(self):return self._definition.referencetype
135
+ @property
136
+ def extra_ddl(self):return self._definition.extra_ddl
137
+ @property
138
+ def is_auto_increment(self):return self._definition.auto_increment
139
+ @property
140
+ def order(self):return self._definition.order
141
+ @property
142
+ def _classifiers(self):return self._definition.dataclass
143
+ @property
144
+ def classifiers(self):
145
+ B=self;A={}
146
+ for D in B.get_components():A=A|D.classifiers
147
+ A=A|B._get_classifiers()
148
+ for C in B._get_classifiers().values():
149
+ if C.is_deletion:A.pop(C._delete,_A);A.pop(C,_A)
150
+ return A
151
+ def get_classifier(A,name):return next((A for A in A.classifiers if A.name==name),_A)
152
+ @property
153
+ def change_tracking(self):return self._definition.change_tracking
154
+ def _copy(A,newname=''):return EntityAttribute(A.entity,A._definition.model_copy(deep=True,update={'name':newname or A.name}),'generated')
155
+ def _parse_entity_attribute_literal(C,literal):A,B=literal.rsplit('.',1);return A,B
156
+ def _get_explicit_components(A):
157
+ C={}
158
+ for F in A._definition.components:
159
+ D,E=A._parse_entity_attribute_literal(F)
160
+ for B in A.entity.get_upstream_lineage_references():
161
+ if getattr(B.source,_D,_B)and B.alias==D:G=B.source.get_attribute(E);H=f"{D}.{E}";C.update({H:G})
162
+ return C
163
+ def get_components(C):
164
+ D={}
165
+ if C._definition.components:D={B:A for(B,A)in C._get_explicit_components().items()if A is not _A}
166
+ else:
167
+ for A in C.entity.get_upstream_lineage_references():
168
+ if getattr(A.source,_D,_B):
169
+ if A.type==ERT.MAPPING_TARGET:
170
+ for G in A.source.get_targetmappings_by_target(A.target.name):
171
+ for F in G.get_attribute_mappings():
172
+ if F.target==C:
173
+ for B in F.source.get_expression_attributes().values():E=f"{A.source.name}.{B}";D.update({E:B})if B is not _A else _A
174
+ if A.type in(ERT.TRANSFORMATION_TARGET,ERT.TASK_TARGET,ERT.PIT_BASE,ERT.SOURCE,ERT.HUB_ROLE,ERT.DIMENSION_ROLE):B=A.source.get_attribute(C.name);E=f"{A.source.name}.{B}";D.update({E:B})if B is not _A else _A
175
+ if A.type in(ERT.DEPENDS_ON,):0
176
+ if A.type==ERT.QUERY:B=A.source.get_attribute(C.name);E=f"{A.source.name}.{B}";D.update({E:B})if B is not _A else _A
177
+ return list(D.values())
178
+ @property
179
+ def referenced_attribute(self):
180
+ A=self
181
+ if A._ref_attribute is _A and A._definition.reference:B,C=A._parse_entity_attribute_literal(A._definition.reference);A.referenced_attribute=A.entity.project.get_entity(B).get_attribute(C)
182
+ return A._ref_attribute
183
+ @referenced_attribute.setter
184
+ def referenced_attribute(self,value):self._ref_attribute=value
185
+ def _validate(A):
186
+ E='invalid';D='attributes';C=[]
187
+ if not A.entity.sys_specification:return C
188
+ K=A.entity.sys_specification._valid_datatype(A.datatype.name)
189
+ if not K:C.append(EntityValidationMessage([D,A.name],E,f"Datatype <{A.datatype}> for Attribute <{A.name}> not valid (not matching any pattern in <{A.entity.sys_specification.name}>)"))
190
+ F=A.entity.project.config.constraints.attribute_roles
191
+ if F and A._role:
192
+ for H in A._role:
193
+ if H not in F+A._ALLOWED_ATTRIBUTE_ROLES:C.append(EntityValidationMessage([D,A.name],E,f"Role <{H}> for Attribute <{A.name}> not valid. Allowed roles: {F}"))
194
+ for L in A._definition.components:
195
+ I=_B;G,O=A._parse_entity_attribute_literal(L)
196
+ for J in A.entity.get_upstream_lineage_references():
197
+ if getattr(J.source,_D,_B)and J.alias==G:I=True
198
+ if not I:C.append(EntityValidationMessage([D,A.name],E,f"Component entity <{G}> of Attribute <{A.name}> not found. Check if <{G}> is part of the upstream lineage of entity <{A.entity.name}>."))
199
+ for(M,N)in A._get_explicit_components().items():
200
+ if N is _A:C.append(EntityValidationMessage([D,A.name],E,f"Component <{M}> of Attribute <{A.name}> not found in source"))
201
+ B=A.referenced_attribute
202
+ if B:
203
+ if A._definition.na and B.not_applicable_value and A._definition.na!=B.not_applicable_value:C.append(EntityValidationMessage([D,A.name],E,f"Not applicable value <{A._definition.na}> for Attribute <{A.name}> does not match with referenced attribute <{B.entity.name}.{B.name}>'s not applicable value <{B.not_applicable_value}>."))
204
+ if A._definition.unk and B.unknown_value and A._definition.unk!=B.unknown_value:C.append(EntityValidationMessage([D,A.name],E,f"Unknown value <{A._definition.unk}> for Attribute <{A.name}> does not match with referenced attribute <{B.entity.name}.{B.name}>'s unknown value <{B.unknown_value}>."))
205
+ return C
206
+ class AttributeExpression:
207
+ _ATTRIBUTE_EXPRESSION_REGEX=re.compile('\\{([a-zA-Z0-9_.]+)\\}');__slots__=['_rawexpression','_datatype','entity','_alias','_expression_attributes','_parsed_expression']
208
+ def __init__(A,entity,expression=_A,resulttype=_A,alias=_A,alias_only_complex=_B):
209
+ D=alias;B=expression;A.entity=entity;A._rawexpression=_A;A._expression_attributes=_A;A._parsed_expression=_A;A._alias=D;A._datatype=resulttype
210
+ if type(B)is dict:A._rawexpression=B.get('value');A._parsed_expression=A._rawexpression;A._expression_attributes={}
211
+ elif isinstance(B,str)and'{'not in B:
212
+ A._rawexpression=B
213
+ if not alias_only_complex:A._alias=D or A._rawexpression
214
+ else:A._alias=A._rawexpression
215
+ C=A.entity.get_attribute(A._rawexpression)
216
+ if C:A._parsed_expression=C.qualifier;A._datatype=C.datatype;A._expression_attributes={C.name:C}
217
+ else:A._expression_attributes={A._rawexpression:_A}
218
+ else:A._rawexpression=B
219
+ def __repr__(A):return'AttributeExpression: <{0}> as <{1}>'.format(A._rawexpression,A._alias)
220
+ def __str__(A):return A.expression
221
+ @property
222
+ def is_simple(self):return isinstance(self._rawexpression,str)and'{'not in self._rawexpression
223
+ @property
224
+ def datatype(self):return self._datatype
225
+ @property
226
+ def alias(self):return self._alias
227
+ def _replace_placeholder(C,match):A=match;D=A.group(1);B=C.get_expression_attributes().get(D);return B.qualifier if B else A.group(0)
228
+ def _get_attribute_matches(A):B=re.finditer(A._ATTRIBUTE_EXPRESSION_REGEX,A._rawexpression);return[[A.group(1),A.span(1)]for A in B]
229
+ @property
230
+ def expression(self):
231
+ A=self
232
+ if A._parsed_expression is not _A:return A._parsed_expression
233
+ A._parsed_expression=A._ATTRIBUTE_EXPRESSION_REGEX.sub(A._replace_placeholder,A._rawexpression);return A._parsed_expression
234
+ def get_expression_attributes(A):
235
+ if A._expression_attributes is not _A:return A._expression_attributes
236
+ B=[A[0]for A in A._get_attribute_matches()];A._expression_attributes={B:A.entity.get_attribute(B)for B in B};return A._expression_attributes
@@ -0,0 +1,88 @@
1
+ _F='validate'
2
+ _E=' or '
3
+ _D=False
4
+ _C=None
5
+ _B=True
6
+ _A='invalid'
7
+ import datetime,logging
8
+ from pydantic import BaseModel,Field,ValidationError
9
+ from dwgen.common import performance
10
+ from dwgen.common.utils import EntityType,EntityValidationException,EntityValidationMessage,extract_extra_fields,get_extra_paths
11
+ from dwgen.common.properties import Properties
12
+ from dwgen.mixins.reference_support import ReferenceSupport
13
+ from dwgen.repository.repository import RepositoryObject
14
+ class GeneratorEntityDefinition(BaseModel,extra='allow'):name:str=Field(description='name of the entity. Only letters, number, dot and underscore are allowed');type:EntityType=Field(description='type of the entity');subtype:str=Field(description='subtype of the entity',default='base');description:str=Field(description='description of the entity',default='');properties:dict=Field(description='dictionary of custom properties',default={});generate:bool=Field(description='`True` if entity schould be generated',default=_B)
15
+ class GeneratorEntity(ReferenceSupport):
16
+ def __init__(A,project,repo_object=_C):ReferenceSupport.__init__(A);A.project=project;A._repo_object=repo_object;A._definition=A._load_definition(A._repo_object.definition);A._validated=_D;A._components_valid=_D;A.errors=[];A.warnings=[];A._properties=Properties(A,A._definition.properties if A._definition else{})
17
+ def _resolve_dependencies(A):logging.info(f"Resolving dependencies for {A.name}")
18
+ def __repr__(A):return f"({id(A)}: {A.type}|{A.name})"
19
+ def _load_definition(A,yaml_dict):
20
+ C='load_definition';performance.start(C,A)
21
+ if not A._schema:return
22
+ try:return A._schema.model_validate(yaml_dict)
23
+ except ValidationError as B:raise EntityValidationException.from_pydantic_error('DefinitionSchemaError','Error while parsing entity definition',B)from B
24
+ finally:performance.end(C,A)
25
+ @property
26
+ def properties(self):return self._properties
27
+ @property
28
+ def is_valid(self):return _B if self._validated and not self.errors else _D
29
+ @property
30
+ def id(self):return self._repo_object.id if self._repo_object else _C
31
+ @property
32
+ def name(self):A=self;return A._definition.name if A._definition else A._repo_object.name
33
+ @property
34
+ def type(self):A=self;return A._definition.type if A._definition else A._repo_object.type
35
+ @property
36
+ def subtype(self):A=self;return A._definition.subtype if A._definition else A._repo_object.subtype
37
+ @property
38
+ def description(self):A=self;return A._definition.description if A._definition else A._repo_object.description
39
+ @property
40
+ def generate(self):return self._definition.generate
41
+ @property
42
+ def _folder_id(self):return self._repo_object.folder_id
43
+ @property
44
+ def project_id(self):return self.project.id if self.project else 0
45
+ @property
46
+ def created(self):return self._repo_object.created
47
+ @property
48
+ def updated(self):return self._repo_object.updated
49
+ @property
50
+ def defaults(self):return self.project._get_entity_defaults(self.type)
51
+ @property
52
+ def config(self):return self.project._get_entity_config(self.type)
53
+ def alias(A,rule):return A.name_for(rule)
54
+ def name_for(A,rule):
55
+ B=A.project._name_rules_compiled.get(rule)
56
+ if B:return B.render(entity=A)
57
+ else:return f"invalid naming rule: <{rule}>"
58
+ def _validate_components_references(A):0
59
+ def _validate_components(B):
60
+ logging.info(f"Validating components of {B.name}");C=0
61
+ for A in B.get_component_references():
62
+ if not A.component:logging.debug('Validate components: Unknown component found');C+=1;continue
63
+ if not A.component._validated:A.component._validate()
64
+ else:logging.debug(f"{A.component.name} already validated")
65
+ C+=1 if not A.component.is_valid else 0
66
+ B._components_valid=_B if C==0 else _D
67
+ def _validate(A):
68
+ logging.info(f"Validating {A.name}")
69
+ if not A.project.config.constraints.entity_name_regex.match(A.name):A._add_error(['name'],_A,f"entity-name: <{A.name}> is not valid. Only letters, number, dot and underscore are allowed. Length has to be between <{A.project.config.constraints.entity_name_min_len}> and <{A.project.config.constraints.entity_name_max_len}>.")
70
+ C=extract_extra_fields(A._definition);D=get_extra_paths(C)
71
+ for B in D:A.errors.append(EntityValidationMessage(B,_A,f"unknown property: <{B[-1]}>"))
72
+ A._validate_components();performance.start(_F,A)
73
+ def _validate_end(A):A._validated=_B;performance.end(_F,A);A._log_errors_and_warnings()
74
+ def _add_error(A,location,type,message):A.errors.append(EntityValidationMessage(location,type,message))
75
+ def _add_error_msg(A,msg):
76
+ if msg:A.errors.append(msg)
77
+ def _log_errors_and_warnings(A):
78
+ if A.errors:
79
+ for B in A.errors:logging.error(f"{A.name}: {str(B)}")
80
+ if A.warnings:
81
+ for C in A.warnings:logging.warning(f"{A.name}: {str(C)}")
82
+ def _check_entity_reference(G,name,types=[],location=[],error_text='invalid reference',hint=''):
83
+ E=location;D=name;B=hint;A=types;F,C=G.project._get_entity_with_suggestions(D,types=A);C=f"[green] - do you mean: {_E.join(f"<{A}>"for A in C)}?"if C else'';B=f"\n[bright_black]{B}"if B else''
84
+ if F is _C:return EntityValidationMessage(E,_A,f"{error_text}: <{D}> {C} {B}")
85
+ elif A and F.type not in A:return EntityValidationMessage(E,_A,f"<{D}> is not of type: {_E.join(f"<{A}>"for A in A)}.")
86
+ def _check_attribute_reference(E,lookup_entity,attribute_name,location=[],error_text='invalid attribute reference',hint=''):
87
+ D=attribute_name;C=lookup_entity;A=hint;F,B=C._get_attribute_with_suggestions(D);B=f"[green] - do you mean: {_E.join(f"<{A}>"for A in B)}?"if B else'';A=f"\n[bright_black]{A}"if A else''
88
+ if F is _C:E._add_error(location,_A,f"{error_text}: <{D}> not found in entity <{C.name}>. {B} {A}")
@@ -0,0 +1,31 @@
1
+ _B='entity'
2
+ _A='project'
3
+ import hashlib,re,uuid
4
+ from jinja2 import pass_context
5
+ from dwgen.common.registry import register_filter
6
+ @register_filter('to_uuid')
7
+ def cust_filter_to_uuid(seed,version=4):A=hashlib.md5();A.update(seed.encode('utf-8'));return uuid.UUID(A.hexdigest(),version=version)
8
+ @register_filter('max_str_len')
9
+ def cust_filter_max_str_len(values,attribute):A=[getattr(A,attribute)for A in values];return len(max(A,key=len))
10
+ @register_filter('render')
11
+ @pass_context
12
+ def cust_filter_render(context,value):
13
+ B=value;A=context;C=''
14
+ if B:D=A.eval_ctx.environment.from_string(str(B));C=D.render(this=A.get(_B),project=A.get(_A))
15
+ return C
16
+ @register_filter('pad')
17
+ def cust_filter_pad(value,length,char=' ',direction='right'):
18
+ C=direction;B=length;A=value;A=str(A);B=int(B)
19
+ if C=='right':return A.ljust(B,char)
20
+ elif C=='left':return A.rjust(B,char)
21
+ else:raise ValueError("direction must be 'left' or 'right'")
22
+ @register_filter('quote')
23
+ def cust_filter_quote(value,char="'"):return char+str(value)+char
24
+ @register_filter('apply_entity_template')
25
+ @pass_context
26
+ def cust_filter_apply_entity_template(context,value,template):
27
+ B=context;A=value;D=re.compile('\\{([a-zA-Z0-9_\\.]*?)(?:(?::)|(?i: as ))([a-zA-Z0-9_\\.]*?)?\\}',re.MULTILINE);E=D.finditer(A)
28
+ if A:
29
+ F=B.eval_ctx.environment.from_string(str(template))
30
+ for(I,C)in enumerate(E):G=C.group(1);H=F.render(this=B.get(_B),project=B.get(_A),entity=B.get(_A).get_entity(G));A=A.replace(C.group(0),H)
31
+ return A
dwgen/common/layer.py ADDED
@@ -0,0 +1,52 @@
1
+ _B='dictionary of custom properties'
2
+ _A='layer'
3
+ from dwgen.common.catalogitem import CatalogItem,CatalogItemDefinition
4
+ from pydantic import AliasChoices,BaseModel,Field
5
+ from dwgen.common.generator_entity import GeneratorEntity,GeneratorEntityDefinition
6
+ from dwgen.configs.sys_specification import SystemSpecification
7
+ from dwgen.common.utils import EntityValidationMessage,Folders
8
+ from dwgen.common.properties import Properties
9
+ from dwgen.mixins.reference_support import EntityReferenceType as ERT
10
+ class LayerDefaultsDefinition(BaseModel,extra='allow'):catalogitem:CatalogItemDefinition=Field(description='Database entity',validation_alias=AliasChoices('catalogitem','dbentity'),default=CatalogItemDefinition(database='DWH',schema='dbo'));properties:dict=Field(description=_B,default={})
11
+ class LayerDefinition(BaseModel,extra='allow'):label:str=Field(description='Layer label',default='');description:str=Field(description='Layer description',default='');sys_specification:str=Field(description='Name of the system specification',default='default.sys_specification');defaults:LayerDefaultsDefinition=Field(description='Layer defaults for all entities assigned to this layer',default=LayerDefaultsDefinition());areas:dict[str,LayerDefaultsDefinition]=Field(description='Area specific layer defaults',default={});properties:dict=Field(description=_B,default={})
12
+ class Layer:
13
+ def __init__(A,project,name,definition):A._name=name;A._definition=definition;A.project=project;A._properties=Properties(A,A._definition.properties or{});A._default_catalogitem=CatalogItem(A,A._definition.defaults.catalogitem)
14
+ def _resolve_dependencies(A):
15
+ if A._definition.sys_specification:
16
+ B=A.project.get_entity(A._definition.sys_specification)
17
+ if B:A._add_component_reference(B,ERT.SYS_SPECIFICATION)
18
+ @property
19
+ def name(self):return self._name
20
+ @property
21
+ def label(self):return self._definition.label
22
+ @property
23
+ def description(self):return self._definition.description
24
+ @property
25
+ def defaults(self):return self._definition.defaults
26
+ @property
27
+ def catalogitem(self):return self._default_catalogitem
28
+ @property
29
+ def catalog(self):return self._definition.defaults.catalogitem.catalog
30
+ @property
31
+ def schema(self):return self._definition.defaults.catalogitem.schema_
32
+ @property
33
+ def sys_specification(self):return self.project.get_entity(self._definition.sys_specification)
34
+ @property
35
+ def areas(self):return self._definition.areas
36
+ @property
37
+ def properties(self):return self._properties
38
+ @property
39
+ def config(self):return self._definition
40
+ @property
41
+ def _folder_id(self):return Folders.LAYER
42
+ def get_entities(A,return_as='list'):
43
+ B=return_as
44
+ if B=='dict':return{C:B for(C,B)in A.project._cache.items()if getattr(B,_A,None)==A}
45
+ elif B=='list':return[B for B in A.project._cache.values()if getattr(B,_A,None)==A]
46
+ else:raise ValueError(f"Unknown return_as value: {B}")
47
+ def get_entity_count(A):return sum(1 for B in A.project._cache.values()if getattr(B,_A,None)==A)
48
+ def get_area_defaults(A,area):return A._definition.areas.get(area,A._definition.defaults)
49
+ def _validate(A):
50
+ B=[];C=[]
51
+ if not A.sys_specification:B.append(EntityValidationMessage([_A,A.name,'sys_specification'],'invalid',f"invalid system specification: {A._definition.sys_specification}"))
52
+ return B,C
@@ -0,0 +1,52 @@
1
+ _D='duration'
2
+ _C='start'
3
+ _B='end'
4
+ _A=None
5
+ import time
6
+ from threading import Lock
7
+ class _PerformanceMonitor:
8
+ def __init__(A):A._lock=Lock();A._global_perf={};A._object_perf={};A._stat_names=[]
9
+ def start(A,stat_name,obj_id=_A):
10
+ B=stat_name;C=time.perf_counter()
11
+ with A._lock:
12
+ D=A._get_target(obj_id);D[B]={_C:C,_B:_A}
13
+ if B not in A._stat_names:A._stat_names.append(B)
14
+ def end(C,stat_name,obj_id=_A):
15
+ A=stat_name;D=time.perf_counter()
16
+ with C._lock:
17
+ B=C._get_target(obj_id)
18
+ if A in B and B[A][_B]is _A:B[A][_B]=D
19
+ def stats(A,obj_id=_A):
20
+ with A._lock:return A._calculate_stats_total()
21
+ def _get_target(A,obj_id):
22
+ B=obj_id
23
+ if B is _A:return A._global_perf
24
+ return A._object_perf.setdefault(B,{})
25
+ def _calculate_stats_total(I):
26
+ K='span';J='count';F='latest_end';E='earliest_start';A={A:{_D:0,K:0,J:0,E:_A,F:_A}for A in I._stat_names}
27
+ for L in I._object_perf.values():
28
+ for(B,G)in L.items():
29
+ C,D=G[_C],G[_B];A[B][_D]+=D-C;A[B][J]+=1
30
+ if A[B][E]is _A or C<A[B][E]:A[B][E]=C
31
+ if A[B][F]is _A or D>A[B][F]:A[B][F]=D
32
+ for(B,G)in I._global_perf.items():
33
+ C,D=G[_C],G[_B]
34
+ if C is not _A and D is not _A:A[B][_D]+=D-C;A[B][J]+=1
35
+ for(M,H)in A.items():
36
+ if H[E]is not _A and H[F]is not _A:H[K]=H[F]-H[E]
37
+ return A
38
+ def _calculate_stats(K,perf_data):
39
+ A=_A;B=_A;E=0;F={}
40
+ for(J,G)in perf_data.items():
41
+ C,D=G.get(_C),G.get(_B)
42
+ if C is _A or D is _A:continue
43
+ H=D-C;F[J]={_C:C,_B:D,_D:H};E+=H
44
+ if A is _A or C<A:A=C
45
+ if B is _A or D>B:B=D
46
+ I=_A
47
+ if A is not _A and B is not _A:I=B-A
48
+ return{'total_duration':E,'total_span':I,'per_stat_name':F}
49
+ _monitor=_PerformanceMonitor()
50
+ start=_monitor.start
51
+ end=_monitor.end
52
+ stats=_monitor.stats