datacontract-cli 0.10.13__py3-none-any.whl → 0.10.15__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.

Potentially problematic release.


This version of datacontract-cli might be problematic. Click here for more details.

Files changed (77) hide show
  1. datacontract/breaking/breaking.py +227 -9
  2. datacontract/breaking/breaking_rules.py +24 -0
  3. datacontract/catalog/catalog.py +1 -1
  4. datacontract/cli.py +104 -32
  5. datacontract/data_contract.py +35 -5
  6. datacontract/engines/datacontract/check_that_datacontract_file_exists.py +1 -1
  7. datacontract/engines/fastjsonschema/check_jsonschema.py +114 -22
  8. datacontract/engines/soda/check_soda_execute.py +5 -3
  9. datacontract/engines/soda/connections/duckdb.py +1 -0
  10. datacontract/engines/soda/connections/kafka.py +38 -17
  11. datacontract/export/avro_converter.py +8 -1
  12. datacontract/export/avro_idl_converter.py +2 -2
  13. datacontract/export/bigquery_converter.py +4 -3
  14. datacontract/export/data_caterer_converter.py +1 -1
  15. datacontract/export/dbml_converter.py +2 -4
  16. datacontract/export/dbt_converter.py +2 -3
  17. datacontract/export/dcs_exporter.py +6 -0
  18. datacontract/export/exporter.py +5 -2
  19. datacontract/export/exporter_factory.py +16 -3
  20. datacontract/export/go_converter.py +3 -2
  21. datacontract/export/great_expectations_converter.py +202 -40
  22. datacontract/export/html_export.py +1 -1
  23. datacontract/export/jsonschema_converter.py +3 -2
  24. datacontract/export/{odcs_converter.py → odcs_v2_exporter.py} +5 -5
  25. datacontract/export/odcs_v3_exporter.py +294 -0
  26. datacontract/export/pandas_type_converter.py +40 -0
  27. datacontract/export/protobuf_converter.py +1 -1
  28. datacontract/export/rdf_converter.py +4 -5
  29. datacontract/export/sodacl_converter.py +86 -2
  30. datacontract/export/spark_converter.py +10 -7
  31. datacontract/export/sql_converter.py +1 -2
  32. datacontract/export/sql_type_converter.py +55 -11
  33. datacontract/export/sqlalchemy_converter.py +1 -2
  34. datacontract/export/terraform_converter.py +1 -1
  35. datacontract/imports/avro_importer.py +1 -1
  36. datacontract/imports/bigquery_importer.py +1 -1
  37. datacontract/imports/dbml_importer.py +2 -2
  38. datacontract/imports/dbt_importer.py +3 -2
  39. datacontract/imports/glue_importer.py +5 -3
  40. datacontract/imports/iceberg_importer.py +161 -0
  41. datacontract/imports/importer.py +2 -0
  42. datacontract/imports/importer_factory.py +12 -1
  43. datacontract/imports/jsonschema_importer.py +3 -2
  44. datacontract/imports/odcs_importer.py +25 -168
  45. datacontract/imports/odcs_v2_importer.py +177 -0
  46. datacontract/imports/odcs_v3_importer.py +309 -0
  47. datacontract/imports/parquet_importer.py +81 -0
  48. datacontract/imports/spark_importer.py +2 -1
  49. datacontract/imports/sql_importer.py +1 -1
  50. datacontract/imports/unity_importer.py +3 -3
  51. datacontract/integration/datamesh_manager.py +1 -1
  52. datacontract/integration/opentelemetry.py +0 -1
  53. datacontract/lint/lint.py +2 -1
  54. datacontract/lint/linters/description_linter.py +1 -0
  55. datacontract/lint/linters/example_model_linter.py +1 -0
  56. datacontract/lint/linters/field_pattern_linter.py +1 -0
  57. datacontract/lint/linters/field_reference_linter.py +1 -0
  58. datacontract/lint/linters/notice_period_linter.py +1 -0
  59. datacontract/lint/linters/quality_schema_linter.py +1 -0
  60. datacontract/lint/linters/valid_constraints_linter.py +1 -0
  61. datacontract/lint/resolve.py +14 -9
  62. datacontract/lint/resources.py +21 -0
  63. datacontract/lint/schema.py +1 -1
  64. datacontract/lint/urls.py +4 -2
  65. datacontract/model/data_contract_specification.py +83 -13
  66. datacontract/model/odcs.py +11 -0
  67. datacontract/model/run.py +21 -12
  68. datacontract/templates/index.html +6 -6
  69. datacontract/web.py +2 -3
  70. {datacontract_cli-0.10.13.dist-info → datacontract_cli-0.10.15.dist-info}/METADATA +176 -93
  71. datacontract_cli-0.10.15.dist-info/RECORD +105 -0
  72. {datacontract_cli-0.10.13.dist-info → datacontract_cli-0.10.15.dist-info}/WHEEL +1 -1
  73. datacontract/engines/datacontract/check_that_datacontract_str_is_valid.py +0 -48
  74. datacontract_cli-0.10.13.dist-info/RECORD +0 -97
  75. {datacontract_cli-0.10.13.dist-info → datacontract_cli-0.10.15.dist-info}/LICENSE +0 -0
  76. {datacontract_cli-0.10.13.dist-info → datacontract_cli-0.10.15.dist-info}/entry_points.txt +0 -0
  77. {datacontract_cli-0.10.13.dist-info → datacontract_cli-0.10.15.dist-info}/top_level.txt +0 -0
