napppy commited on
Commit
e71ccc4
·
1 Parent(s): 8ddb808

feat: add memberships

Browse files
databases/data.duckdb CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:61e70b472a2b545005f5668a47b292381c50348db0083dab886fe65457d84c4c
3
- size 5779456
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82433f465a60e793068d978c267fc8247e50afe187c3e226f132d3c5ff9385d1
3
+ size 19935232
scripts/load_persons_to_db.py CHANGED
@@ -16,6 +16,7 @@ import duckdb
16
  sys.path.insert(0, str(Path(__file__).parent.parent))
17
 
18
  from schemas.person import PERSON_SCHEMA
 
19
  from schemas.base import transform_value
20
  from config import DATABASE_PATH, PERSON_DATA_DIR
21
 
@@ -41,22 +42,35 @@ def create_persons_table(conn: duckdb.DuckDBPyConnection):
41
  conn.execute(create_sql)
42
 
43
 
 
 
 
 
 
 
 
 
 
 
44
  def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = False, parquet_path: Path = None):
45
  """Load all person TOML files into the DuckDB database."""
46
  print(f"Connecting to database: {db_path}")
47
  conn = duckdb.connect(str(db_path))
48
 
49
- # Create table with explicit schema
50
  create_persons_table(conn)
 
51
 
52
- # Build INSERT statement using schema definition
53
- insert_sql = PERSON_SCHEMA.get_insert_sql()
 
54
 
55
  # Load data within a single transaction for performance
56
  print("\nLoading person data...")
57
  loaded_count = 0
58
  error_count = 0
59
  processed_count = 0
 
60
  unknown_fields_seen = set()
61
 
62
  # Start explicit transaction
@@ -68,8 +82,9 @@ def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = Fal
68
  person_data = load_toml_file(toml_file)
69
 
70
  # Warn about unknown fields (helps catch typos)
 
71
  for field in person_data.keys():
72
- if field not in PERSON_SCHEMA.schema and field not in unknown_fields_seen:
73
  print(f" Warning: Unknown field '{field}' found in {toml_file.name} (will be ignored)")
74
  unknown_fields_seen.add(field)
75
 
@@ -81,7 +96,29 @@ def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = Fal
81
  ]
82
 
83
  # Insert person data
84
- conn.execute(insert_sql, values)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  loaded_count += 1
87
  processed_count += 1
@@ -113,12 +150,14 @@ def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = Fal
113
  print(f" Errors: {error_count}")
114
 
115
  # Show database stats
116
- result = conn.execute("SELECT COUNT(*) as total FROM persons").fetchone()
117
- print(f" Total persons in database: {result[0]}")
 
 
118
  print(f"{'='*60}")
119
 
120
  # Show sample data
