avrotize 2.21.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.
- avrotize/__init__.py +66 -0
- avrotize/__main__.py +6 -0
- avrotize/_version.py +34 -0
- avrotize/asn1toavro.py +160 -0
- avrotize/avrotize.py +152 -0
- avrotize/avrotocpp/CMakeLists.txt.jinja +77 -0
- avrotize/avrotocpp/build.bat.jinja +7 -0
- avrotize/avrotocpp/build.sh.jinja +7 -0
- avrotize/avrotocpp/dataclass_body.jinja +108 -0
- avrotize/avrotocpp/vcpkg.json.jinja +21 -0
- avrotize/avrotocpp.py +483 -0
- avrotize/avrotocsharp/README.md.jinja +166 -0
- avrotize/avrotocsharp/class_test.cs.jinja +266 -0
- avrotize/avrotocsharp/dataclass_core.jinja +293 -0
- avrotize/avrotocsharp/enum_test.cs.jinja +20 -0
- avrotize/avrotocsharp/project.csproj.jinja +30 -0
- avrotize/avrotocsharp/project.sln.jinja +34 -0
- avrotize/avrotocsharp/run_coverage.ps1.jinja +98 -0
- avrotize/avrotocsharp/run_coverage.sh.jinja +149 -0
- avrotize/avrotocsharp/testproject.csproj.jinja +19 -0
- avrotize/avrotocsharp.py +1180 -0
- avrotize/avrotocsv.py +121 -0
- avrotize/avrotodatapackage.py +173 -0
- avrotize/avrotodb.py +1383 -0
- avrotize/avrotogo/go_enum.jinja +12 -0
- avrotize/avrotogo/go_helpers.jinja +31 -0
- avrotize/avrotogo/go_struct.jinja +151 -0
- avrotize/avrotogo/go_test.jinja +47 -0
- avrotize/avrotogo/go_union.jinja +38 -0
- avrotize/avrotogo.py +476 -0
- avrotize/avrotographql.py +197 -0
- avrotize/avrotoiceberg.py +210 -0
- avrotize/avrotojava/class_test.java.jinja +212 -0
- avrotize/avrotojava/enum_test.java.jinja +21 -0
- avrotize/avrotojava/testproject.pom.jinja +54 -0
- avrotize/avrotojava.py +2156 -0
- avrotize/avrotojs.py +250 -0
- avrotize/avrotojsons.py +481 -0
- avrotize/avrotojstruct.py +345 -0
- avrotize/avrotokusto.py +364 -0
- avrotize/avrotomd/README.md.jinja +49 -0
- avrotize/avrotomd.py +137 -0
- avrotize/avrotools.py +168 -0
- avrotize/avrotoparquet.py +208 -0
- avrotize/avrotoproto.py +359 -0
- avrotize/avrotopython/dataclass_core.jinja +241 -0
- avrotize/avrotopython/enum_core.jinja +87 -0
- avrotize/avrotopython/pyproject_toml.jinja +18 -0
- avrotize/avrotopython/test_class.jinja +97 -0
- avrotize/avrotopython/test_enum.jinja +23 -0
- avrotize/avrotopython.py +626 -0
- avrotize/avrotorust/dataclass_enum.rs.jinja +74 -0
- avrotize/avrotorust/dataclass_struct.rs.jinja +204 -0
- avrotize/avrotorust/dataclass_union.rs.jinja +105 -0
- avrotize/avrotorust.py +435 -0
- avrotize/avrotots/class_core.ts.jinja +140 -0
- avrotize/avrotots/class_test.ts.jinja +77 -0
- avrotize/avrotots/enum_core.ts.jinja +46 -0
- avrotize/avrotots/gitignore.jinja +34 -0
- avrotize/avrotots/index.ts.jinja +0 -0
- avrotize/avrotots/package.json.jinja +23 -0
- avrotize/avrotots/tsconfig.json.jinja +21 -0
- avrotize/avrotots.py +687 -0
- avrotize/avrotoxsd.py +344 -0
- avrotize/cddltostructure.py +1841 -0
- avrotize/commands.json +3496 -0
- avrotize/common.py +834 -0
- avrotize/constants.py +87 -0
- avrotize/csvtoavro.py +132 -0
- avrotize/datapackagetoavro.py +76 -0
- avrotize/dependencies/cpp/vcpkg/vcpkg.json +19 -0
- avrotize/dependencies/cs/net90/dependencies.csproj +29 -0
- avrotize/dependencies/go/go121/go.mod +6 -0
- avrotize/dependencies/java/jdk21/pom.xml +91 -0
- avrotize/dependencies/python/py312/requirements.txt +13 -0
- avrotize/dependencies/rust/stable/Cargo.toml +17 -0
- avrotize/dependencies/typescript/node22/package.json +16 -0
- avrotize/dependency_resolver.py +348 -0
- avrotize/dependency_version.py +432 -0
- avrotize/generic/generic.avsc +57 -0
- avrotize/jsonstoavro.py +2167 -0
- avrotize/jsonstostructure.py +2864 -0
- avrotize/jstructtoavro.py +878 -0
- avrotize/kstructtoavro.py +93 -0
- avrotize/kustotoavro.py +455 -0
- avrotize/openapitostructure.py +717 -0
- avrotize/parquettoavro.py +157 -0
- avrotize/proto2parser.py +498 -0
- avrotize/proto3parser.py +403 -0
- avrotize/prototoavro.py +382 -0
- avrotize/prototypes/any.avsc +19 -0
- avrotize/prototypes/api.avsc +106 -0
- avrotize/prototypes/duration.avsc +20 -0
- avrotize/prototypes/field_mask.avsc +18 -0
- avrotize/prototypes/struct.avsc +60 -0
- avrotize/prototypes/timestamp.avsc +20 -0
- avrotize/prototypes/type.avsc +253 -0
- avrotize/prototypes/wrappers.avsc +117 -0
- avrotize/structuretocddl.py +597 -0
- avrotize/structuretocpp/CMakeLists.txt.jinja +76 -0
- avrotize/structuretocpp/build.bat.jinja +3 -0
- avrotize/structuretocpp/build.sh.jinja +3 -0
- avrotize/structuretocpp/dataclass_body.jinja +50 -0
- avrotize/structuretocpp/vcpkg.json.jinja +11 -0
- avrotize/structuretocpp.py +697 -0
- avrotize/structuretocsharp/class_test.cs.jinja +180 -0
- avrotize/structuretocsharp/dataclass_core.jinja +156 -0
- avrotize/structuretocsharp/enum_test.cs.jinja +36 -0
- avrotize/structuretocsharp/json_structure_converters.cs.jinja +399 -0
- avrotize/structuretocsharp/program.cs.jinja +49 -0
- avrotize/structuretocsharp/project.csproj.jinja +17 -0
- avrotize/structuretocsharp/project.sln.jinja +34 -0
- avrotize/structuretocsharp/testproject.csproj.jinja +18 -0
- avrotize/structuretocsharp/tuple_converter.cs.jinja +121 -0
- avrotize/structuretocsharp.py +2295 -0
- avrotize/structuretocsv.py +365 -0
- avrotize/structuretodatapackage.py +659 -0
- avrotize/structuretodb.py +1125 -0
- avrotize/structuretogo/go_enum.jinja +12 -0
- avrotize/structuretogo/go_helpers.jinja +26 -0
- avrotize/structuretogo/go_interface.jinja +18 -0
- avrotize/structuretogo/go_struct.jinja +187 -0
- avrotize/structuretogo/go_test.jinja +70 -0
- avrotize/structuretogo.py +729 -0
- avrotize/structuretographql.py +502 -0
- avrotize/structuretoiceberg.py +355 -0
- avrotize/structuretojava/choice_core.jinja +34 -0
- avrotize/structuretojava/class_core.jinja +23 -0
- avrotize/structuretojava/enum_core.jinja +18 -0
- avrotize/structuretojava/equals_hashcode.jinja +30 -0
- avrotize/structuretojava/pom.xml.jinja +26 -0
- avrotize/structuretojava/tuple_core.jinja +49 -0
- avrotize/structuretojava.py +938 -0
- avrotize/structuretojs/class_core.js.jinja +33 -0
- avrotize/structuretojs/enum_core.js.jinja +10 -0
- avrotize/structuretojs/package.json.jinja +12 -0
- avrotize/structuretojs/test_class.js.jinja +84 -0
- avrotize/structuretojs/test_enum.js.jinja +58 -0
- avrotize/structuretojs/test_runner.js.jinja +45 -0
- avrotize/structuretojs.py +657 -0
- avrotize/structuretojsons.py +498 -0
- avrotize/structuretokusto.py +639 -0
- avrotize/structuretomd/README.md.jinja +204 -0
- avrotize/structuretomd.py +322 -0
- avrotize/structuretoproto.py +764 -0
- avrotize/structuretopython/dataclass_core.jinja +363 -0
- avrotize/structuretopython/enum_core.jinja +45 -0
- avrotize/structuretopython/map_alias.jinja +21 -0
- avrotize/structuretopython/pyproject_toml.jinja +23 -0
- avrotize/structuretopython/test_class.jinja +103 -0
- avrotize/structuretopython/test_enum.jinja +34 -0
- avrotize/structuretopython.py +799 -0
- avrotize/structuretorust/dataclass_enum.rs.jinja +63 -0
- avrotize/structuretorust/dataclass_struct.rs.jinja +121 -0
- avrotize/structuretorust/dataclass_union.rs.jinja +81 -0
- avrotize/structuretorust.py +714 -0
- avrotize/structuretots/class_core.ts.jinja +78 -0
- avrotize/structuretots/enum_core.ts.jinja +6 -0
- avrotize/structuretots/gitignore.jinja +8 -0
- avrotize/structuretots/index.ts.jinja +1 -0
- avrotize/structuretots/package.json.jinja +39 -0
- avrotize/structuretots/test_class.ts.jinja +35 -0
- avrotize/structuretots/tsconfig.json.jinja +21 -0
- avrotize/structuretots.py +740 -0
- avrotize/structuretoxsd.py +679 -0
- avrotize/xsdtoavro.py +413 -0
- avrotize-2.21.1.dist-info/METADATA +1319 -0
- avrotize-2.21.1.dist-info/RECORD +171 -0
- avrotize-2.21.1.dist-info/WHEEL +4 -0
- avrotize-2.21.1.dist-info/entry_points.txt +3 -0
- avrotize-2.21.1.dist-info/licenses/LICENSE +201 -0
avrotize/avrotokusto.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
from typing import Any, List
|
|
6
|
+
from avrotize.common import build_flat_type_dict, inline_avro_references, strip_first_doc
|
|
7
|
+
from azure.kusto.data import KustoClient, KustoConnectionStringBuilder, ClientRequestProperties
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AvroToKusto:
|
|
11
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
12
|
+
|
|
13
|
+
def ___init___(self):
|
|
14
|
+
"""Initializes a new instance of the AvroToKusto class."""
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
def convert_record_to_kusto(self, type_dict:dict, recordschema: dict, emit_cloudevents_columns: bool, emit_cloudevents_dispatch_table: bool) -> List[str]:
|
|
18
|
+
"""Converts an Avro record schema to a Kusto table schema."""
|
|
19
|
+
# Get the name and fields of the top-level record
|
|
20
|
+
table_name = recordschema["name"]
|
|
21
|
+
fields = recordschema["fields"]
|
|
22
|
+
|
|
23
|
+
# Create a StringBuilder to store the kusto statements
|
|
24
|
+
kusto = []
|
|
25
|
+
|
|
26
|
+
# Append the create table statement with the column names and types
|
|
27
|
+
kusto.append(f".create-merge table [{table_name}] (")
|
|
28
|
+
columns = []
|
|
29
|
+
for field in fields:
|
|
30
|
+
column_name = field["name"]
|
|
31
|
+
column_type = self.convert_avro_type_to_kusto_type(field["type"])
|
|
32
|
+
columns.append(f" [{column_name}]: {column_type}")
|
|
33
|
+
if emit_cloudevents_columns:
|
|
34
|
+
columns.append(" [___type]: string")
|
|
35
|
+
columns.append(" [___source]: string")
|
|
36
|
+
columns.append(" [___id]: string")
|
|
37
|
+
columns.append(" [___time]: datetime")
|
|
38
|
+
columns.append(" [___subject]: string")
|
|
39
|
+
kusto.append(",\n".join(columns))
|
|
40
|
+
kusto.append(");")
|
|
41
|
+
kusto.append("")
|
|
42
|
+
|
|
43
|
+
# Add the doc string as table metadata
|
|
44
|
+
if "doc" in recordschema:
|
|
45
|
+
doc_data = recordschema["doc"]
|
|
46
|
+
doc_data = (doc_data[:997] + "...") if len(doc_data) > 1000 else doc_data
|
|
47
|
+
doc_string = json.dumps(json.dumps({
|
|
48
|
+
"description": doc_data
|
|
49
|
+
}))
|
|
50
|
+
kusto.append(
|
|
51
|
+
f".alter table [{table_name}] docstring {doc_string};")
|
|
52
|
+
kusto.append("")
|
|
53
|
+
|
|
54
|
+
doc_string_statement = []
|
|
55
|
+
for field in fields:
|
|
56
|
+
column_name = field["name"]
|
|
57
|
+
if "doc" in field:
|
|
58
|
+
doc_data = field["doc"]
|
|
59
|
+
if len(doc_data) > 900:
|
|
60
|
+
doc_data = (doc_data[:897] + "...")
|
|
61
|
+
doc_content = {
|
|
62
|
+
"description": doc_data
|
|
63
|
+
}
|
|
64
|
+
if isinstance(field["type"], list) or isinstance(field["type"], dict):
|
|
65
|
+
inline_schema = inline_avro_references(field["type"].copy(), type_dict.copy(), '')
|
|
66
|
+
if (len(json.dumps(inline_schema)) + len(doc_data)) > 900:
|
|
67
|
+
while strip_first_doc(inline_schema):
|
|
68
|
+
if (len(json.dumps(inline_schema)) + len(doc_data)) < 900:
|
|
69
|
+
break
|
|
70
|
+
if (len(json.dumps(inline_schema)) + len(doc_data)) > 900:
|
|
71
|
+
doc_content["schema"] = '{ "doc": "Schema too large to inline. Please refer to the Avro schema for more details." }'
|
|
72
|
+
else:
|
|
73
|
+
doc_content["schema"] = inline_schema
|
|
74
|
+
else:
|
|
75
|
+
doc_content["schema"] = inline_schema
|
|
76
|
+
doc = json.dumps(json.dumps(doc_content))
|
|
77
|
+
doc_string_statement.append(f" [{column_name}]: {doc}")
|
|
78
|
+
if doc_string_statement and emit_cloudevents_columns:
|
|
79
|
+
doc_string_statement.extend([
|
|
80
|
+
" [___type] : 'Event type'",
|
|
81
|
+
" [___source]: 'Context origin/source of the event'",
|
|
82
|
+
" [___id]: 'Event identifier'",
|
|
83
|
+
" [___time]: 'Event generation time'",
|
|
84
|
+
" [___subject]: 'Context subject of the event'"
|
|
85
|
+
])
|
|
86
|
+
if doc_string_statement:
|
|
87
|
+
kusto.append(f".alter table [{table_name}] column-docstrings (")
|
|
88
|
+
kusto.append(",\n".join(doc_string_statement))
|
|
89
|
+
kusto.append(");")
|
|
90
|
+
kusto.append("")
|
|
91
|
+
|
|
92
|
+
# add the JSON mapping for the table
|
|
93
|
+
# .create-or-alter table dfl_data_events ingestion json mapping
|
|
94
|
+
kusto.append(
|
|
95
|
+
f".create-or-alter table [{table_name}] ingestion json mapping \"{table_name}_json_flat\"")
|
|
96
|
+
kusto.append("```\n[")
|
|
97
|
+
if emit_cloudevents_columns:
|
|
98
|
+
kusto.append(" {\"column\": \"___type\", \"path\": \"$.type\"},")
|
|
99
|
+
kusto.append(
|
|
100
|
+
" {\"column\": \"___source\", \"path\": \"$.source\"},")
|
|
101
|
+
kusto.append(" {\"column\": \"___id\", \"path\": \"$.id\"},")
|
|
102
|
+
kusto.append(" {\"column\": \"___time\", \"path\": \"$.time\"},")
|
|
103
|
+
kusto.append(
|
|
104
|
+
" {\"column\": \"___subject\", \"path\": \"$.subject\"},")
|
|
105
|
+
for field in fields:
|
|
106
|
+
json_name = column_name = field["name"]
|
|
107
|
+
if 'altnames' in field:
|
|
108
|
+
if 'kql' in field['altnames']:
|
|
109
|
+
column_name = field['altnames']['kql']
|
|
110
|
+
if 'json' in field['altnames']:
|
|
111
|
+
json_name = field['altnames']['json']
|
|
112
|
+
kusto.append(
|
|
113
|
+
f" {{\"column\": \"{column_name}\", \"path\": \"$.{json_name}\"}},")
|
|
114
|
+
kusto.append("]\n```\n\n")
|
|
115
|
+
|
|
116
|
+
if emit_cloudevents_columns:
|
|
117
|
+
kusto.append(
|
|
118
|
+
f".create-or-alter table [{table_name}] ingestion json mapping \"{table_name}_json_ce_structured\"")
|
|
119
|
+
kusto.append("```\n[")
|
|
120
|
+
kusto.append(" {\"column\": \"___type\", \"path\": \"$.type\"},")
|
|
121
|
+
kusto.append(
|
|
122
|
+
" {\"column\": \"___source\", \"path\": \"$.source\"},")
|
|
123
|
+
kusto.append(" {\"column\": \"___id\", \"path\": \"$.id\"},")
|
|
124
|
+
kusto.append(" {\"column\": \"___time\", \"path\": \"$.time\"},")
|
|
125
|
+
kusto.append(
|
|
126
|
+
" {\"column\": \"___subject\", \"path\": \"$.subject\"},")
|
|
127
|
+
for field in fields:
|
|
128
|
+
json_name = column_name = field["name"]
|
|
129
|
+
if 'altnames' in field:
|
|
130
|
+
if 'kql' in field['altnames']:
|
|
131
|
+
column_name = field['altnames']['kql']
|
|
132
|
+
if 'json' in field['altnames']:
|
|
133
|
+
json_name = field['altnames']['json']
|
|
134
|
+
kusto.append(
|
|
135
|
+
f" {{\"column\": \"{column_name}\", \"path\": \"$.data.{json_name}\"}},")
|
|
136
|
+
kusto.append("]\n```\n\n")
|
|
137
|
+
|
|
138
|
+
if emit_cloudevents_columns:
|
|
139
|
+
kusto.append(
|
|
140
|
+
f".drop materialized-view {table_name}Latest ifexists;")
|
|
141
|
+
kusto.append("")
|
|
142
|
+
kusto.append(
|
|
143
|
+
f".create materialized-view with (backfill=true) {table_name}Latest on table {table_name} {{")
|
|
144
|
+
kusto.append(
|
|
145
|
+
f" {table_name} | summarize arg_max(___time, *) by ___type, ___source, ___subject")
|
|
146
|
+
kusto.append("}")
|
|
147
|
+
kusto.append("")
|
|
148
|
+
|
|
149
|
+
if emit_cloudevents_dispatch_table:
|
|
150
|
+
event_type = recordschema["namespace"] + "." + \
|
|
151
|
+
recordschema["name"] if "namespace" in recordschema else recordschema["name"]
|
|
152
|
+
|
|
153
|
+
query = f"_cloudevents_dispatch | where (specversion == '1.0' and type == '{event_type}') | " + \
|
|
154
|
+
"project"
|
|
155
|
+
for field in fields:
|
|
156
|
+
column_name = field["name"]
|
|
157
|
+
if "altnames" in field and "kql" in field["altnames"]:
|
|
158
|
+
column_name = field["altnames"]["kql"]
|
|
159
|
+
column_type = self.convert_avro_type_to_kusto_type(
|
|
160
|
+
field["type"])
|
|
161
|
+
query += f"['{column_name}'] = to{column_type}(data.['{column_name}']),"
|
|
162
|
+
query += "___type = type,___source = source,___id = ['id'],___time = ['time'],___subject = subject"
|
|
163
|
+
|
|
164
|
+
# build an update policy for the table that gets triggered by updates to the dispatch table and extracts the event
|
|
165
|
+
kusto.append(f".alter table [{table_name}] policy update")
|
|
166
|
+
kusto.append("```")
|
|
167
|
+
kusto.append("[{")
|
|
168
|
+
kusto.append(" \"IsEnabled\": true,")
|
|
169
|
+
kusto.append(" \"Source\": \"_cloudevents_dispatch\",")
|
|
170
|
+
kusto.append(
|
|
171
|
+
f" \"Query\": \"{query}\",")
|
|
172
|
+
kusto.append(" \"IsTransactional\": false,")
|
|
173
|
+
kusto.append(" \"PropagateIngestionProperties\": true,")
|
|
174
|
+
kusto.append("}]")
|
|
175
|
+
kusto.append("```\n")
|
|
176
|
+
|
|
177
|
+
return kusto
|
|
178
|
+
|
|
179
|
+
def convert_avro_to_kusto_script(self, avro_schema_path, avro_record_type, emit_cloudevents_columns=False, emit_cloudevents_dispatch_table=False) -> str:
|
|
180
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
181
|
+
if emit_cloudevents_dispatch_table:
|
|
182
|
+
emit_cloudevents_columns = True
|
|
183
|
+
schema_file = avro_schema_path
|
|
184
|
+
if not schema_file:
|
|
185
|
+
print("Please specify the avro schema file")
|
|
186
|
+
sys.exit(1)
|
|
187
|
+
with open(schema_file, "r", encoding="utf-8") as f:
|
|
188
|
+
schema_json = f.read()
|
|
189
|
+
|
|
190
|
+
# Parse the schema as a JSON object
|
|
191
|
+
schema = json.loads(schema_json)
|
|
192
|
+
|
|
193
|
+
if isinstance(schema, list):
|
|
194
|
+
if avro_record_type:
|
|
195
|
+
schema = next(
|
|
196
|
+
(x for x in schema if x["name"] == avro_record_type), None)
|
|
197
|
+
if schema is None:
|
|
198
|
+
print(
|
|
199
|
+
f"No record type {avro_record_type} found in the Avro schema")
|
|
200
|
+
sys.exit(1)
|
|
201
|
+
elif not isinstance(schema, dict) or "type" not in schema or schema["type"] != "record":
|
|
202
|
+
print(
|
|
203
|
+
"Expected a single Avro schema as a JSON object, or a list of schema records")
|
|
204
|
+
sys.exit(1)
|
|
205
|
+
|
|
206
|
+
if not isinstance(schema, list):
|
|
207
|
+
schema = [schema]
|
|
208
|
+
|
|
209
|
+
kusto_script = []
|
|
210
|
+
|
|
211
|
+
if emit_cloudevents_dispatch_table:
|
|
212
|
+
kusto_script.append(
|
|
213
|
+
".create-merge table [_cloudevents_dispatch] (")
|
|
214
|
+
kusto_script.append(" [specversion]: string,")
|
|
215
|
+
kusto_script.append(" [type]: string,")
|
|
216
|
+
kusto_script.append(" [source]: string,")
|
|
217
|
+
kusto_script.append(" [id]: string,")
|
|
218
|
+
kusto_script.append(" [time]: datetime,")
|
|
219
|
+
kusto_script.append(" [subject]: string,")
|
|
220
|
+
kusto_script.append(" [datacontenttype]: string,")
|
|
221
|
+
kusto_script.append(" [dataschema]: string,")
|
|
222
|
+
kusto_script.append(" [data]: dynamic")
|
|
223
|
+
kusto_script.append(");\n\n")
|
|
224
|
+
kusto_script.append(
|
|
225
|
+
".create-or-alter table [_cloudevents_dispatch] ingestion json mapping \"_cloudevents_dispatch_json\"")
|
|
226
|
+
kusto_script.append("```\n[")
|
|
227
|
+
kusto_script.append(
|
|
228
|
+
" {\"column\": \"specversion\", \"path\": \"$.specversion\"},")
|
|
229
|
+
kusto_script.append(
|
|
230
|
+
" {\"column\": \"type\", \"path\": \"$.type\"},")
|
|
231
|
+
kusto_script.append(
|
|
232
|
+
" {\"column\": \"source\", \"path\": \"$.source\"},")
|
|
233
|
+
kusto_script.append(" {\"column\": \"id\", \"path\": \"$.id\"},")
|
|
234
|
+
kusto_script.append(
|
|
235
|
+
" {\"column\": \"time\", \"path\": \"$.time\"},")
|
|
236
|
+
kusto_script.append(
|
|
237
|
+
" {\"column\": \"subject\", \"path\": \"$.subject\"},")
|
|
238
|
+
kusto_script.append(
|
|
239
|
+
" {\"column\": \"datacontenttype\", \"path\": \"$.datacontenttype\"},")
|
|
240
|
+
kusto_script.append(
|
|
241
|
+
" {\"column\": \"dataschema\", \"path\": \"$.dataschema\"},")
|
|
242
|
+
kusto_script.append(
|
|
243
|
+
" {\"column\": \"data\", \"path\": \"$.data\"}")
|
|
244
|
+
kusto_script.append("]\n```\n\n")
|
|
245
|
+
|
|
246
|
+
type_dict = build_flat_type_dict(schema)
|
|
247
|
+
for record in schema:
|
|
248
|
+
if not isinstance(record, dict) or "type" not in record or record["type"] != "record":
|
|
249
|
+
continue
|
|
250
|
+
kusto_script.extend(self.convert_record_to_kusto(type_dict,
|
|
251
|
+
record, emit_cloudevents_columns, emit_cloudevents_dispatch_table))
|
|
252
|
+
return "\n".join(kusto_script)
|
|
253
|
+
|
|
254
|
+
def convert_avro_to_kusto_file(self, avro_schema_path, avro_record_type, kusto_file_path, emit_cloudevents_columns=False, emit_cloudevents_dispatch_table=False):
|
|
255
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
256
|
+
script = self.convert_avro_to_kusto_script(
|
|
257
|
+
avro_schema_path, avro_record_type, emit_cloudevents_columns, emit_cloudevents_dispatch_table)
|
|
258
|
+
with open(kusto_file_path, "w", encoding="utf-8") as kusto_file:
|
|
259
|
+
kusto_file.write(script)
|
|
260
|
+
|
|
261
|
+
def convert_avro_type_to_kusto_type(self, avro_type: str | dict | list):
|
|
262
|
+
"""Converts an Avro type to a Kusto type."""
|
|
263
|
+
if isinstance(avro_type, list):
|
|
264
|
+
# If the type is an array, then it is a union type. Look whether it's a pair of a scalar type and null:
|
|
265
|
+
itemCount = len(avro_type)
|
|
266
|
+
if itemCount > 2:
|
|
267
|
+
return "dynamic"
|
|
268
|
+
if itemCount == 1:
|
|
269
|
+
return self.convert_avro_type_to_kusto_type(avro_type[0])
|
|
270
|
+
else:
|
|
271
|
+
first = avro_type[0]
|
|
272
|
+
second = avro_type[1]
|
|
273
|
+
if isinstance(first, str) and first == "null":
|
|
274
|
+
return self.convert_avro_type_to_kusto_type(second)
|
|
275
|
+
elif isinstance(second, str) and second == "null":
|
|
276
|
+
return self.convert_avro_type_to_kusto_type(first)
|
|
277
|
+
else:
|
|
278
|
+
return "dynamic"
|
|
279
|
+
elif isinstance(avro_type, dict):
|
|
280
|
+
type_value = avro_type.get("type")
|
|
281
|
+
if type_value == "enum":
|
|
282
|
+
return "string"
|
|
283
|
+
elif type_value == "fixed":
|
|
284
|
+
return "dynamic"
|
|
285
|
+
elif type_value == "string":
|
|
286
|
+
logical_type = avro_type.get("logicalType")
|
|
287
|
+
if logical_type == "uuid":
|
|
288
|
+
return "guid"
|
|
289
|
+
return "string"
|
|
290
|
+
elif type_value == "bytes":
|
|
291
|
+
logical_type = avro_type.get("logicalType")
|
|
292
|
+
if logical_type == "decimal":
|
|
293
|
+
return "decimal"
|
|
294
|
+
return "dynamic"
|
|
295
|
+
elif type_value == "long":
|
|
296
|
+
logical_type = avro_type.get("logicalType")
|
|
297
|
+
if logical_type in ["timestamp-millis", "timestamp-micros"]:
|
|
298
|
+
return "datetime"
|
|
299
|
+
if logical_type in ["time-millis", "time-micros"]:
|
|
300
|
+
return "timespan"
|
|
301
|
+
return "long"
|
|
302
|
+
elif type_value == "int":
|
|
303
|
+
logical_type = avro_type.get("logicalType")
|
|
304
|
+
if logical_type == "date":
|
|
305
|
+
return "datetime"
|
|
306
|
+
return "int"
|
|
307
|
+
else:
|
|
308
|
+
return self.map_scalar_type(type_value)
|
|
309
|
+
elif isinstance(avro_type, str):
|
|
310
|
+
return self.map_scalar_type(avro_type)
|
|
311
|
+
|
|
312
|
+
def map_scalar_type(self, type_value: Any):
|
|
313
|
+
"""Maps an Avro scalar type to a Kusto scalar type."""
|
|
314
|
+
if type_value == "null":
|
|
315
|
+
return "dynamic"
|
|
316
|
+
elif type_value == "int":
|
|
317
|
+
return "int"
|
|
318
|
+
elif type_value == "long":
|
|
319
|
+
return "long"
|
|
320
|
+
elif type_value == "float":
|
|
321
|
+
return "real"
|
|
322
|
+
elif type_value == "double":
|
|
323
|
+
return "real"
|
|
324
|
+
elif type_value == "boolean":
|
|
325
|
+
return "bool"
|
|
326
|
+
elif type_value == "bytes":
|
|
327
|
+
return "dynamic"
|
|
328
|
+
elif type_value == "string":
|
|
329
|
+
return "string"
|
|
330
|
+
else:
|
|
331
|
+
return "dynamic"
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def convert_avro_to_kusto_file(avro_schema_path, avro_record_type, kusto_file_path, emit_cloudevents_columns=False, emit_cloudevents_dispatch_table=False):
|
|
335
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
336
|
+
avro_to_kusto = AvroToKusto()
|
|
337
|
+
avro_to_kusto.convert_avro_to_kusto_file(
|
|
338
|
+
avro_schema_path, avro_record_type, kusto_file_path, emit_cloudevents_columns, emit_cloudevents_dispatch_table)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def convert_avro_to_kusto_db(avro_schema_path, avro_record_type, kusto_uri, kusto_database, emit_cloudevents_columns=False, emit_cloudevents_dispatch_table=False, token_provider=None):
|
|
342
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
343
|
+
avro_to_kusto = AvroToKusto()
|
|
344
|
+
script = avro_to_kusto.convert_avro_to_kusto_script(
|
|
345
|
+
avro_schema_path, avro_record_type, emit_cloudevents_columns, emit_cloudevents_dispatch_table)
|
|
346
|
+
kcsb = KustoConnectionStringBuilder.with_az_cli_authentication(
|
|
347
|
+
kusto_uri) if not token_provider else KustoConnectionStringBuilder.with_token_provider(kusto_uri, token_provider)
|
|
348
|
+
client = KustoClient(kcsb)
|
|
349
|
+
for statement in script.split("\n\n"):
|
|
350
|
+
if statement.strip():
|
|
351
|
+
try:
|
|
352
|
+
client.execute_mgmt(kusto_database, statement)
|
|
353
|
+
except Exception as e:
|
|
354
|
+
print(e)
|
|
355
|
+
sys.exit(1)
|
|
356
|
+
|
|
357
|
+
def convert_avro_to_kusto(avro_schema_path, avro_record_type, kusto_file_path, kusto_uri, kusto_database, emit_cloudevents_columns=False, emit_cloudevents_dispatch_table=False, token_provider=None):
|
|
358
|
+
"""Converts an Avro schema to a Kusto table schema."""
|
|
359
|
+
if not kusto_uri and not kusto_database:
|
|
360
|
+
convert_avro_to_kusto_file(
|
|
361
|
+
avro_schema_path, avro_record_type, kusto_file_path, emit_cloudevents_columns, emit_cloudevents_dispatch_table)
|
|
362
|
+
else:
|
|
363
|
+
convert_avro_to_kusto_db(
|
|
364
|
+
avro_schema_path, avro_record_type, kusto_uri, kusto_database, emit_cloudevents_columns, emit_cloudevents_dispatch_table, token_provider)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# {{ schema_name }} Schemas
|
|
2
|
+
|
|
3
|
+
{%- if records %}
|
|
4
|
+
## Records
|
|
5
|
+
{%- for namespace, records in records.items() %}
|
|
6
|
+
### Namespace: {{ namespace }}
|
|
7
|
+
{%- for record in records %}
|
|
8
|
+
#### {{ record.name }}
|
|
9
|
+
{%- if record.doc %}
|
|
10
|
+
{{ record.doc }}
|
|
11
|
+
{%- endif %}
|
|
12
|
+
- **Type:** record
|
|
13
|
+
##### Fields
|
|
14
|
+
{%- for field in record.fields %}
|
|
15
|
+
{{ generate_field_markdown(field, 5) }}
|
|
16
|
+
{%- endfor %}
|
|
17
|
+
{%- endfor %}
|
|
18
|
+
{%- endfor %}
|
|
19
|
+
{%- endif %}
|
|
20
|
+
|
|
21
|
+
{%- if enums %}
|
|
22
|
+
## Enums
|
|
23
|
+
{%- for namespace, enums in enums.items() %}
|
|
24
|
+
### Namespace: {{ namespace }}
|
|
25
|
+
{%- for enum in enums %}
|
|
26
|
+
#### {{ enum.name }}
|
|
27
|
+
{%- if enum.doc %}
|
|
28
|
+
{{ enum.doc }}
|
|
29
|
+
{%- endif %}
|
|
30
|
+
- **Type:** enum
|
|
31
|
+
- **Symbols:** {{ enum.symbols | join(', ') }}
|
|
32
|
+
{%- endfor %}
|
|
33
|
+
{%- endfor %}
|
|
34
|
+
{%- endif %}
|
|
35
|
+
|
|
36
|
+
{%- if fixeds %}
|
|
37
|
+
## Fixed Types
|
|
38
|
+
{%- for namespace, fixeds in fixeds.items() %}
|
|
39
|
+
### Namespace: {{ namespace }}
|
|
40
|
+
{%- for fixed in fixeds %}
|
|
41
|
+
#### {{ fixed.name }}
|
|
42
|
+
{%- if fixed.doc %}
|
|
43
|
+
{{ fixed.doc }}
|
|
44
|
+
{%- endif %}
|
|
45
|
+
- **Type:** fixed
|
|
46
|
+
- **Size:** {{ fixed.size }}
|
|
47
|
+
{%- endfor %}
|
|
48
|
+
{%- endfor %}
|
|
49
|
+
{%- endif %}
|
avrotize/avrotomd.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
"""
|
|
3
|
+
Module to convert Avro schema to a comprehensive README.md.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from jinja2 import Environment, FileSystemLoader
|
|
9
|
+
|
|
10
|
+
from avrotize.common import render_template
|
|
11
|
+
|
|
12
|
+
class AvroToMarkdownConverter:
|
|
13
|
+
"""
|
|
14
|
+
Class to convert Avro schema to a comprehensive README.md.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(self, avro_schema_path, markdown_path):
|
|
18
|
+
"""
|
|
19
|
+
Initialize the converter with file paths.
|
|
20
|
+
|
|
21
|
+
:param avro_schema_path: Path to the Avro schema file.
|
|
22
|
+
:param markdown_path: Path to save the README.md file.
|
|
23
|
+
"""
|
|
24
|
+
self.avro_schema_path = avro_schema_path
|
|
25
|
+
self.markdown_path = markdown_path
|
|
26
|
+
self.records = {}
|
|
27
|
+
self.enums = {}
|
|
28
|
+
self.fixeds = {}
|
|
29
|
+
|
|
30
|
+
def convert(self):
|
|
31
|
+
"""
|
|
32
|
+
Convert Avro schema to Markdown and save to file.
|
|
33
|
+
"""
|
|
34
|
+
with open(self.avro_schema_path, 'r', encoding='utf-8') as file:
|
|
35
|
+
avro_schemas = json.load(file)
|
|
36
|
+
|
|
37
|
+
schema_name = os.path.splitext(os.path.basename(self.avro_schema_path))[0]
|
|
38
|
+
if isinstance(avro_schemas, dict):
|
|
39
|
+
self.extract_named_types(avro_schemas)
|
|
40
|
+
elif isinstance(avro_schemas, list):
|
|
41
|
+
for schema in avro_schemas:
|
|
42
|
+
self.extract_named_types(schema)
|
|
43
|
+
|
|
44
|
+
self.generate_markdown(schema_name)
|
|
45
|
+
|
|
46
|
+
def extract_named_types(self, schema, parent_namespace: str = ''):
|
|
47
|
+
"""
|
|
48
|
+
Extract all named types (records, enums, fixed) from the schema.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
if isinstance(schema, dict):
|
|
52
|
+
ns = schema.get('namespace', parent_namespace)
|
|
53
|
+
if schema['type'] == 'record':
|
|
54
|
+
self.records.setdefault(ns, []).append(schema)
|
|
55
|
+
elif schema['type'] == 'enum':
|
|
56
|
+
self.enums.setdefault(ns, []).append(schema)
|
|
57
|
+
elif schema['type'] == 'fixed':
|
|
58
|
+
self.fixeds.setdefault(ns, []).append(schema)
|
|
59
|
+
if 'fields' in schema:
|
|
60
|
+
for field in schema['fields']:
|
|
61
|
+
self.extract_named_types(field['type'], ns)
|
|
62
|
+
if 'items' in schema:
|
|
63
|
+
self.extract_named_types(schema['items'], ns)
|
|
64
|
+
if 'values' in schema:
|
|
65
|
+
self.extract_named_types(schema['values'], ns)
|
|
66
|
+
elif isinstance(schema, list):
|
|
67
|
+
for sub_schema in schema:
|
|
68
|
+
self.extract_named_types(sub_schema, '')
|
|
69
|
+
|
|
70
|
+
def generate_markdown(self, schema_name: str):
|
|
71
|
+
"""
|
|
72
|
+
Generate markdown content from the extracted types using Jinja2 template.
|
|
73
|
+
|
|
74
|
+
:param schema_name: The name of the schema file.
|
|
75
|
+
:return: Markdown content as a string.
|
|
76
|
+
"""
|
|
77
|
+
render_template("avrotomd/README.md.jinja", self.markdown_path,
|
|
78
|
+
schema_name = schema_name,
|
|
79
|
+
records = self.records,
|
|
80
|
+
enums = self.enums,
|
|
81
|
+
fixeds = self.fixeds,
|
|
82
|
+
generate_field_markdown = self.generate_field_markdown
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
def generate_field_markdown(self, field, level):
|
|
86
|
+
"""
|
|
87
|
+
Generate markdown content for a single field.
|
|
88
|
+
|
|
89
|
+
:param field: Avro field as a dictionary.
|
|
90
|
+
:param level: The current level of nesting.
|
|
91
|
+
:return: Markdown content as a string.
|
|
92
|
+
"""
|
|
93
|
+
field_md = []
|
|
94
|
+
heading = "#" * level
|
|
95
|
+
field_md.append(f"{heading} {field['name']}\n")
|
|
96
|
+
field_md.append(f"- **Type:** {self.get_avro_type(field['type'])}")
|
|
97
|
+
if 'doc' in field:
|
|
98
|
+
field_md.append(f"- **Description:** {field['doc']}")
|
|
99
|
+
if 'default' in field:
|
|
100
|
+
field_md.append(f"- **Default:** {field['default']}")
|
|
101
|
+
if isinstance(field['type'], dict) and field['type'].get('logicalType'):
|
|
102
|
+
field_md.append(f"- **Logical Type:** {field['type']['logicalType']}")
|
|
103
|
+
if 'symbols' in field.get('type', {}):
|
|
104
|
+
field_md.append(f"- **Symbols:** {', '.join(field['type']['symbols'])}")
|
|
105
|
+
field_md.append("\n")
|
|
106
|
+
return "\n".join(field_md)
|
|
107
|
+
|
|
108
|
+
def get_avro_type(self, avro_type):
|
|
109
|
+
"""
|
|
110
|
+
Get Avro type as a string.
|
|
111
|
+
|
|
112
|
+
:param avro_type: Avro type as a string or dictionary.
|
|
113
|
+
:return: Avro type as a string.
|
|
114
|
+
"""
|
|
115
|
+
if isinstance(avro_type, list):
|
|
116
|
+
return " | ".join([self.get_avro_type(t) for t in avro_type])
|
|
117
|
+
if isinstance(avro_type, dict):
|
|
118
|
+
type_name = avro_type.get('type', 'unknown')
|
|
119
|
+
namespace = avro_type.get('namespace', '')
|
|
120
|
+
if type_name in [r['name'] for r in self.records.get(namespace, [])]:
|
|
121
|
+
return f"[{type_name}](#record-{namespace.lower()}-{type_name.lower()})"
|
|
122
|
+
if type_name in [e['name'] for e in self.enums.get(namespace, [])]:
|
|
123
|
+
return f"[{type_name}](#enum-{namespace.lower()}-{type_name.lower()})"
|
|
124
|
+
if type_name in [f['name'] for f in self.fixeds.get(namespace, [])]:
|
|
125
|
+
return f"[{type_name}](#fixed-{namespace.lower()}-{type_name.lower()})"
|
|
126
|
+
return type_name
|
|
127
|
+
return avro_type
|
|
128
|
+
|
|
129
|
+
def convert_avro_to_markdown(avro_schema_path, markdown_path):
|
|
130
|
+
"""
|
|
131
|
+
Convert an Avro schema file to a README.md file.
|
|
132
|
+
|
|
133
|
+
:param avro_schema_path: Path to the Avro schema file.
|
|
134
|
+
:param markdown_path: Path to save the README.md file.
|
|
135
|
+
"""
|
|
136
|
+
converter = AvroToMarkdownConverter(avro_schema_path, markdown_path)
|
|
137
|
+
converter.convert()
|