structurize 2.19.0__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 (70) hide show
  1. avrotize/__init__.py +64 -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.py +483 -0
  7. avrotize/avrotocsharp.py +1075 -0
  8. avrotize/avrotocsv.py +121 -0
  9. avrotize/avrotodatapackage.py +173 -0
  10. avrotize/avrotodb.py +1383 -0
  11. avrotize/avrotogo.py +476 -0
  12. avrotize/avrotographql.py +197 -0
  13. avrotize/avrotoiceberg.py +210 -0
  14. avrotize/avrotojava.py +2156 -0
  15. avrotize/avrotojs.py +250 -0
  16. avrotize/avrotojsons.py +481 -0
  17. avrotize/avrotojstruct.py +345 -0
  18. avrotize/avrotokusto.py +364 -0
  19. avrotize/avrotomd.py +137 -0
  20. avrotize/avrotools.py +168 -0
  21. avrotize/avrotoparquet.py +208 -0
  22. avrotize/avrotoproto.py +359 -0
  23. avrotize/avrotopython.py +624 -0
  24. avrotize/avrotorust.py +435 -0
  25. avrotize/avrotots.py +598 -0
  26. avrotize/avrotoxsd.py +344 -0
  27. avrotize/cddltostructure.py +1841 -0
  28. avrotize/commands.json +3337 -0
  29. avrotize/common.py +834 -0
  30. avrotize/constants.py +72 -0
  31. avrotize/csvtoavro.py +132 -0
  32. avrotize/datapackagetoavro.py +76 -0
  33. avrotize/dependencies/cpp/vcpkg/vcpkg.json +19 -0
  34. avrotize/dependencies/typescript/node22/package.json +16 -0
  35. avrotize/dependency_resolver.py +348 -0
  36. avrotize/dependency_version.py +432 -0
  37. avrotize/jsonstoavro.py +2167 -0
  38. avrotize/jsonstostructure.py +2642 -0
  39. avrotize/jstructtoavro.py +878 -0
  40. avrotize/kstructtoavro.py +93 -0
  41. avrotize/kustotoavro.py +455 -0
  42. avrotize/parquettoavro.py +157 -0
  43. avrotize/proto2parser.py +498 -0
  44. avrotize/proto3parser.py +403 -0
  45. avrotize/prototoavro.py +382 -0
  46. avrotize/structuretocddl.py +597 -0
  47. avrotize/structuretocpp.py +697 -0
  48. avrotize/structuretocsharp.py +2295 -0
  49. avrotize/structuretocsv.py +365 -0
  50. avrotize/structuretodatapackage.py +659 -0
  51. avrotize/structuretodb.py +1125 -0
  52. avrotize/structuretogo.py +720 -0
  53. avrotize/structuretographql.py +502 -0
  54. avrotize/structuretoiceberg.py +355 -0
  55. avrotize/structuretojava.py +853 -0
  56. avrotize/structuretojsons.py +498 -0
  57. avrotize/structuretokusto.py +639 -0
  58. avrotize/structuretomd.py +322 -0
  59. avrotize/structuretoproto.py +764 -0
  60. avrotize/structuretopython.py +772 -0
  61. avrotize/structuretorust.py +714 -0
  62. avrotize/structuretots.py +653 -0
  63. avrotize/structuretoxsd.py +679 -0
  64. avrotize/xsdtoavro.py +413 -0
  65. structurize-2.19.0.dist-info/METADATA +107 -0
  66. structurize-2.19.0.dist-info/RECORD +70 -0
  67. structurize-2.19.0.dist-info/WHEEL +5 -0
  68. structurize-2.19.0.dist-info/entry_points.txt +2 -0
  69. structurize-2.19.0.dist-info/licenses/LICENSE +201 -0
  70. structurize-2.19.0.dist-info/top_level.txt +1 -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)
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()
avrotize/avrotools.py ADDED
@@ -0,0 +1,168 @@
1
+ """ Avro Tools Module """
2
+
3
+ import json
4
+ import hashlib
5
+ import base64
6
+ from typing import Dict, List, cast
7
+
8
+ JsonNode = Dict[str, 'JsonNode'] | List['JsonNode'] | str | int | bool | None
9
+
10
+ def transform_to_pcf(schema_json: str) -> str:
11
+ """
12
+ Transforms an Avro schema into its Parsing Canonical Form (PCF).
13
+
14
+ :param schema_json: The Avro schema as a JSON string.
15
+ :return: The Parsing Canonical Form (PCF) as a JSON string.
16
+ """
17
+ schema = json.loads(schema_json)
18
+ canonical_schema = canonicalize_schema(schema)
19
+ return json.dumps(canonical_schema, separators=(',', ':'))
20
+
21
+ def avsc_to_pcf(schema_file: str) -> None:
22
+ """ Convert an Avro schema file to its Parsing Canonical Form (PCF)."""
23
+ with open(schema_file, 'r', encoding='utf-8') as file:
24
+ schema = json.load(file)
25
+ print(transform_to_pcf(json.dumps(schema)))
26
+
27
+ def canonicalize_schema(schema: JsonNode, namespace:str="") -> JsonNode:
28
+ """
29
+ Recursively processes the schema to convert it to the Parsing Canonical Form (PCF).
30
+
31
+ :param schema: The Avro schema as a dictionary.
32
+ :param namespace: The current namespace for resolving names.
33
+ :return: The canonicalized schema as a dictionary.
34
+ """
35
+ if isinstance(schema, str):
36
+ return schema
37
+ elif isinstance(schema, dict):
38
+ if 'type' in schema and isinstance(schema['type'], str):
39
+ if schema['type'] in PRIMITIVE_TYPES:
40
+ return schema['type']
41
+ if '.' not in schema['type'] and namespace:
42
+ schema['type'] = namespace + '.' + schema['type']
43
+
44
+ if 'name' in schema and '.' not in cast(str,schema['name']) and namespace:
45
+ schema['name'] = namespace + '.' + cast(str,schema['name'])
46
+
47
+ canonical = {}
48
+ for field in FIELD_ORDER:
49
+ if field in schema:
50
+ value = schema[field]
51
+ if field == 'fields' and isinstance(value, list):
52
+ value = [canonicalize_schema(f, cast(str,schema.get('namespace', namespace))) for f in value]
53
+ elif field == 'symbols' or field == 'items' or field == 'values':
54
+ value = canonicalize_schema(value, namespace)
55
+ elif isinstance(value, dict):
56
+ value = canonicalize_schema(value, namespace)
57
+ elif isinstance(value, list):
58
+ value = [canonicalize_schema(v, namespace) for v in value]
59
+ elif isinstance(value, str):
60
+ value = normalize_string(value)
61
+ elif isinstance(value, int):
62
+ value = normalize_integer(value)
63
+ canonical[field] = value
64
+ return canonical
65
+ elif isinstance(schema, list):
66
+ return [canonicalize_schema(s, namespace) for s in schema]
67
+ raise ValueError("Invalid schema: " + str(schema))
68
+
69
+ def normalize_string(value):
70
+ """
71
+ Normalizes JSON string literals by replacing escaped characters with their UTF-8 equivalents.
72
+
73
+ :param value: The string value to normalize.
74
+ :return: The normalized string.
75
+ """
76
+ return value.encode('utf-8').decode('unicode_escape')
77
+
78
+ def normalize_integer(value):
79
+ """
80
+ Normalizes JSON integer literals by removing leading zeros.
81
+
82
+ :param value: The integer value to normalize.
83
+ :return: The normalized integer.
84
+ """
85
+ return int(value)
86
+
87
+ def fingerprint_sha256(schema_json):
88
+ """
89
+ Generates a SHA-256 fingerprint for the given Avro schema.
90
+
91
+ :param schema_json: The Avro schema as a JSON string.
92
+ :return: The SHA-256 fingerprint as a base64 string.
93
+ """
94
+ pcf = transform_to_pcf(schema_json)
95
+ sha256_hash = hashlib.sha256(pcf.encode('utf-8')).digest()
96
+ return base64.b64encode(sha256_hash).decode('utf-8')
97
+
98
+ def fingerprint_md5(schema_json):
99
+ """
100
+ Generates an MD5 fingerprint for the given Avro schema.
101
+
102
+ :param schema_json: The Avro schema as a JSON string.
103
+ :return: The MD5 fingerprint as a base64 string.
104
+ """
105
+ pcf = transform_to_pcf(schema_json)
106
+ md5_hash = hashlib.md5(pcf.encode('utf-8')).digest()
107
+ return base64.b64encode(md5_hash).decode('utf-8')
108
+
109
+ def fingerprint_rabin(schema_json):
110
+ """
111
+ Generates a 64-bit Rabin fingerprint for the given Avro schema.
112
+
113
+ :param schema_json: The Avro schema as a JSON string.
114
+ :return: The Rabin fingerprint as a base64 string.
115
+ """
116
+ pcf = transform_to_pcf(schema_json).encode('utf-8')
117
+ fp = fingerprint64(pcf)
118
+ return base64.b64encode(fp.to_bytes(8, 'big')).decode('utf-8')
119
+
120
+ def fingerprint64(buf):
121
+ """
122
+ Computes a 64-bit Rabin fingerprint.
123
+
124
+ :param buf: The input byte buffer.
125
+ :return: The 64-bit Rabin fingerprint.
126
+ """
127
+ if FP_TABLE is None:
128
+ init_fp_table()
129
+ fp = EMPTY
130
+ for byte in buf:
131
+ fp = (fp >> 8) ^ FP_TABLE[(fp ^ byte) & 0xff]
132
+ return fp
133
+
134
+ def init_fp_table():
135
+ """
136
+ Initializes the fingerprint table for the Rabin fingerprint algorithm.
137
+ """
138
+ global FP_TABLE
139
+ FP_TABLE = []
140
+ for i in range(256):
141
+ fp = i
142
+ for _ in range(8):
143
+ fp = (fp >> 1) ^ (EMPTY & -(fp & 1))
144
+ FP_TABLE.append(fp)
145
+
146
+ PRIMITIVE_TYPES = {"null", "boolean", "int", "long", "float", "double", "bytes", "string"}
147
+ FIELD_ORDER = ["name", "type", "fields", "symbols", "items", "values", "size"]
148
+
149
+ EMPTY = 0xc15d213aa4d7a795
150
+ FP_TABLE = None
151
+
152
+ class PCFSchemaResult:
153
+ def __init__(self, pcf: str, sha256: str, md5: str, rabin: str) -> None:
154
+ self.pcf = pcf
155
+ self.sha256 = sha256
156
+ self.md5 = md5
157
+ self.rabin = rabin
158
+
159
+ def pcf_schema(schema_json):
160
+ """
161
+ Wrapper function to provide PCF transformation and fingerprinting.
162
+
163
+ :param schema_json: The Avro schema as a JSON string.
164
+ :return: An instance of the PCFSchemaResult class containing the PCF and fingerprints (SHA-256, MD5, and Rabin) as base64 strings.
165
+ """
166
+ pcf = transform_to_pcf(schema_json)
167
+ return PCFSchemaResult(pcf, fingerprint_sha256(schema_json), fingerprint_md5(schema_json), fingerprint_rabin(schema_json))
168
+