-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpure_openapi_ingest.py
More file actions
1656 lines (1398 loc) · 62.9 KB
/
pure_openapi_ingest.py
File metadata and controls
1656 lines (1398 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Pure API → SQLite Ingestion Tool
A schema-driven tool that automatically ingests data from Elsevier Pure API
into a queryable SQLite database with full support for nested data structures,
discriminated unions, and localized content.
Features:
- Schema-driven design - everything driven by OpenAPI specification
- Deep nested array support with recursive unpacking to arbitrary depth
- Localization-aware - automatically detects and unpacks localized strings
- Discriminated union support - fully resolves OpenAPI oneOf/anyOf/allOf schemas
- Idempotent updates - content hash tracking for change detection
- Automatic retries with exponential backoff
- Rate limiting and timeout configuration
- Comprehensive logging with progress tracking
CLI:
python pure_openapi_ingest.py \
--openapi ./openapi.yaml \
--db ./pure.sqlite \
--discover # ingest all detected list endpoints
--max-depth 5 # maximum nesting depth (default: 5)
--limit 100 # test with limited items
# or pick specific paths
--paths /research-outputs /activities
.env (create a file next to your script):
PURE_BASE_URL=https://your-institution.pure.elsevier.com/ws/api
PURE_API_KEY=your_api_key_here
# Optional settings (defaults shown)
PAGE_SIZE=100 # Number of items per API request
RATE_LIMIT_RPS=3 # Requests per second (adjust based on your API limits)
TIMEOUT_SECONDS=60 # HTTP request timeout
RETRY_MAX=5 # Maximum retries on 5xx/429 errors
Dependencies:
pip install pyyaml requests
"""
import argparse
import hashlib
import json
import logging
import os
import re
import sqlite3
import sys
import time
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Set, Tuple, Union
try:
import yaml # pyyaml
except ImportError as e:
print("Missing dependency: pyyaml. Install with: pip install pyyaml", file=sys.stderr)
raise
try:
import requests
except ImportError:
print("Missing dependency: requests. Install with: pip install requests", file=sys.stderr)
raise
# -------------------------
# Configuration
# -------------------------
@dataclass
class Config:
"""Configuration for the ingestion process"""
max_depth: int = 5
prefix_separator: str = "_" # or "." for dot notation
array_table_separator: str = "__"
skip_empty_arrays: bool = True
detect_date_fields: bool = True
preserve_case: bool = False # if True, don't convert to snake_case
create_indexes: bool = True
verbose: bool = False
# -------------------------
# Small .env loader
# -------------------------
def load_env_file(path: str) -> Dict[str, str]:
env = {}
if not os.path.isfile(path):
return env
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, val = line.split("=", 1)
env[key.strip()] = val.strip()
return env
def getenv(key: str, default: Optional[str]=None) -> Optional[str]:
return os.environ.get(key, default)
# -------------------------
# Utility Functions
# -------------------------
def snake(name: str, preserve_case: bool = False) -> str:
"""Convert name to snake_case"""
if preserve_case:
return re.sub(r'[^0-9a-zA-Z]+', '_', name).strip('_') or "field"
name = re.sub(r'[^0-9a-zA-Z]+', '_', name)
name = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', name)
s = name.strip('_').lower()
return s or "field"
def safe_ident(name: str) -> str:
"""SQLite identifier quoting"""
return '"' + name.replace('"', '""') + '"'
def sha256_json(obj: Any) -> str:
"""Generate SHA256 hash of JSON object"""
return hashlib.sha256(
json.dumps(obj, sort_keys=True, separators=(",", ":")).encode("utf-8")
).hexdigest()
def now_iso() -> str:
"""Current time in ISO format"""
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
def is_date_field(name: str, schema: Dict[str, Any]) -> bool:
"""Detect if a field is likely a date/datetime"""
fmt = schema.get("format", "")
if fmt in ("date", "date-time", "datetime"):
return True
name_lower = name.lower()
return any(indicator in name_lower for indicator in
["date", "time", "created", "updated", "modified", "published"])
def is_scalar(schema: Dict[str, Any]) -> bool:
"""Check if schema represents a scalar type"""
t = schema.get("type")
return t in ("string", "number", "integer", "boolean", "null")
def sql_type_for(schema: Dict[str, Any], field_name: str = "", config: Config = None) -> str:
"""Determine SQL type for a schema"""
t = schema.get("type")
fmt = schema.get("format")
# Check for date/time types
if config and config.detect_date_fields and is_date_field(field_name, schema):
return "TEXT" # Store as ISO strings
if t == "integer":
return "INTEGER"
elif t == "number":
return "REAL"
elif t == "boolean":
return "INTEGER" # SQLite convention: 0/1
elif t == "null":
return "TEXT"
# Default to TEXT for strings, unknown types, objects
return "TEXT"
# -------------------------
# Schema Resolution
# -------------------------
class SchemaResolver:
"""Handles OpenAPI schema resolution including $ref, allOf, oneOf, anyOf"""
def __init__(self, components: Dict[str, Any]):
self.components = components
self._ref_cache: Dict[str, Dict[str, Any]] = {}
self._resolution_stack: List[str] = [] # Track resolution path to detect cycles
self._max_depth = 50 # Maximum recursion depth
def resolve(self, schema: Dict[str, Any]) -> Dict[str, Any]:
"""Recursively resolve schema with $ref, allOf, oneOf, anyOf"""
if not schema:
return {}
# Check recursion depth
if len(self._resolution_stack) > self._max_depth:
return {} # Return empty schema to prevent infinite recursion
# Handle $ref
if "$ref" in schema:
ref = schema["$ref"]
# Check if already in resolution stack (circular reference)
if ref in self._resolution_stack:
return {} # Break the cycle
if ref in self._ref_cache:
return self._ref_cache[ref]
# Add to stack before resolving
self._resolution_stack.append(ref)
try:
resolved = self._resolve_ref(ref)
self._ref_cache[ref] = resolved
return resolved
finally:
# Remove from stack after resolving
self._resolution_stack.pop()
# Handle discriminator with mapping (OpenAPI 3.0 style)
# This expands discriminator.mapping into oneOf-style resolution
# BUT: Don't expand if we're already inside a discriminator variant to avoid cycles
if "discriminator" in schema and "mapping" in schema["discriminator"]:
# Check if any variant is already in the resolution stack (would create cycle)
mapping = schema["discriminator"]["mapping"]
variant_refs = [ref for ref in mapping.values() if isinstance(ref, str)]
# If we're already resolving one of the variants, don't expand the discriminator
# Just return the base schema to break the cycle
if any(ref in self._resolution_stack for ref in variant_refs):
# Return base schema without expanding variants
result = dict(schema)
# Still recursively resolve nested properties
if "properties" in result:
result["properties"] = {
k: self.resolve(v) for k, v in result["properties"].items()
}
return result
# Safe to expand - convert mapping to list of schema refs
variant_schemas = []
for variant_ref in mapping.values():
if isinstance(variant_ref, str):
variant_schemas.append({"$ref": variant_ref})
else:
variant_schemas.append(variant_ref)
# Merge all variants plus the base schema's own properties
merged = self._merge_schemas(variant_schemas)
# Also merge any properties defined directly on the base
if "properties" in schema:
base_props = schema["properties"]
if "properties" not in merged:
merged["properties"] = {}
merged["properties"].update(base_props)
merged["x-discriminator"] = schema["discriminator"]
return merged
# Handle allOf (merge all schemas)
if "allOf" in schema:
return self._merge_schemas(schema["allOf"])
# Handle oneOf/anyOf (merge all schemas to capture all possible fields)
# This ensures we create tables for fields that exist in ANY variant
# of a discriminated union (e.g., both Internal and External contributor types)
if "oneOf" in schema:
merged = self._merge_schemas(schema["oneOf"])
# Preserve discriminator info if available
if "discriminator" in schema:
merged["x-discriminator"] = schema["discriminator"]
return merged
if "anyOf" in schema:
return self._merge_schemas(schema["anyOf"])
# Recursively resolve nested schemas
result = dict(schema)
if "properties" in result:
result["properties"] = {
k: self.resolve(v) for k, v in result["properties"].items()
}
if "items" in result:
result["items"] = self.resolve(result["items"])
return result
def _resolve_ref(self, ref: str) -> Dict[str, Any]:
"""Resolve a $ref pointer"""
if not ref.startswith("#/"):
raise ValueError(f"External $ref not supported: {ref}")
parts = ref.lstrip("#/").split("/")
node = {"components": self.components}
for part in parts:
if part == "components":
node = node["components"]
else:
node = node.get(part, {})
# Recursively resolve in case the referenced schema has refs
return self.resolve(node)
def _merge_schemas(self, schemas: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Merge multiple schemas (for allOf, anyOf)"""
result: Dict[str, Any] = {}
all_properties: Dict[str, Dict] = {}
for s in schemas:
resolved = self.resolve(s)
# Merge properties
if "properties" in resolved:
all_properties.update(resolved["properties"])
# Merge other fields (last one wins)
for k, v in resolved.items():
if k != "properties":
result[k] = v
if all_properties:
result["properties"] = all_properties
return result
# -------------------------
# Field Path Builder
# -------------------------
@dataclass
class FieldPath:
"""Represents a path to a field in nested structure"""
parts: List[str]
schema: Dict[str, Any]
is_array: bool = False
array_depth: int = 0
def to_column_name(self, separator: str = "_") -> str:
"""Convert path to column name"""
return separator.join(self.parts)
def __str__(self) -> str:
return ".".join(self.parts)
class SchemaFlattener:
"""Flattens nested schemas into table structures"""
def __init__(self, resolver: SchemaResolver, config: Config):
self.resolver = resolver
self.config = config
def _is_locale_dict_schema(self, schema: Dict[str, Any]) -> bool:
"""Check if schema represents a locale dictionary (FormattedLocalizedString, etc.)"""
# Check for additionalProperties pattern used by FormattedLocalizedString
if schema.get("type") == "object" and "additionalProperties" in schema:
# Check if description mentions "localized" or it's a string dict
desc = schema.get("description", "").lower()
if "localized" in desc or "locale" in desc:
return True
# Check if additionalProperties is string type
add_props = schema.get("additionalProperties", {})
if isinstance(add_props, dict) and add_props.get("type") == "string":
return True
return False
def _is_formatted_string_schema(self, schema: Dict[str, Any]) -> bool:
"""Check if schema represents FormattedString {value: string}"""
if schema.get("type") != "object":
return False
props = schema.get("properties", {})
# FormattedString has a single 'value' property of type string
if "value" in props:
value_schema = props["value"]
if isinstance(value_schema, dict) and value_schema.get("type") == "string":
return True
return False
def flatten_schema(self, schema: Dict[str, Any], prefix: str = "",
depth: int = 0) -> Dict[str, FieldPath]:
"""
Recursively flatten schema into a dict of column_name -> FieldPath
Args:
schema: OpenAPI schema to flatten
prefix: Current path prefix
depth: Current recursion depth
Returns:
Dict mapping column names to field paths
"""
if depth > self.config.max_depth:
return {}
schema = self.resolver.resolve(schema)
fields: Dict[str, FieldPath] = {}
schema_type = schema.get("type")
properties = schema.get("properties", {})
if schema_type == "object" and properties:
for prop_name, prop_schema in properties.items():
prop_schema = self.resolver.resolve(prop_schema)
field_prefix = f"{prefix}{prop_name}" if prefix else prop_name
prop_type = prop_schema.get("type")
if is_scalar(prop_schema):
# Scalar field - add directly
path_parts = field_prefix.split(self.config.prefix_separator)
fields[field_prefix] = FieldPath(
parts=path_parts,
schema=prop_schema,
is_array=False
)
elif self._is_locale_dict_schema(prop_schema):
# Locale dictionary - create columns for common locales
# These will be populated at runtime by DataUnpacker
for locale in ["en_GB", "da_DK"]:
locale_field = f"{field_prefix}_{locale.lower()}"
path_parts = locale_field.split(self.config.prefix_separator)
fields[locale_field] = FieldPath(
parts=path_parts,
schema={"type": "string"}, # locale values are strings
is_array=False
)
elif self._is_formatted_string_schema(prop_schema):
# FormattedString {value: "text"} - create a single column
# The DataUnpacker will extract the value field at runtime
path_parts = field_prefix.split(self.config.prefix_separator)
fields[field_prefix] = FieldPath(
parts=path_parts,
schema={"type": "string"}, # value is a string
is_array=False
)
elif prop_type == "object":
# Nested object - recurse
nested_fields = self.flatten_schema(
prop_schema,
prefix=field_prefix + self.config.prefix_separator,
depth=depth + 1
)
fields.update(nested_fields)
elif prop_type == "array":
# Array - will be handled as child table
# Store info about the array itself
items_schema = self.resolver.resolve(prop_schema.get("items", {}))
path_parts = field_prefix.split(self.config.prefix_separator)
fields[field_prefix] = FieldPath(
parts=path_parts,
schema=items_schema,
is_array=True,
array_depth=1
)
return fields
# -------------------------
# Enhanced SQLite Schema Builder
# -------------------------
@dataclass
class TableSchema:
"""Represents a table schema"""
name: str
columns: Dict[str, str] # column_name -> SQL type
primary_key: List[str]
foreign_keys: List[Tuple[str, str, str]] # (column, ref_table, ref_column)
indexes: List[List[str]] # columns to index
parent_table: Optional[str] = None
class EnhancedSQLiteBuilder:
"""Builds SQLite schema with deep unpacking support"""
def __init__(self, conn: sqlite3.Connection, resolver: SchemaResolver, config: Config):
self.conn = conn
self.resolver = resolver
self.config = config
self.flattener = SchemaFlattener(resolver, config)
self.created_tables: Set[str] = set()
self.table_schemas: Dict[str, TableSchema] = {}
def _get_child_table_name(self, parent_table: str, field_name: str) -> str:
"""Generate child table name from parent and field name"""
field_snake = snake(field_name, self.config.preserve_case)
return f"{parent_table}{self.config.array_table_separator}{field_snake}"
def create_parent_table(self, base_name: str, item_schema: Dict[str, Any]) -> TableSchema:
"""Create main table for an endpoint with deep unpacking"""
table_name = snake(base_name, self.config.preserve_case)
if table_name in self.created_tables:
return self.table_schemas[table_name]
# Flatten the schema
flat_fields = self.flattener.flatten_schema(item_schema)
# Determine primary key
pk_candidates = ["uuid", "id", "pureId"]
pk_field = None
for candidate in pk_candidates:
if candidate in flat_fields or snake(candidate) in flat_fields:
pk_field = snake(candidate, self.config.preserve_case)
break
if not pk_field:
pk_field = "uuid" # fallback
# Build columns
columns = {
pk_field: "TEXT",
"raw_json": "TEXT",
"hash": "TEXT",
"first_seen": "TEXT",
"last_seen": "TEXT"
}
# Add flattened scalar columns
for field_name, field_path in flat_fields.items():
if not field_path.is_array: # Skip arrays - they become child tables
col_name = snake(field_name, self.config.preserve_case)
if col_name not in columns:
columns[col_name] = sql_type_for(
field_path.schema,
field_name,
self.config
)
# Create table
col_defs = []
for col_name, col_type in columns.items():
if col_name == pk_field:
col_defs.append(f"{safe_ident(col_name)} {col_type} PRIMARY KEY")
else:
col_defs.append(f"{safe_ident(col_name)} {col_type}")
ddl = f"CREATE TABLE IF NOT EXISTS {safe_ident(table_name)} (\n "
ddl += ",\n ".join(col_defs)
ddl += "\n);"
if self.config.verbose:
print(f"Creating table {table_name} with {len(columns)} columns")
self.conn.execute(ddl)
self.conn.commit()
# Create indexes
if self.config.create_indexes:
# Index on hash for deduplication
self._create_index(table_name, ["hash"])
# Index on timestamp fields
self._create_index(table_name, ["last_seen"])
schema = TableSchema(
name=table_name,
columns=columns,
primary_key=[pk_field],
foreign_keys=[],
indexes=[["hash"], ["last_seen"]]
)
self.created_tables.add(table_name)
self.table_schemas[table_name] = schema
return schema
def create_child_table(self, parent_table: str, field_name: str,
items_schema: Dict[str, Any], depth: int = 1) -> TableSchema:
"""Create child table for array field with deep unpacking"""
items_schema = self.resolver.resolve(items_schema)
# Generate table name using helper method
table_name = self._get_child_table_name(parent_table, field_name)
if table_name in self.created_tables:
return self.table_schemas[table_name]
# Parent FK columns - need to match parent's primary key
parent_schema = self.table_schemas[parent_table]
parent_pk_cols = parent_schema.primary_key
columns = {}
# Add FK columns for each parent PK column
fk_col_names = []
for parent_pk_col in parent_pk_cols:
fk_col_name = f"{parent_table}_{parent_pk_col}"
columns[fk_col_name] = "TEXT"
fk_col_names.append(fk_col_name)
# Create composite foreign key constraint
# Format: [(fk_columns_list, ref_table, ref_columns_list)]
foreign_keys = [(fk_col_names, parent_table, parent_pk_cols)]
# Add ordinal column for array ordering
columns["ord"] = "INTEGER"
# Primary key is all parent FK columns + ord
primary_key = fk_col_names + ["ord"]
if is_scalar(items_schema):
# Array of scalars
columns["value"] = sql_type_for(items_schema, field_name, self.config)
else:
# Array of objects - flatten recursively
flat_fields = self.flattener.flatten_schema(items_schema, depth=depth)
for field_path_name, field_path in flat_fields.items():
if not field_path.is_array:
col_name = snake(field_path_name, self.config.preserve_case)
if col_name not in columns:
columns[col_name] = sql_type_for(
field_path.schema,
field_path_name,
self.config
)
# Always store raw JSON for complex objects
columns["raw_json"] = "TEXT"
# Create table
col_defs = []
for col_name, col_type in columns.items():
col_defs.append(f"{safe_ident(col_name)} {col_type}")
# Add primary key constraint
pk_cols = ", ".join(safe_ident(c) for c in primary_key)
col_defs.append(f"PRIMARY KEY ({pk_cols})")
# Add foreign key constraints (now supporting composite FKs)
for fk_entry in foreign_keys:
if isinstance(fk_entry[0], list):
# Composite foreign key: (list of fk_cols, ref_table, list of ref_cols)
fk_cols, ref_table, ref_cols = fk_entry
fk_cols_str = ", ".join(safe_ident(c) for c in fk_cols)
ref_cols_str = ", ".join(safe_ident(c) for c in ref_cols)
col_defs.append(
f"FOREIGN KEY ({fk_cols_str}) "
f"REFERENCES {safe_ident(ref_table)}({ref_cols_str}) "
f"ON DELETE CASCADE"
)
else:
# Single foreign key (backward compatibility): (fk_col, ref_table, ref_col)
fk_col, ref_table, ref_col = fk_entry
col_defs.append(
f"FOREIGN KEY ({safe_ident(fk_col)}) "
f"REFERENCES {safe_ident(ref_table)}({safe_ident(ref_col)}) "
f"ON DELETE CASCADE"
)
ddl = f"CREATE TABLE IF NOT EXISTS {safe_ident(table_name)} (\n "
ddl += ",\n ".join(col_defs)
ddl += "\n);"
if self.config.verbose:
print(f"Creating child table {table_name} with {len(columns)} columns")
self.conn.execute(ddl)
self.conn.commit()
# Create indexes
# Index on the first parent FK column (typically the main parent UUID)
if self.config.create_indexes and fk_col_names:
self._create_index(table_name, [fk_col_names[0]])
schema = TableSchema(
name=table_name,
columns=columns,
primary_key=primary_key,
foreign_keys=foreign_keys,
indexes=[fk_col_names[:1]] if fk_col_names else [],
parent_table=parent_table
)
self.created_tables.add(table_name)
self.table_schemas[table_name] = schema
# Recursively create child tables for nested arrays in the items schema
if not is_scalar(items_schema) and depth < self.config.max_depth:
props = items_schema.get("properties", {})
for nested_field_name, nested_field_schema in props.items():
nested_field_schema = self.resolver.resolve(nested_field_schema)
if nested_field_schema.get("type") == "array":
nested_items_schema = self.resolver.resolve(
nested_field_schema.get("items", {})
)
# Create nested child table
self.create_child_table(
table_name,
nested_field_name,
nested_items_schema,
depth=depth + 1
)
if self.config.verbose:
nested_table = self._get_child_table_name(table_name, nested_field_name)
print(f" Created nested child table: {nested_table}")
return schema
def _create_index(self, table: str, columns: List[str]) -> None:
"""Create index on specified columns"""
idx_name = f"idx_{table}_{'_'.join(columns)}"
col_list = ", ".join(safe_ident(c) for c in columns)
try:
self.conn.execute(
f"CREATE INDEX IF NOT EXISTS {safe_ident(idx_name)} "
f"ON {safe_ident(table)} ({col_list})"
)
except sqlite3.OperationalError:
pass # Index might already exist
# -------------------------
# Enhanced Data Unpacker
# -------------------------
class DataUnpacker:
"""Unpacks nested data structures recursively with Pure-specific patterns"""
def __init__(self, config: Config):
self.config = config
def _is_locale_dict(self, value: Any) -> bool:
"""Check if value is a dict with locale keys (en_GB, da_DK, etc.)"""
if not isinstance(value, dict) or not value:
return False
# Check if keys look like locales
for key in value.keys():
if "_" in key and len(key) == 5: # e.g., en_GB, da_DK
return True
return False
def _is_localized_array(self, value: Any) -> bool:
"""Check if value is an array with locale/value dicts"""
if not isinstance(value, list) or not value:
return False
first = value[0]
return isinstance(first, dict) and "locale" in first and "value" in first
def _unpack_locale_dict(self, value_dict: Dict, field_key: str) -> Dict[str, Any]:
"""Unpack locale dictionary {en_GB: 'text', da_DK: 'tekst'}"""
result = {}
for locale, text in value_dict.items():
clean_locale = locale.replace("-", "_")
col_name = f"{field_key}_{clean_locale}"
result[col_name] = text
return result
def _unpack_localized_array(self, values: List[Dict], field_key: str) -> Dict[str, Any]:
"""Unpack array [{locale: 'en', value: 'text'}, ...]"""
result = {}
for item in values:
if not isinstance(item, dict):
continue
locale = item.get("locale", "").replace("-", "_")
text = item.get("value", "")
if locale and text:
col_name = f"{field_key}_{locale}"
result[col_name] = text
return result
def _is_person_reference(self, value: Any) -> bool:
"""Check if this is a person reference object {systemName: 'Person', uuid: '...'}"""
if not isinstance(value, dict):
return False
return value.get("systemName") == "Person" and "uuid" in value
def _is_org_reference(self, value: Any) -> bool:
"""Check if this is an org reference object {systemName: 'Organization', uuid: '...'}"""
if not isinstance(value, dict):
return False
return value.get("systemName") == "Organization" and "uuid" in value
def _extract_person_name(self, name_obj: Any) -> str:
"""Extract full name from Pure name object"""
if not isinstance(name_obj, dict):
return ""
first = name_obj.get("firstName", "")
last = name_obj.get("lastName", "")
return f"{first} {last}".strip()
def unpack_object(self, data: Dict[str, Any], schema: Dict[str, Any],
prefix: str = "", depth: int = 0) -> Dict[str, Any]:
"""
Recursively unpack nested object with Pure-specific patterns
Handles:
- Locale dicts: {en_GB: 'text', da_DK: 'tekst'}
- Locale arrays: [{locale: 'en', value: 'text'}]
- Nested locale values: {value: {en_GB: 'text'}}
- Nested locale terms: {term: {en_GB: 'text'}}
- Person references: {systemName: 'Person', uuid: '...'}
- Person with name: {name: {firstName, lastName}, uuid: '...'}
"""
if depth > self.config.max_depth:
return {}
result = {}
properties = schema.get("properties", {})
for key, value in data.items():
if value is None:
continue
prop_schema = properties.get(key, {})
field_key = f"{prefix}{key}" if prefix else key
prop_type = prop_schema.get("type")
# Pattern 1: Localized array [{locale, value}]
if self._is_localized_array(value):
localized = self._unpack_localized_array(value, field_key)
result.update(localized)
continue
# Pattern 2: Person reference {systemName: 'Person', uuid: '...'}
if self._is_person_reference(value):
result[f"{field_key}_uuid"] = value.get("uuid")
continue
# Pattern 3: Organization reference
if self._is_org_reference(value):
result[f"{field_key}_uuid"] = value.get("uuid")
continue
# Pattern 4: Object with 'value' field containing locales
if isinstance(value, dict) and "value" in value:
nested_value = value["value"]
if self._is_locale_dict(nested_value):
# description: {value: {en_GB: 'text', da_DK: 'tekst'}, type: {...}}
localized = self._unpack_locale_dict(nested_value, field_key)
result.update(localized)
# Also unpack other fields in the object (like 'type')
for sub_key, sub_value in value.items():
if sub_key != "value" and sub_value is not None:
sub_field_key = f"{field_key}_{sub_key}"
if isinstance(sub_value, dict):
sub_unpacked = self.unpack_object(
sub_value, {},
prefix=sub_field_key + self.config.prefix_separator,
depth=depth + 1
)
result.update(sub_unpacked)
else:
result[sub_field_key] = sub_value
continue
elif isinstance(nested_value, (str, int, float, bool)):
# Simple value field
result[field_key] = nested_value
continue
# Pattern 5: Object with 'term' field containing locales
if isinstance(value, dict) and "term" in value:
nested_term = value["term"]
if self._is_locale_dict(nested_term):
# role: {term: {en_GB: 'Recipient', da_DK: 'Modtager'}, uri: '...'}
localized = self._unpack_locale_dict(nested_term, f"{field_key}_term")
result.update(localized)
# Unpack other fields like 'uri'
for sub_key, sub_value in value.items():
if sub_key != "term" and sub_value is not None:
result[f"{field_key}_{sub_key}"] = sub_value
continue
# Pattern 6: Person association with name object
if isinstance(value, dict) and "name" in value:
name_obj = value.get("name")
if isinstance(name_obj, dict) and ("firstName" in name_obj or "lastName" in name_obj):
# Extract person name
full_name = self._extract_person_name(name_obj)
if full_name:
result[f"{field_key}_name"] = full_name
# Also extract other person fields
for sub_key, sub_value in value.items():
if sub_key == "name":
continue
elif sub_key == "person" and self._is_person_reference(sub_value):
result[f"{field_key}_person_uuid"] = sub_value.get("uuid")
elif isinstance(sub_value, dict):
sub_unpacked = self.unpack_object(
sub_value, {},
prefix=f"{field_key}_{sub_key}{self.config.prefix_separator}",
depth=depth + 1
)
result.update(sub_unpacked)
else:
result[f"{field_key}_{sub_key}"] = sub_value
continue
# Pattern 7: Locale dict (direct)
if self._is_locale_dict(value):
localized = self._unpack_locale_dict(value, field_key)
result.update(localized)
continue
# Pattern 8: Scalar values
if isinstance(value, (str, int, float, bool)):
result[field_key] = value
continue
# Pattern 9: Nested object (recurse)
if isinstance(value, dict):
nested = self.unpack_object(
value,
prop_schema,
prefix=field_key + self.config.prefix_separator,
depth=depth + 1
)
result.update(nested)
continue
# Pattern 10: Arrays (will be handled as child tables elsewhere)
if isinstance(value, list):
pass # Skip - arrays become child tables
continue
# Fallback: Store as JSON
result[field_key] = json.dumps(value)
return result
# -------------------------
# Enhanced Upsert Logic
# -------------------------
def upsert_parent(cur: sqlite3.Cursor, table_schema: TableSchema,
pk_value: str, raw_json: Dict[str, Any],
flat_data: Dict[str, Any], config: Config) -> None:
"""Upsert parent table record with unpacked data"""
pk_field = table_schema.primary_key[0]
h = sha256_json(raw_json)
first_seen = now_iso()
last_seen = first_seen
# Check existing hash
cur.execute(
f'SELECT {safe_ident("hash")}, {safe_ident("first_seen")} '
f'FROM {safe_ident(table_schema.name)} '
f'WHERE {safe_ident(pk_field)}=?',
(pk_value,)
)
row = cur.fetchone()
# Prepare column data
col_data = {
pk_field: pk_value,
"raw_json": json.dumps(raw_json),
"hash": h,
"last_seen": last_seen
}
# Add flattened data (only columns that exist in table)
for key, value in flat_data.items():
col_name = snake(key, config.preserve_case)
if col_name in table_schema.columns:
col_data[col_name] = value
if row is None:
# Insert new record
col_data["first_seen"] = first_seen
columns = list(col_data.keys())
placeholders = ",".join(["?"] * len(columns))
col_names = ",".join(safe_ident(c) for c in columns)
cur.execute(
f'INSERT INTO {safe_ident(table_schema.name)} ({col_names}) '
f'VALUES ({placeholders})',
[col_data[c] for c in columns]
)
else:
existing_hash, existing_first_seen = row
col_data["first_seen"] = existing_first_seen
if existing_hash != h:
# Data changed - update all fields
set_parts = [f"{safe_ident(k)}=?" for k in col_data.keys() if k != pk_field]
set_clause = ", ".join(set_parts)
cur.execute(
f'UPDATE {safe_ident(table_schema.name)} '
f'SET {set_clause} '
f'WHERE {safe_ident(pk_field)}=?',
[col_data[k] for k in col_data.keys() if k != pk_field] + [pk_value]
)
else:
# Just update last_seen
cur.execute(
f'UPDATE {safe_ident(table_schema.name)} '
f'SET {safe_ident("last_seen")}=? '
f'WHERE {safe_ident(pk_field)}=?',
(last_seen, pk_value)
)
def insert_child_array(cur: sqlite3.Cursor, child_schema: TableSchema,
parent_pk_values: Union[str, Dict[str, Any]], items_schema: Dict[str, Any],
array_data: List[Any], unpacker: DataUnpacker,
builder: 'EnhancedSQLiteBuilder' = None) -> None:
"""Insert array data into child table with deep unpacking
Args:
parent_pk_values: Either a string (for single-column PK) or dict mapping parent's PK column names to values
"""
if not array_data and unpacker.config.skip_empty_arrays:
return
# Get the FK columns from the child schema's foreign key metadata