@@ -3,7 +3,7 @@ import logging
3
3
  from typing import List
4
4
 
5
5
  from datacontract.imports.importer import Importer
6
- from datacontract.model.data_contract_specification import DataContractSpecification, Model, Field
6
+ from datacontract.model.data_contract_specification import DataContractSpecification, Field, Model
7
7
  from datacontract.model.exceptions import DataContractException
8
8
 
9
9
 
@@ -1,11 +1,11 @@
1
- from pydbml import PyDBML, Database
2
1
  from typing import List
3
2
 
3
+ from pydbml import Database, PyDBML
4
4
  from pyparsing import ParseException
5
5
 
6
6
  from datacontract.imports.importer import Importer
7
7
  from datacontract.imports.sql_importer import map_type_from_sql
8
- from datacontract.model.data_contract_specification import DataContractSpecification, Model, Field
8
+ from datacontract.model.data_contract_specification import DataContractSpecification, Field, Model
9
9
  from datacontract.model.exceptions import DataContractException
10
10
 
11
11
 
@@ -1,11 +1,12 @@
1
1
  import json
2
2
  from typing import TypedDict
3
3
 
4
- from datacontract.imports.importer import Importer
5
- from datacontract.model.data_contract_specification import DataContractSpecification, Field, Model
6
4
  from dbt.artifacts.resources.v1.components import ColumnInfo
7
5
  from dbt.contracts.graph.manifest import Manifest
8
6
 
7
+ from datacontract.imports.importer import Importer
8
+ from datacontract.model.data_contract_specification import DataContractSpecification, Field, Model
9
+
9
10
 
10
11
  class DBTImportArgs(TypedDict, total=False):
