napppy commited on
Commit
67e2a15
·
1 Parent(s): 9dd6e61

feat: add loader

Browse files
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ tomlkit==0.13.3
2
+ duckdb==1.4.1
schemas/README.md ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Schemas
2
+
3
+ This directory contains schema definitions for various entity types in the raw Philippine data project.
4
+
5
+ ## Structure
6
+
7
+ - `base.py` - Base classes and utilities for all schemas
8
+ - `person.py` - Schema definition for persons
9
+ - Add more entity schemas as needed
10
+
11
+ ## How to Define a New Schema
12
+
13
+ ### 1. Create a new schema file
14
+
15
+ Create `schemas/your_entity.py`:
16
+
17
+ ```python
18
+ from schemas.base import SchemaDefinition
19
+
20
+ YOUR_ENTITY_SCHEMA = SchemaDefinition(
21
+ table_name='your_entities',
22
+ schema={
23
+ 'id': 'VARCHAR PRIMARY KEY',
24
+ 'name': 'VARCHAR',
25
+ 'nested_field': 'JSON',
26
+ },
27
+ field_order=['id', 'name', 'nested_field'],
28
+ nested_fields=set(['nested_field'])
29
+ )
30
+ ```
31
+
32
+ ### 2. Create a loader script
33
+
34
+ Create `scripts/load_your_entity_to_db.py`:
35
+
36
+ ```python
37
+ import sys
38
+ import argparse
39
+ from pathlib import Path
40
+ sys.path.insert(0, str(Path(__file__).parent.parent))
41
+
42
+ from schemas.your_entity import YOUR_ENTITY_SCHEMA
43
+ from schemas.base import transform_value
44
+ from config import DATABASE_PATH
45
+
46
+ # Then use YOUR_ENTITY_SCHEMA.get_create_table_sql(), etc.
47
+ # Add argparse with --db-path argument for flexibility
48
+ # Default database: databases/data.duckdb (shared across all entities)
49
+ ```
50
+
51
+ ### 3. Update the schema as needed
52
+
53
+ When adding new fields:
54
+ 1. Add to `schema` dict with SQL type
55
+ 2. Add to `field_order` list
56
+ 3. If nested (dict/array), add to `nested_fields` set
57
+
58
+ ## Schema Definition Reference
59
+
60
+ ### `SchemaDefinition` class
61
+
62
+ **Attributes:**
63
+ - `table_name` (str): Name of the database table
64
+ - `schema` (dict): Field names → SQL types
65
+ - `field_order` (list): Ordered list of fields for INSERT
66
+ - `nested_fields` (set): Fields containing JSON/nested data
67
+
68
+ **Methods:**
69
+ - `get_create_table_sql()`: Returns CREATE TABLE statement
70
+ - `get_insert_sql()`: Returns INSERT statement with placeholders
71
+
72
+ ### `transform_value()` function
73
+
74
+ Transforms TOML values for database storage:
75
+ - Converts dicts/lists to JSON for nested fields
76
+ - Passes through primitive types unchanged
77
+ - Handles None values
78
+
79
+ **Usage:**
80
+ ```python
81
+ from schemas.base import transform_value
82
+
83
+ value = transform_value(
84
+ field_name='positions',
85
+ value={'title': 'Mayor'},
86
+ nested_fields={'positions'}
87
+ )
88
+ # Returns: '{"title": "Mayor"}'
89
+ ```
90
+
91
+ ## Adding Nested Fields
92
+
93
+ For nested data (objects, arrays):
94
+
95
+ 1. Add field to schema with `JSON` type:
96
+ ```python
97
+ schema={'positions': 'JSON'}
98
+ ```
99
+
100
+ 2. Add to nested_fields set:
101
+ ```python
102
+ nested_fields=set(['positions'])
103
+ ```
104
+
105
+ 3. Use transform_value when inserting:
106
+ ```python
107
+ values = [
108
+ transform_value(field, data.get(field), SCHEMA.nested_fields)
109
+ for field in SCHEMA.field_order
110
+ ]
111
+ ```
112
+
113
+ ## Database Configuration
114
+
115
+ All loader scripts use the shared `config.py` file which defines:
116
+ - **DATABASE_PATH**: Default path to `databases/data.duckdb` (shared by all entities)
117
+ - All entities (persons, groups, etc.) are stored in the same database as separate tables
118
+ - Use `--db-path` CLI argument to override the default database path
119
+
120
+ ## Examples
121
+
122
+ - **Person schema**: `person.py` - Basic schema with flat fields
schemas/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """
2
+ Schema definitions for raw Philippine data.
3
+
4
+ This package contains schema definitions for various entity types
5
+ (persons, groups, etc.) that define how data is structured in the database.
6
+ """
schemas/base.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Base utilities for schema definitions.
3
+
4
+ Provides common functionality for transforming and validating data
5
+ across different entity types.
6
+ """
7
+
8
+ import json
9
+ from typing import Any, Dict, Set
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass
14
+ class SchemaDefinition:
15
+ """
16
+ Base schema definition for an entity type.
17
+
18
+ Attributes:
19
+ table_name: Name of the database table
20
+ schema: Dict mapping field names to SQL types
21
+ field_order: List of fields in order for INSERT statements
22
+ nested_fields: Set of field names that contain nested/complex data
23
+ """
24
+ table_name: str
25
+ schema: Dict[str, str]
26
+ field_order: list[str]
27
+ nested_fields: Set[str]
28
+
29
+ def get_create_table_sql(self) -> str:
30
+ """Generate CREATE TABLE SQL statement."""
31
+ columns = [f"{field} {field_type}" for field, field_type in self.schema.items()]
32
+ return f"""
33
+ CREATE TABLE IF NOT EXISTS {self.table_name} (
34
+ {', '.join(columns)}
35
+ )
36
+ """
37
+
38
+ def get_insert_sql(self) -> str:
39
+ """Generate INSERT SQL statement."""
40
+ placeholders = ', '.join(['?' for _ in self.field_order])
41
+ return f"""
42
+ INSERT INTO {self.table_name} ({', '.join(self.field_order)})
43
+ VALUES ({placeholders})
44
+ ON CONFLICT (id) DO NOTHING
45
+ """
46
+
47
+
48
+ def transform_value(field_name: str, value: Any, nested_fields: Set[str]) -> Any:
49
+ """
50
+ Transform a field value for database storage.
51
+
52
+ Handles nested objects, arrays, and type conversions.
53
+
54
+ Args:
55
+ field_name: Name of the field being transformed
56
+ value: The value to transform
57
+ nested_fields: Set of field names that should be stored as JSON
58
+
59
+ Returns:
60
+ Transformed value ready for database insertion
61
+ """
62
+ if value is None:
63
+ return None
64
+
65
+ # Check if this field should be stored as JSON
66
+ if field_name in nested_fields:
67
+ if isinstance(value, (dict, list)):
68
+ return json.dumps(value)
69
+ elif isinstance(value, str):
70
+ # Already a string, assume it's valid JSON or plain text
71
+ return value
72
+ else:
73
+ # Convert other types to JSON
74
+ return json.dumps(value)
75
+
76
+ # Handle non-nested complex types that shouldn't be in the data
77
+ if isinstance(value, (dict, list)):
78
+ # Warn: this field has nested data but isn't marked as nested_fields
79
+ # Store as JSON anyway to avoid data loss
80
+ return json.dumps(value)
81
+
82
+ # Return primitive types as-is
83
+ return value
schemas/person.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Schema definition for persons.
3
+
4
+ Update this file when adding new fields to the person data model.
5
+ """
6
+
7
+ from schemas.base import SchemaDefinition
8
+
9
+
10
+ # Define the person schema
11
+ PERSON_SCHEMA = SchemaDefinition(
12
+ table_name='persons',
13
+ schema={
14
+ 'id': 'VARCHAR PRIMARY KEY',
15
+ 'first_name': 'VARCHAR',
16
+ 'last_name': 'VARCHAR',
17
+ # Add new fields here as needed:
18
+ # 'middle_name': 'VARCHAR',
19
+ # 'birth_date': 'DATE',
20
+ # 'positions': 'JSON', # For nested arrays of positions
21
+ # 'addresses': 'JSON', # For nested address objects
22
+ # etc.
23
+ },
24
+ field_order=['id', 'first_name', 'last_name'],
25
+ nested_fields=set([
26
+ # Add nested field names here:
27
+ # 'positions',
28
+ # 'addresses',
29
+ # 'metadata',
30
+ ])
31
+ )
scripts/load_persons_to_db.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Load person data from TOML files into a DuckDB database.
4
+
5
+ This script scans the data/person directory for TOML files and loads them
6
+ into a local DuckDB database for duplicate detection and processing.
7
+ """
8
+
9
+ import sys
10
+ import argparse
11
+ from pathlib import Path
12
+ import tomlkit
13
+ import duckdb
14
+
15
+ # Add parent directory to path to import schemas and config
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
+
22
+
23
+ def load_toml_file(file_path: Path) -> dict:
24
+ """Load and parse a TOML file."""
25
+ with open(file_path, 'r', encoding='utf-8') as f:
26
+ return tomlkit.load(f)
27
+
28
+
29
+ def get_person_toml_files(data_dir: Path):
30
+ """Recursively find all TOML files in the person data directory (generator)."""
31
+ return data_dir.glob('**/*.toml')
32
+
33
+
34
+ def create_persons_table(conn: duckdb.DuckDBPyConnection):
35
+ """Create the persons table using the explicit schema."""
36
+ create_sql = PERSON_SCHEMA.get_create_table_sql()
37
+
38
+ print(f"Creating table '{PERSON_SCHEMA.table_name}' with {len(PERSON_SCHEMA.schema)} columns:")
39
+ print(f" Fields: {', '.join(PERSON_SCHEMA.field_order)}")
40
+
41
+ conn.execute(create_sql)
42
+
43
+
44
+ def load_persons_to_db(data_dir: Path, db_path: Path):
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
63
+ conn.execute("BEGIN TRANSACTION")
64
+
65
+ try:
66
+ for toml_file in get_person_toml_files(data_dir):
67
+ try:
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
+
76
+ # Build values list in the same order as field_order
77
+ # Apply transformation for nested/complex types
78
+ values = [
79
+ transform_value(field, person_data.get(field), PERSON_SCHEMA.nested_fields)
80
+ for field in PERSON_SCHEMA.field_order
81
+ ]
82
+
83
+ # Insert person data
84
+ conn.execute(insert_sql, values)
85
+
86
+ loaded_count += 1
87
+ processed_count += 1
88
+
89
+ # Progress indicator
90
+ if processed_count % 100 == 0:
91
+ print(f" Processed {processed_count} files...")
92
+
93
+ except Exception as e:
94
+ error_count += 1
95
+ processed_count += 1
96
+ print(f" Error loading {toml_file}: {e}")
97
+
98
+ # Commit transaction
99
+ conn.execute("COMMIT")
100
+ print(" Transaction committed")
101
+
102
+ except Exception as e:
103
+ # Rollback on error
104
+ conn.execute("ROLLBACK")
105
+ print(f" Transaction rolled back due to error: {e}")
106
+ raise
107
+
108
+ # Show summary
109
+ print(f"\n{'='*60}")
110
+ print(f"Load complete!")
111
+ print(f" Total files processed: {processed_count}")
112
+ print(f" Successfully loaded: {loaded_count}")
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
124
+ FROM persons
125
+ LIMIT 5
126
+ """).fetchall()
127
+
128
+ for row in sample:
129
+ print(f" {row[0]}: {row[1]} {row[2]}")
130
+
131
+ conn.close()
132
+ print(f"\nDatabase saved to: {db_path}")
133
+
134
+
135
+ def main():
136
+ """Main entry point."""
137
+ parser = argparse.ArgumentParser(
138
+ description='Load person data from TOML files into a DuckDB database',
139
+ formatter_class=argparse.RawDescriptionHelpFormatter,
140
+ epilog="""
141
+ Examples:
142
+ # Use default database path (databases/data.duckdb)
143
+ python scripts/load_persons_to_db.py
144
+
145
+ # Specify custom database path
146
+ python scripts/load_persons_to_db.py --db-path /path/to/custom.duckdb
147
+
148
+ # Use a different data directory
149
+ python scripts/load_persons_to_db.py --data-dir /path/to/person/data
150
+ """
151
+ )
152
+ parser.add_argument(
153
+ '--db-path',
154
+ type=Path,
155
+ default=DATABASE_PATH,
156
+ help=f'Path to the DuckDB database (default: {DATABASE_PATH})'
157
+ )
158
+ parser.add_argument(
159
+ '--data-dir',
160
+ type=Path,
161
+ default=PERSON_DATA_DIR,
162
+ help=f'Path to the person data directory (default: {PERSON_DATA_DIR})'
163
+ )
164
+
165
+ args = parser.parse_args()
166
+
167
+ # Validate data directory exists
168
+ if not args.data_dir.exists():
169
+ print(f"Error: Data directory not found: {args.data_dir}")
170
+ sys.exit(1)
171
+
172
+ # Create databases directory if it doesn't exist
173
+ args.db_path.parent.mkdir(parents=True, exist_ok=True)
174
+
175
+ load_persons_to_db(args.data_dir, args.db_path)
176
+
177
+
178
+ if __name__ == '__main__':
179
+ main()