121
- print("\nSample data (first 5 rows):")
122
  sample = conn.execute("""
123
  SELECT id, first_name, last_name, name_suffix
124
  FROM persons
@@ -129,6 +168,24 @@ def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = Fal
129
  suffix = f" {row[3]}" if row[3] else ""
130
  print(f" {row[0]}: {row[1]} {row[2]}{suffix}")
131
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
  # Export to Parquet if requested
133
  if export_parquet:
134
  print(f"\n{'='*60}")
 
16
  sys.path.insert(0, str(Path(__file__).parent.parent))
17
 
18
  from schemas.person import PERSON_SCHEMA
19
+ from schemas.membership import MEMBERSHIP_SCHEMA
20
  from schemas.base import transform_value
21
  from config import DATABASE_PATH, PERSON_DATA_DIR
22
 
 
42
  conn.execute(create_sql)
43
 
44
 
45
+ def create_memberships_table(conn: duckdb.DuckDBPyConnection):
46
+ """Create the memberships table using the explicit schema."""
47
+ create_sql = MEMBERSHIP_SCHEMA.get_create_table_sql()
48
+
49
+ print(f"Creating table '{MEMBERSHIP_SCHEMA.table_name}' with {len(MEMBERSHIP_SCHEMA.schema)} columns:")
50
+ print(f" Fields: {', '.join(MEMBERSHIP_SCHEMA.field_order)}")
51
+
52
+ conn.execute(create_sql)
53
+
54
+
55
  def load_persons_to_db(data_dir: Path, db_path: Path, export_parquet: bool = False, parquet_path: Path = None):
56
  """Load all person TOML files into the DuckDB database."""
57
  print(f"Connecting to database: {db_path}")
58
  conn = duckdb.connect(str(db_path))
59
 
60
+ # Create tables with explicit schema
61
  create_persons_table(conn)
62
+ create_memberships_table(conn)
63
 
64
+ # Build INSERT statements using schema definitions
65
+ insert_person_sql = PERSON_SCHEMA.get_insert_sql()
66
+ insert_membership_sql = MEMBERSHIP_SCHEMA.get_insert_sql()
67
 
68
  # Load data within a single transaction for performance
69
  print("\nLoading person data...")
70
  loaded_count = 0
71
  error_count = 0
72
  processed_count = 0
73
+ memberships_loaded_count = 0
74
  unknown_fields_seen = set()
75
 
76
  # Start explicit transaction
 
82
  person_data = load_toml_file(toml_file)
83
 
84
  # Warn about unknown fields (helps catch typos)
85
+ # Skip 'memberships' as it's handled separately
86
  for field in person_data.keys():
87
+ if field not in PERSON_SCHEMA.schema and field != 'memberships' and field not in unknown_fields_seen:
88
  print(f" Warning: Unknown field '{field}' found in {toml_file.name} (will be ignored)")
89
  unknown_fields_seen.add(field)
90
 
 
96
  ]
97
 
98
  # Insert person data
99
+ conn.execute(insert_person_sql, values)
100
+
101
+ # Extract and insert memberships for this person
102
+ person_id = person_data.get('id')
103
+ memberships = person_data.get('memberships', [])
104
+
105
+ for idx, membership in enumerate(memberships):
106
+ # Generate unique ID for membership: person_id + index
107
+ membership_id = f"{person_id}_m{idx}"
108
+
109
+ membership_values = [
110
+ membership_id,
111
+ person_id,
112
+ membership.get('party'),
113
+ membership.get('region'),
114
+ membership.get('province'),
115
+ membership.get('locality'), # May be None/missing
116
+ membership.get('position'),
117
+ membership.get('year'),
118
+ ]
119
+
120
+ conn.execute(insert_membership_sql, membership_values)
121
+ memberships_loaded_count += 1
122
 
123
  loaded_count += 1
124
  processed_count += 1
 
150
  print(f" Errors: {error_count}")
151
 
152
  # Show database stats
153
+ persons_count = conn.execute("SELECT COUNT(*) as total FROM persons").fetchone()
154
+ memberships_count = conn.execute("SELECT COUNT(*) as total FROM memberships").fetchone()
155
+ print(f" Total persons in database: {persons_count[0]}")
156
+ print(f" Total memberships in database: {memberships_count[0]}")
157
  print(f"{'='*60}")
158
 
159
  # Show sample data
160
+ print("\nSample persons (first 5 rows):")
161
  sample = conn.execute("""
162
  SELECT id, first_name, last_name, name_suffix
163
  FROM persons
 
168
  suffix = f" {row[3]}" if row[3] else ""
169
  print(f" {row[0]}: {row[1]} {row[2]}{suffix}")
170
 
171
+ # Show sample memberships
172
+ print("\nSample memberships (first 5 rows):")
173
+ memberships_sample = conn.execute("""
174
+ SELECT
175
+ p.first_name,
176
+ p.last_name,
177
+ m.party,
178
+ m.position,
179
+ m.region,
180
+ m.year
181
+ FROM memberships m
182
+ JOIN persons p ON m.person_id = p.id
183
+ LIMIT 5
184
+ """).fetchall()
185
+
186
+ for row in memberships_sample:
187
+ print(f" {row[0]} {row[1]} - {row[3]} ({row[2]}) in {row[4]}, {row[5]}")
188
+
189
  # Export to Parquet if requested
190
  if export_parquet:
191
  print(f"\n{'='*60}")