11
12
  """
@@ -1,11 +1,13 @@
1
- import boto3
2
- from typing import List, Dict, Generator
3
1
  import re
2
+ from typing import Dict, Generator, List
3
+
4
+ import boto3
5
+
4
6
  from datacontract.imports.importer import Importer
5
7
  from datacontract.model.data_contract_specification import (
6
8
  DataContractSpecification,
7
- Model,
8
9
  Field,
10
+ Model,
9
11
  Server,
10
12
  )
11
13
 
@@ -0,0 +1,161 @@
1
+ from typing import Any, Dict
2
+
3
+ from pydantic import ValidationError
4
+ from pyiceberg import types as iceberg_types
5
+ from pyiceberg.schema import Schema
6
+
7
+ from datacontract.imports.importer import Importer
8
+ from datacontract.model.data_contract_specification import DataContractSpecification, Field, Model
9
+ from datacontract.model.exceptions import DataContractException
10
+
11
+
12
+ class IcebergImporter(Importer):
13
+ def import_source(
14
+ self, data_contract_specification: DataContractSpecification, source: str, import_args: dict
15
+ ) -> DataContractSpecification:
16
+ schema = load_and_validate_iceberg_schema(source)
17
+ return import_iceberg(
18
+ data_contract_specification,
19
+ schema,
20
+ import_args.get("iceberg_table"),
21
+ )
22
+
23
+
24
+ def load_and_validate_iceberg_schema(source: str) -> Schema:
25
+ with open(source, "r") as file:
26
+ try:
27
+ return Schema.model_validate_json(file.read())
28
+ except ValidationError as e:
29
+ raise DataContractException(
30
+ type="schema",
31
+ name="Parse iceberg schema",
32
+ reason=f"Failed to validate iceberg schema from {source}: {e}",
33
+ engine="datacontract",
34
+ )
35
+
36
+
37
+ def import_iceberg(
38
+ data_contract_specification: DataContractSpecification, schema: Schema, table_name: str
39
+ ) -> DataContractSpecification:
40
+ if data_contract_specification.models is None:
41
+ data_contract_specification.models = {}
42
+
43
+ model = Model(type="table", title=table_name)
44
+
45
+ for field in schema.fields:
46
+ model.fields[field.name] = _field_from_nested_field(field)
47
+
48
+ data_contract_specification.models[table_name] = model
49
+ return data_contract_specification
50
+
51
+
52
+ def _field_from_nested_field(nested_field: iceberg_types.NestedField) -> Field:
53
+ """
54
+ Converts an Iceberg NestedField into a Field object for the data contract.
55
+
56
+ Args:
57
+ nested_field: The Iceberg NestedField to convert.
58
+
59
+ Returns:
60
+ Field: The generated Field object.
61
+ """
62
+ field = Field(
63
+ title=nested_field.name,
64
+ required=nested_field.required,
65
+ config=build_field_config(nested_field),
66
+ )
67
+
68
+ if nested_field.doc is not None:
69
+ field.description = nested_field.doc
70
+
71
+ return _type_from_iceberg_type(field, nested_field.field_type)
72
+
73
+
74
+ def _type_from_iceberg_type(field: Field, iceberg_type: iceberg_types.IcebergType) -> Field:
75
+ """
76
+ Maps Iceberg data types to the Data Contract type system and updates the field.
77
+
78
+ Args:
79
+ field: The Field object to update.
80
+ iceberg_type: The Iceberg data type to map.
81
+
82
+ Returns:
83
+ Field: The updated Field object.
84
+ """
85
+ field.type = _data_type_from_iceberg(iceberg_type)
86
+
87
+ if field.type == "array":
88
+ field.items = _type_from_iceberg_type(Field(required=iceberg_type.element_required), iceberg_type.element_type)
89
+
90
+ elif field.type == "map":
91
+ field.keys = _type_from_iceberg_type(Field(required=True), iceberg_type.key_type)
92
+ field.values = _type_from_iceberg_type(Field(required=iceberg_type.value_required), iceberg_type.value_type)
93
+
94
+ elif field.type == "object":
95
+ field.fields = {nf.name: _field_from_nested_field(nf) for nf in iceberg_type.fields}
96
+
97
+ return field
98
+
99
+
100
+ def build_field_config(iceberg_field: iceberg_types.NestedField) -> Dict[str, Any]:
101
+ config = {}
102
+
103
+ if iceberg_field.field_id > 0:
104
+ config["icebergFieldId"] = iceberg_field.field_id
105
+
106
+ if iceberg_field.initial_default is not None:
107
+ config["icebergInitialDefault"] = iceberg_field.initial_default
108
+
109
+ if iceberg_field.write_default is not None:
110
+ config["icebergWriteDefault"] = iceberg_field.write_default
111
+
112
+ return config
113
+
114
+
115
+ def _data_type_from_iceberg(type: iceberg_types.IcebergType) -> str:
116
+ """
117
+ Convert an Iceberg field type to a datacontract field type
118
+
119
+ Args:
120
+ type: The Iceberg field type
121
+
122
+ Returns:
123
+ str: The datacontract field type
124
+ """
125
+ if isinstance(type, iceberg_types.BooleanType):
126
+ return "boolean"
127
+ if isinstance(type, iceberg_types.IntegerType):
128
+ return "integer"
129
+ if isinstance(type, iceberg_types.LongType):
130
+ return "long"
131
+ if isinstance(type, iceberg_types.FloatType):
132
+ return "float"
133
+ if isinstance(type, iceberg_types.DoubleType):
134
+ return "double"
135
+ if isinstance(type, iceberg_types.DecimalType):
136
+ return "decimal"
137
+ if isinstance(type, iceberg_types.DateType):
138
+ return "date"
139
+ if isinstance(type, iceberg_types.TimeType):
140
+ # there isn't a great mapping for the iceberg type "time", just map to string for now
141
+ return "string"
142
+ if isinstance(type, iceberg_types.TimestampType):
143
+ return "timestamp_ntz"
144
+ if isinstance(type, iceberg_types.TimestamptzType):
145
+ return "timestamp_tz"
146
+ if isinstance(type, iceberg_types.StringType):
147
+ return "string"
148
+ if isinstance(type, iceberg_types.UUIDType):
149
+ return "string"
150
+ if isinstance(type, iceberg_types.BinaryType):
151
+ return "bytes"
152
+ if isinstance(type, iceberg_types.FixedType):
153
+ return "bytes"
154
+ if isinstance(type, iceberg_types.MapType):
155
+ return "map"
156
+ if isinstance(type, iceberg_types.ListType):
157
+ return "array"
158
+ if isinstance(type, iceberg_types.StructType):
159
+ return "object"
160
+
161
+ raise ValueError(f"Unknown Iceberg type: {type}")
@@ -29,6 +29,8 @@ class ImportFormat(str, Enum):
29
29
  odcs = "odcs"
30
30
  unity = "unity"
31
31
  spark = "spark"
32
+ iceberg = "iceberg"
33
+ parquet = "parquet"
32
34
 
33
35
  @classmethod
34
36
  def get_supported_formats(cls):
@@ -1,6 +1,7 @@
1
1
  import importlib.util
2
2
  import sys
3
- from datacontract.imports.importer import ImportFormat, Importer
3
+
4
+ from datacontract.imports.importer import Importer, ImportFormat
4
5
 
5
6
 
6
7
  class ImporterFactory:
@@ -93,3 +94,13 @@ importer_factory.register_lazy_importer(
93
94
  module_path="datacontract.imports.dbml_importer",
94
95
  class_name="DBMLImporter",
95
96
  )
97
+ importer_factory.register_lazy_importer(
98
+ name=ImportFormat.iceberg,
99
+ module_path="datacontract.imports.iceberg_importer",
100
+ class_name="IcebergImporter",
101
+ )
102
+ importer_factory.register_lazy_importer(
103
+ name=ImportFormat.parquet,
104
+ module_path="datacontract.imports.parquet_importer",
105
+ class_name="ParquetImporter",
106
+ )
@@ -3,7 +3,7 @@ import json
3
3
  import fastjsonschema
4
4
 
5
5
  from datacontract.imports.importer import Importer
6
- from datacontract.model.data_contract_specification import DataContractSpecification, Model, Field, Definition
6
+ from datacontract.model.data_contract_specification import DataContractSpecification, Definition, Field, Model
7
7
  from datacontract.model.exceptions import DataContractException
8
8
 
9
9
 
@@ -111,7 +111,8 @@ def schema_to_args(property_schema, is_required: bool = None) -> dict:
111
111
  nested_properties = property_schema.get("properties")
112
112
  if nested_properties is not None:
113
113
  # recursive call for complex nested properties
114
- field_kwargs["fields"] = jsonschema_to_args(nested_properties, property_schema["required"])
114
+ required = property_schema.get("required", [])
115
+ field_kwargs["fields"] = jsonschema_to_args(nested_properties, required)
115
116
 
116
117
  return field_kwargs
117
118
 
@@ -1,47 +1,12 @@
1
- import datetime
2
- import logging
3
- from typing import Any, Dict, List
4
1
  import yaml
2
+
5
3
  from datacontract.imports.importer import Importer
4
+ from datacontract.lint.resources import read_resource
6
5
  from datacontract.model.data_contract_specification import (
7
- Availability,
8
- Contact,
9
6
  DataContractSpecification,
10
- Info,
11
- Model,
12
- Field,
13
- Retention,
14
- ServiceLevel,
15
- Terms,
16
7
  )
17
8
  from datacontract.model.exceptions import DataContractException
18
9
 
19
- DATACONTRACT_TYPES = [
20
- "string",
21
- "text",
22
- "varchar",
23
- "number",
24
- "decimal",
25
- "numeric",
26
- "int",
27
- "integer",
28
- "long",
29
- "bigint",
30
- "float",
31
- "double",
32
- "boolean",
33
- "timestamp",
34
- "timestamp_tz",
35
- "timestamp_ntz",
36
- "date",
37
- "array",
38
- "bytes",
39
- "object",
40
- "record",
41
- "struct",
42
- "null",
43
- ]
44
-
45
10
 
46
11
  class OdcsImporter(Importer):
47
12
  def import_source(
@@ -52,8 +17,7 @@ class OdcsImporter(Importer):
52
17
 
53
18
  def import_odcs(data_contract_specification: DataContractSpecification, source: str) -> DataContractSpecification:
54
19
  try:
55
- with open(source, "r") as file:
56
- odcs_contract = yaml.safe_load(file.read())
20
+ odcs_contract = yaml.safe_load(read_resource(source))
57
21
 
58
22
  except Exception as e:
59
23
  raise DataContractException(
@@ -64,137 +28,30 @@ def import_odcs(data_contract_specification: DataContractSpecification, source:
64
28
  original_exception=e,
65
29
  )
66
30
 
67
- data_contract_specification.id = odcs_contract["uuid"]
68
- data_contract_specification.info = import_info(odcs_contract)
69
- data_contract_specification.terms = import_terms(odcs_contract)
70
- data_contract_specification.servicelevels = import_servicelevels(odcs_contract)
71
- data_contract_specification.models = import_models(odcs_contract)
72
-
73
- return data_contract_specification
74
-
75
-
76
- def import_info(odcs_contract: Dict[str, Any]) -> Info:
77
- info = Info(title=odcs_contract.get("quantumName"), version=odcs_contract.get("version"))
78
-
79
- if odcs_contract.get("description").get("purpose") is not None:
80
- info.description = odcs_contract.get("description").get("purpose")
81
-
82
- if odcs_contract.get("datasetDomain") is not None:
83
- info.owner = odcs_contract.get("datasetDomain")
84
-
85
- if odcs_contract.get("productDl") is not None or odcs_contract.get("productFeedbackUrl") is not None:
86
- contact = Contact()
87
- if odcs_contract.get("productDl") is not None:
88
- contact.name = odcs_contract.get("productDl")
89
- if odcs_contract.get("productFeedbackUrl") is not None:
90
- contact.url = odcs_contract.get("productFeedbackUrl")
91
-
92
- info.contact = contact
93
-
94
- return info
31
+ odcs_kind = odcs_contract.get("kind")
32
+ odcs_api_version = odcs_contract.get("apiVersion")
95
33
 
34
+ # if odcs_kind is not DataContract throw exception
35
+ if odcs_kind != "DataContract":
36
+ raise DataContractException(
37
+ type="schema",
38
+ name="Importing ODCS contract",
39
+ reason=f"Unsupported ODCS kind: {odcs_kind}. Is this a valid ODCS data contract?",
40
+ engine="datacontract",
41
+ )
96
42
 
97
- def import_terms(odcs_contract: Dict[str, Any]) -> Terms | None:
98
- if (
99
- odcs_contract.get("description").get("usage") is not None
100
- or odcs_contract.get("description").get("limitations") is not None
101
- or odcs_contract.get("price") is not None
102
- ):
103
- terms = Terms()
104
- if odcs_contract.get("description").get("usage") is not None:
105
- terms.usage = odcs_contract.get("description").get("usage")
106
- if odcs_contract.get("description").get("limitations") is not None:
107
- terms.limitations = odcs_contract.get("description").get("limitations")
108
- if odcs_contract.get("price") is not None:
109
- terms.billing = f"{odcs_contract.get('price').get('priceAmount')} {odcs_contract.get('price').get('priceCurrency')} / {odcs_contract.get('price').get('priceUnit')}"
110
-
111
- return terms
112
- else:
113
- return None
114
-
115
-
116
- def import_servicelevels(odcs_contract: Dict[str, Any]) -> ServiceLevel:
117
- # find the two properties we can map (based on the examples)
118
- sla_properties = odcs_contract.get("slaProperties") if odcs_contract.get("slaProperties") is not None else []
119
- availability = next((p for p in sla_properties if p["property"] == "generalAvailability"), None)
120
- retention = next((p for p in sla_properties if p["property"] == "retention"), None)
121
-
122
- if availability is not None or retention is not None:
123
- servicelevel = ServiceLevel()
124
-
125
- if availability is not None:
126
- value = availability.get("value")
127
- if isinstance(value, datetime.datetime):
128
- value = value.isoformat()
129
- servicelevel.availability = Availability(description=value)
130
-
131
- if retention is not None:
132
- servicelevel.retention = Retention(period=f"{retention.get('value')}{retention.get('unit')}")
133
-
134
- return servicelevel
135
- else:
136
- return None
137
-
138
-
139
- def import_models(odcs_contract: Dict[str, Any]) -> Dict[str, Model]:
140
- custom_type_mappings = get_custom_type_mappings(odcs_contract.get("customProperties"))
141
-
142
- odcs_tables = odcs_contract.get("dataset") if odcs_contract.get("dataset") is not None else []
143
- result = {}
144
-
145
- for table in odcs_tables:
146
- description = table.get("description") if table.get("description") is not None else ""
147
- model = Model(description=" ".join(description.splitlines()), type="table")
148
- model.fields = import_fields(table.get("columns"), custom_type_mappings)
149
- result[table.get("table")] = model
150
-
151
- return result
152
-
153
-
154
- def import_fields(odcs_columns: Dict[str, Any], custom_type_mappings: Dict[str, str]) -> Dict[str, Field]:
155
- logger = logging.getLogger(__name__)
156
- result = {}
157
-
158
- for column in odcs_columns:
159
- mapped_type = map_type(column.get("logicalType"), custom_type_mappings)
160
- if mapped_type is not None:
161
- description = column.get("description") if column.get("description") is not None else ""
162
- field = Field(
163
- description=" ".join(description.splitlines()),
164
- type=mapped_type,
165
- title=column.get("businessName") if column.get("businessName") is not None else "",
166
- required=not column.get("isNullable") if column.get("isNullable") is not None else False,
167
- primary=column.get("isPrimary") if column.get("isPrimary") is not None else False,
168
- unique=column.get("isUnique") if column.get("isUnique") is not None else False,
169
- classification=column.get("classification") if column.get("classification") is not None else "",
170
- tags=column.get("tags") if column.get("tags") is not None else [],
171
- )
172
- result[column["column"]] = field
173
- else:
174
- logger.info(
175
- f"Can't properly map {column.get('column')} to the Datacontract Mapping types, as there is no equivalent or special mapping. Consider introducing a customProperty 'dc_mapping_{column.get('logicalName')}' that defines your expected type as the 'value'"
176
- )
177
-
178
- return result
43
+ if odcs_api_version.startswith("v2."):
44
+ from datacontract.imports.odcs_v2_importer import import_odcs_v2
179
45
 
46
+ return import_odcs_v2(data_contract_specification, source)
47
+ elif odcs_api_version.startswith("v3."):
48
+ from datacontract.imports.odcs_v3_importer import import_odcs_v3
180
49
 
181
- def map_type(odcs_type: str, custom_mappings: Dict[str, str]) -> str | None:
182
- t = odcs_type.lower()
183
- if t in DATACONTRACT_TYPES:
184
- return t
185
- elif custom_mappings.get(t) is not None:
186
- return custom_mappings.get(t)
50
+ return import_odcs_v3(data_contract_specification, source)
187
51
  else:
188
- return None
189
-
190
-
191
- def get_custom_type_mappings(odcs_custom_properties: List[Any]) -> Dict[str, str]:
192
- result = {}
193
- if odcs_custom_properties is not None:
194
- for prop in odcs_custom_properties:
195
- if prop["property"].startswith("dc_mapping_"):
196
- odcs_type_name = prop["property"].substring(11)
197
- datacontract_type = prop["value"]
198
- result[odcs_type_name] = datacontract_type
199
-
200
- return result
52
+ raise DataContractException(
53
+ type="schema",
54
+ name="Importing ODCS contract",
55
+ reason=f"Unsupported ODCS API version: {odcs_api_version}",
56
+ engine="datacontract",
57
+ )
@@ -0,0 +1,177 @@
1
+ import datetime
2
+ import logging
3
+ from typing import Any, Dict, List
4
+
5
+ import yaml
6
+
7
+ from datacontract.imports.importer import Importer
8
+ from datacontract.model.data_contract_specification import (
9
+ DATACONTRACT_TYPES,
10
+ Availability,
11
+ Contact,
12
+ DataContractSpecification,
13
+ Field,
14
+ Info,
15
+ Model,
16
+ Retention,
17
+ ServiceLevel,
18
+ Terms,
19
+ )
20
+ from datacontract.model.exceptions import DataContractException
21
+
22
+
23
+ class OdcsImporter(Importer):
24
+ def import_source(
25
+ self, data_contract_specification: DataContractSpecification, source: str, import_args: dict
26
+ ) -> DataContractSpecification:
27
+ return import_odcs_v2(data_contract_specification, source)
28
+
29
+
30
+ def import_odcs_v2(data_contract_specification: DataContractSpecification, source: str) -> DataContractSpecification:
31
+ try:
32
+ with open(source, "r") as file:
33
+ odcs_contract = yaml.safe_load(file.read())
34
+
35
+ except Exception as e:
36
+ raise DataContractException(
37
+ type="schema",
38
+ name="Parse ODCS contract",
39
+ reason=f"Failed to parse odcs contract from {source}",
40
+ engine="datacontract",
41
+ original_exception=e,
42
+ )
43
+
44
+ data_contract_specification.id = odcs_contract["uuid"]
45
+ data_contract_specification.info = import_info(odcs_contract)
46
+ data_contract_specification.terms = import_terms(odcs_contract)
47
+ data_contract_specification.servicelevels = import_servicelevels(odcs_contract)
48
+ data_contract_specification.models = import_models(odcs_contract)
49
+
50
+ return data_contract_specification
51
+
52
+
53
+ def import_info(odcs_contract: Dict[str, Any]) -> Info:
54
+ info = Info(title=odcs_contract.get("quantumName"), version=odcs_contract.get("version"))
55
+
56
+ if odcs_contract.get("description").get("purpose") is not None:
57
+ info.description = odcs_contract.get("description").get("purpose")
58
+
59
+ if odcs_contract.get("datasetDomain") is not None:
60
+ info.owner = odcs_contract.get("datasetDomain")
61
+
62
+ if odcs_contract.get("productDl") is not None or odcs_contract.get("productFeedbackUrl") is not None:
63
+ contact = Contact()
64
+ if odcs_contract.get("productDl") is not None:
65
+ contact.name = odcs_contract.get("productDl")
66
+ if odcs_contract.get("productFeedbackUrl") is not None:
67
+ contact.url = odcs_contract.get("productFeedbackUrl")
68
+
69
+ info.contact = contact
70
+
71
+ return info
72
+
73
+
74
+ def import_terms(odcs_contract: Dict[str, Any]) -> Terms | None:
75
+ if (
76
+ odcs_contract.get("description").get("usage") is not None
77
+ or odcs_contract.get("description").get("limitations") is not None
78
+ or odcs_contract.get("price") is not None
79
+ ):
80
+ terms = Terms()
81
+ if odcs_contract.get("description").get("usage") is not None:
82
+ terms.usage = odcs_contract.get("description").get("usage")
83
+ if odcs_contract.get("description").get("limitations") is not None:
84
+ terms.limitations = odcs_contract.get("description").get("limitations")
85
+ if odcs_contract.get("price") is not None:
86
+ terms.billing = f"{odcs_contract.get('price').get('priceAmount')} {odcs_contract.get('price').get('priceCurrency')} / {odcs_contract.get('price').get('priceUnit')}"
87
+
88
+ return terms
89
+ else:
90
+ return None
91
+
92
+
93
+ def import_servicelevels(odcs_contract: Dict[str, Any]) -> ServiceLevel:
94
+ # find the two properties we can map (based on the examples)
95
+ sla_properties = odcs_contract.get("slaProperties") if odcs_contract.get("slaProperties") is not None else []
96
+ availability = next((p for p in sla_properties if p["property"] == "generalAvailability"), None)
97
+ retention = next((p for p in sla_properties if p["property"] == "retention"), None)
98
+
99
+ if availability is not None or retention is not None:
100
+ servicelevel = ServiceLevel()
101
+
102
+ if availability is not None:
103
+ value = availability.get("value")
104
+ if isinstance(value, datetime.datetime):
105
+ value = value.isoformat()
106
+ servicelevel.availability = Availability(description=value)
107
+
108
+ if retention is not None:
109
+ servicelevel.retention = Retention(period=f"{retention.get('value')}{retention.get('unit')}")
110
+
111
+ return servicelevel
112
+ else:
113
+ return None
114
+
115
+
116
+ def import_models(odcs_contract: Dict[str, Any]) -> Dict[str, Model]:
117
+ custom_type_mappings = get_custom_type_mappings(odcs_contract.get("customProperties"))
118
+
119
+ odcs_tables = odcs_contract.get("dataset") if odcs_contract.get("dataset") is not None else []
120
+ result = {}
121
+
122
+ for table in odcs_tables:
123
+ description = table.get("description") if table.get("description") is not None else ""
124
+ model = Model(description=" ".join(description.splitlines()), type="table")
125
+ model.fields = import_fields(table.get("columns"), custom_type_mappings)
126
+ result[table.get("table")] = model
127
+
128
+ return result
129
+
130
+
131
+ def import_fields(odcs_columns: Dict[str, Any], custom_type_mappings: Dict[str, str]) -> Dict[str, Field]:
132
+ logger = logging.getLogger(__name__)
133
+ result = {}
134
+
135
+ for column in odcs_columns:
136
+ mapped_type = map_type(column.get("logicalType"), custom_type_mappings)
137
+ if mapped_type is not None:
138
+ description = column.get("description") if column.get("description") is not None else ""
139
+ field = Field(
140
+ description=" ".join(description.splitlines()),
141
+ type=mapped_type,
142
+ title=column.get("businessName") if column.get("businessName") is not None else "",
143
+ required=not column.get("isNullable") if column.get("isNullable") is not None else False,
144
+ primary=column.get("isPrimary") if column.get("isPrimary") is not None else False,
145
+ unique=column.get("isUnique") if column.get("isUnique") is not None else False,
146
+ classification=column.get("classification") if column.get("classification") is not None else "",
147
+ tags=column.get("tags") if column.get("tags") is not None else [],
148
+ )
149
+ result[column["column"]] = field
150
+ else:
151
+ logger.info(
152
+ f"Can't properly map {column.get('column')} to the Datacontract Mapping types, as there is no equivalent or special mapping. Consider introducing a customProperty 'dc_mapping_{column.get('logicalName')}' that defines your expected type as the 'value'"
153
+ )
154
+
155
+ return result
156
+
157
+
158
+ def map_type(odcs_type: str, custom_mappings: Dict[str, str]) -> str | None:
159
+ t = odcs_type.lower()
160
+ if t in DATACONTRACT_TYPES:
161
+ return t
162
+ elif custom_mappings.get(t) is not None:
163
+ return custom_mappings.get(t)
164
+ else:
165
+ return None
166
+
167
+
168
+ def get_custom_type_mappings(odcs_custom_properties: List[Any]) -> Dict[str, str]:
169
+ result = {}
170
+ if odcs_custom_properties is not None:
171
+ for prop in odcs_custom_properties:
172
+ if prop["property"].startswith("dc_mapping_"):
173
+ odcs_type_name = prop["property"].substring(11)
174
+ datacontract_type = prop["value"]
175
+ result[odcs_type_name] = datacontract_type
176
+
177
+ return result