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.
Files changed (171) hide show
  1. avrotize/__init__.py +66 -0
  2. avrotize/__main__.py +6 -0
  3. avrotize/_version.py +34 -0
  4. avrotize/asn1toavro.py +160 -0
  5. avrotize/avrotize.py +152 -0
  6. avrotize/avrotocpp/CMakeLists.txt.jinja +77 -0
  7. avrotize/avrotocpp/build.bat.jinja +7 -0
  8. avrotize/avrotocpp/build.sh.jinja +7 -0
  9. avrotize/avrotocpp/dataclass_body.jinja +108 -0
  10. avrotize/avrotocpp/vcpkg.json.jinja +21 -0
  11. avrotize/avrotocpp.py +483 -0
  12. avrotize/avrotocsharp/README.md.jinja +166 -0
  13. avrotize/avrotocsharp/class_test.cs.jinja +266 -0
  14. avrotize/avrotocsharp/dataclass_core.jinja +293 -0
  15. avrotize/avrotocsharp/enum_test.cs.jinja +20 -0
  16. avrotize/avrotocsharp/project.csproj.jinja +30 -0
  17. avrotize/avrotocsharp/project.sln.jinja +34 -0
  18. avrotize/avrotocsharp/run_coverage.ps1.jinja +98 -0
  19. avrotize/avrotocsharp/run_coverage.sh.jinja +149 -0
  20. avrotize/avrotocsharp/testproject.csproj.jinja +19 -0
  21. avrotize/avrotocsharp.py +1180 -0
  22. avrotize/avrotocsv.py +121 -0
  23. avrotize/avrotodatapackage.py +173 -0
  24. avrotize/avrotodb.py +1383 -0
  25. avrotize/avrotogo/go_enum.jinja +12 -0
  26. avrotize/avrotogo/go_helpers.jinja +31 -0
  27. avrotize/avrotogo/go_struct.jinja +151 -0
  28. avrotize/avrotogo/go_test.jinja +47 -0
  29. avrotize/avrotogo/go_union.jinja +38 -0
  30. avrotize/avrotogo.py +476 -0
  31. avrotize/avrotographql.py +197 -0
  32. avrotize/avrotoiceberg.py +210 -0
  33. avrotize/avrotojava/class_test.java.jinja +212 -0
  34. avrotize/avrotojava/enum_test.java.jinja +21 -0
  35. avrotize/avrotojava/testproject.pom.jinja +54 -0
  36. avrotize/avrotojava.py +2156 -0
  37. avrotize/avrotojs.py +250 -0
  38. avrotize/avrotojsons.py +481 -0
  39. avrotize/avrotojstruct.py +345 -0
  40. avrotize/avrotokusto.py +364 -0
  41. avrotize/avrotomd/README.md.jinja +49 -0
  42. avrotize/avrotomd.py +137 -0
  43. avrotize/avrotools.py +168 -0
  44. avrotize/avrotoparquet.py +208 -0
  45. avrotize/avrotoproto.py +359 -0
  46. avrotize/avrotopython/dataclass_core.jinja +241 -0
  47. avrotize/avrotopython/enum_core.jinja +87 -0
  48. avrotize/avrotopython/pyproject_toml.jinja +18 -0
  49. avrotize/avrotopython/test_class.jinja +97 -0
  50. avrotize/avrotopython/test_enum.jinja +23 -0
  51. avrotize/avrotopython.py +626 -0
  52. avrotize/avrotorust/dataclass_enum.rs.jinja +74 -0
  53. avrotize/avrotorust/dataclass_struct.rs.jinja +204 -0
  54. avrotize/avrotorust/dataclass_union.rs.jinja +105 -0
  55. avrotize/avrotorust.py +435 -0
  56. avrotize/avrotots/class_core.ts.jinja +140 -0
  57. avrotize/avrotots/class_test.ts.jinja +77 -0
  58. avrotize/avrotots/enum_core.ts.jinja +46 -0
  59. avrotize/avrotots/gitignore.jinja +34 -0
  60. avrotize/avrotots/index.ts.jinja +0 -0
  61. avrotize/avrotots/package.json.jinja +23 -0
  62. avrotize/avrotots/tsconfig.json.jinja +21 -0
  63. avrotize/avrotots.py +687 -0
  64. avrotize/avrotoxsd.py +344 -0
  65. avrotize/cddltostructure.py +1841 -0
  66. avrotize/commands.json +3496 -0
  67. avrotize/common.py +834 -0
  68. avrotize/constants.py +87 -0
  69. avrotize/csvtoavro.py +132 -0
  70. avrotize/datapackagetoavro.py +76 -0
  71. avrotize/dependencies/cpp/vcpkg/vcpkg.json +19 -0
  72. avrotize/dependencies/cs/net90/dependencies.csproj +29 -0
  73. avrotize/dependencies/go/go121/go.mod +6 -0
  74. avrotize/dependencies/java/jdk21/pom.xml +91 -0
  75. avrotize/dependencies/python/py312/requirements.txt +13 -0
  76. avrotize/dependencies/rust/stable/Cargo.toml +17 -0
  77. avrotize/dependencies/typescript/node22/package.json +16 -0
  78. avrotize/dependency_resolver.py +348 -0
  79. avrotize/dependency_version.py +432 -0
  80. avrotize/generic/generic.avsc +57 -0
  81. avrotize/jsonstoavro.py +2167 -0
  82. avrotize/jsonstostructure.py +2864 -0
  83. avrotize/jstructtoavro.py +878 -0
  84. avrotize/kstructtoavro.py +93 -0
  85. avrotize/kustotoavro.py +455 -0
  86. avrotize/openapitostructure.py +717 -0
  87. avrotize/parquettoavro.py +157 -0
  88. avrotize/proto2parser.py +498 -0
  89. avrotize/proto3parser.py +403 -0
  90. avrotize/prototoavro.py +382 -0
  91. avrotize/prototypes/any.avsc +19 -0
  92. avrotize/prototypes/api.avsc +106 -0
  93. avrotize/prototypes/duration.avsc +20 -0
  94. avrotize/prototypes/field_mask.avsc +18 -0
  95. avrotize/prototypes/struct.avsc +60 -0
  96. avrotize/prototypes/timestamp.avsc +20 -0
  97. avrotize/prototypes/type.avsc +253 -0
  98. avrotize/prototypes/wrappers.avsc +117 -0
  99. avrotize/structuretocddl.py +597 -0
  100. avrotize/structuretocpp/CMakeLists.txt.jinja +76 -0
  101. avrotize/structuretocpp/build.bat.jinja +3 -0
  102. avrotize/structuretocpp/build.sh.jinja +3 -0
  103. avrotize/structuretocpp/dataclass_body.jinja +50 -0
  104. avrotize/structuretocpp/vcpkg.json.jinja +11 -0
  105. avrotize/structuretocpp.py +697 -0
  106. avrotize/structuretocsharp/class_test.cs.jinja +180 -0
  107. avrotize/structuretocsharp/dataclass_core.jinja +156 -0
  108. avrotize/structuretocsharp/enum_test.cs.jinja +36 -0
  109. avrotize/structuretocsharp/json_structure_converters.cs.jinja +399 -0
  110. avrotize/structuretocsharp/program.cs.jinja +49 -0
  111. avrotize/structuretocsharp/project.csproj.jinja +17 -0
  112. avrotize/structuretocsharp/project.sln.jinja +34 -0
  113. avrotize/structuretocsharp/testproject.csproj.jinja +18 -0
  114. avrotize/structuretocsharp/tuple_converter.cs.jinja +121 -0
  115. avrotize/structuretocsharp.py +2295 -0
  116. avrotize/structuretocsv.py +365 -0
  117. avrotize/structuretodatapackage.py +659 -0
  118. avrotize/structuretodb.py +1125 -0
  119. avrotize/structuretogo/go_enum.jinja +12 -0
  120. avrotize/structuretogo/go_helpers.jinja +26 -0
  121. avrotize/structuretogo/go_interface.jinja +18 -0
  122. avrotize/structuretogo/go_struct.jinja +187 -0
  123. avrotize/structuretogo/go_test.jinja +70 -0
  124. avrotize/structuretogo.py +729 -0
  125. avrotize/structuretographql.py +502 -0
  126. avrotize/structuretoiceberg.py +355 -0
  127. avrotize/structuretojava/choice_core.jinja +34 -0
  128. avrotize/structuretojava/class_core.jinja +23 -0
  129. avrotize/structuretojava/enum_core.jinja +18 -0
  130. avrotize/structuretojava/equals_hashcode.jinja +30 -0
  131. avrotize/structuretojava/pom.xml.jinja +26 -0
  132. avrotize/structuretojava/tuple_core.jinja +49 -0
  133. avrotize/structuretojava.py +938 -0
  134. avrotize/structuretojs/class_core.js.jinja +33 -0
  135. avrotize/structuretojs/enum_core.js.jinja +10 -0
  136. avrotize/structuretojs/package.json.jinja +12 -0
  137. avrotize/structuretojs/test_class.js.jinja +84 -0
  138. avrotize/structuretojs/test_enum.js.jinja +58 -0
  139. avrotize/structuretojs/test_runner.js.jinja +45 -0
  140. avrotize/structuretojs.py +657 -0
  141. avrotize/structuretojsons.py +498 -0
  142. avrotize/structuretokusto.py +639 -0
  143. avrotize/structuretomd/README.md.jinja +204 -0
  144. avrotize/structuretomd.py +322 -0
  145. avrotize/structuretoproto.py +764 -0
  146. avrotize/structuretopython/dataclass_core.jinja +363 -0
  147. avrotize/structuretopython/enum_core.jinja +45 -0
  148. avrotize/structuretopython/map_alias.jinja +21 -0
  149. avrotize/structuretopython/pyproject_toml.jinja +23 -0
  150. avrotize/structuretopython/test_class.jinja +103 -0
  151. avrotize/structuretopython/test_enum.jinja +34 -0
  152. avrotize/structuretopython.py +799 -0
  153. avrotize/structuretorust/dataclass_enum.rs.jinja +63 -0
  154. avrotize/structuretorust/dataclass_struct.rs.jinja +121 -0
  155. avrotize/structuretorust/dataclass_union.rs.jinja +81 -0
  156. avrotize/structuretorust.py +714 -0
  157. avrotize/structuretots/class_core.ts.jinja +78 -0
  158. avrotize/structuretots/enum_core.ts.jinja +6 -0
  159. avrotize/structuretots/gitignore.jinja +8 -0
  160. avrotize/structuretots/index.ts.jinja +1 -0
  161. avrotize/structuretots/package.json.jinja +39 -0
  162. avrotize/structuretots/test_class.ts.jinja +35 -0
  163. avrotize/structuretots/tsconfig.json.jinja +21 -0
  164. avrotize/structuretots.py +740 -0
  165. avrotize/structuretoxsd.py +679 -0
  166. avrotize/xsdtoavro.py +413 -0
  167. avrotize-2.21.1.dist-info/METADATA +1319 -0
  168. avrotize-2.21.1.dist-info/RECORD +171 -0
  169. avrotize-2.21.1.dist-info/WHEEL +4 -0
  170. avrotize-2.21.1.dist-info/entry_points.txt +3 -0
  171. avrotize-2.21.1.dist-info/licenses/LICENSE +201 -0
@@ -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()