-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrepomix-output.xml
More file actions
2055 lines (1704 loc) · 64.7 KB
/
Copy pathrepomix-output.xml
File metadata and controls
2055 lines (1704 loc) · 64.7 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
This file is a merged representation of the entire codebase, combined into a single document by Repomix.
<file_summary>
This section contains a summary of this file.
<purpose>
This file contains a packed representation of the entire repository's contents.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>
<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
- File path as an attribute
- Full contents of the file
</file_format>
<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
original repository files, not this packed version.
- When processing this file, use the file path to distinguish
between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
the same level of security as you would the original repository.
</usage_guidelines>
<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>
</file_summary>
<directory_structure>
.github/
workflows/
ci_pipeline.yml
assets/
images/
sonnet_scripts_banner.png
jupyterbase/
__init__.py
Dockerfile
jupyter_notebook_config.py
pgduckdb_connect.ipynb
requirements.txt
linuxbase/
Dockerfile
pgadmin/
pgpass
preferences.json
servers.json
pipelinebase/
db/
__init__.py
duckdb.py
minio.py
postgres.py
validation.py
etl_pipelines/
__init__.py
duckdb_to_minio.py
minio_to_duckdb.py
ingest_claims/
__init__.py
load_claims_to_db.py
schema.py
tests/
integration/
__init__.py
test_pipeline.py
unit/
__init__.py
test_db_utils.py
test_load_claims_to_db.py
__init__.py
conftest.py
__init__.py
config.py
Dockerfile
logging_config.py
requirements.txt
pythonbase/
Dockerfile
requirements.txt
sonnets/
healthcare/
medicare-claims-synthetic-public-use-files/
README.md
requirements.txt
README.md
.gitignore
docker-compose.yml
LICENSE
Makefile
pytest.ini
README.md
</directory_structure>
<files>
This section contains the contents of the repository's files.
<file path="jupyterbase/pgduckdb_connect.ipynb">
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"id": "527321f5-1ff0-416d-b990-67d27daccb73",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"hello\n"
]
}
],
"source": [
"print('hello')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "475a1233-de42-4a35-972f-33c097c1f4e6",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
</file>
<file path="jupyterbase/requirements.txt">
duckdb==1.2.2
pandas==2.2.3
jupyterlab==4.4.2
</file>
<file path="pgadmin/pgpass">
pgduckdb:5432:postgres:postgres:postgres
</file>
<file path="pgadmin/preferences.json">
{
"preferences": {
"browser:display:auto_expand_sole_children": true,
"browser:display:confirm_on_properties_close": true,
"browser:display:confirm_on_refresh_close": true,
"browser:display:browser_tree_state_save_interval": 30,
"browser:display:show_system_objects": false,
"browser:display:show_user_defined_templates": false,
"browser:node:show_node_aggregate": false,
"browser:node:show_node_cast": false,
"browser:node:show_node_catalog_object": false,
"browser:node:show_node_catalog": false,
"browser:node:show_node_check_constraint": false,
"browser:node:show_node_collation": false,
"browser:node:show_node_column": true,
"browser:node:show_node_foreign_table_column": false,
"browser:node:show_node_compound_trigger": false,
"browser:node:show_node_constraints": false,
"browser:node:show_node_dbms_job_scheduler": false,
"browser:node:show_node_dbms_job": false,
"browser:node:show_node_dbms_program": false,
"browser:node:show_node_dbms_schedule": false,
"browser:node:show_node_database": true,
"browser:node:show_node_directory": false,
"browser:node:show_node_domain_constraints": false,
"browser:node:show_node_domain": false,
"browser:node:show_node_event_trigger": false,
"browser:node:show_node_exclusion_constraint": false,
"browser:node:show_node_extension": false,
"browser:node:show_node_fts_configuration": false,
"browser:node:show_node_fts_dictionary": false,
"browser:node:show_node_fts_parser": false,
"browser:node:show_node_fts_template": false,
"browser:node:show_node_foreign_data_wrapper": false,
"browser:node:show_node_foreign_key": false,
"browser:node:show_node_foreign_server": false,
"browser:node:show_node_foreign_table": false,
"browser:node:show_node_function": false,
"browser:node:show_node_index": false,
"browser:node:show_node_language": false,
"browser:node:show_node_role": false,
"browser:node:show_node_mview": false,
"browser:node:show_node_operator": false,
"browser:node:show_node_pgd_replication_groups": false,
"browser:node:show_node_edbfunc": false,
"browser:node:show_node_edbproc": false,
"browser:node:show_node_package": false,
"browser:node:show_node_partition": false,
"browser:node:show_node_primary_key": false,
"browser:node:show_node_procedure": false,
"browser:node:show_node_publication": false,
"browser:node:show_node_row_security_policy": false,
"browser:node:show_node_replica_nodes": false,
"browser:node:show_node_resource_group": false,
"browser:node:show_node_rule": false,
"browser:node:show_node_pga_schedule": false,
"browser:node:show_node_schema": true,
"browser:node:show_node_sequence": false,
"browser:node:show_node_pgd_replication_servers": false,
"browser:node:show_node_pga_jobstep": false,
"browser:node:show_node_subscription": false,
"browser:node:show_node_synonym": false,
"browser:node:show_node_table": true,
"browser:node:show_node_tablespace": false,
"browser:node:show_node_trigger_function": false,
"browser:node:show_node_trigger": false,
"browser:node:show_node_type": false,
"browser:node:show_node_unique_constraint": false,
"browser:node:show_node_user_mapping": false,
"browser:node:show_node_edbvar": false,
"browser:node:show_node_view": true,
"browser:node:show_node_pga_job": false,
"browser:display:show_empty_coll_nodes": false,
"browser:tab_settings:new_browser_tab_open": "query_tool",
"misc:user_interface:theme": "system",
"misc:user_interface:layout": "classic"
}
}
</file>
<file path="pgadmin/servers.json">
{
"Servers": {
"1": {
"Name": "pgduckdb",
"Group": "Servers",
"Host": "pgduckdb",
"Port": 5432,
"MaintenanceDB": "postgres",
"Username": "postgres",
"PassFile": "/pgadmin4/pgpass",
"SSLMode": "prefer"
}
}
}
</file>
<file path="pipelinebase/db/__init__.py">
from db.postgres import connect_to_db, copy_csv_to_db
from db.duckdb import setup_duckdb_minio_connection
from db.minio import get_minio_client, create_bucket_if_not_exists
from db.validation import validate_identifier, validate_s3_path
__all__ = [
"connect_to_db",
"copy_csv_to_db",
"setup_duckdb_minio_connection",
"get_minio_client",
"create_bucket_if_not_exists",
"validate_identifier",
"validate_s3_path",
]
</file>
<file path="pipelinebase/db/duckdb.py">
import duckdb
import config
from logging_config import setup_logging
logger = setup_logging(__name__)
def setup_duckdb_minio_connection():
"""Configure DuckDB connection to MinIO and use persistent database."""
con = duckdb.connect(config.DUCKDB_PATH)
con.execute("INSTALL httpfs;")
con.execute("LOAD httpfs;")
con.execute(f"""
SET s3_endpoint='{config.MINIO_ENDPOINT}';
SET s3_access_key_id='{config.MINIO_ACCESS_KEY}';
SET s3_secret_access_key='{config.MINIO_SECRET_KEY}';
SET s3_use_ssl={'true' if config.MINIO_USE_SSL else 'false'};
SET s3_url_style='path';
""")
logger.debug("DuckDB MinIO connection established")
return con
</file>
<file path="pipelinebase/db/minio.py">
from minio import Minio
import config
from logging_config import setup_logging
logger = setup_logging(__name__)
def get_minio_client():
"""Get a configured MinIO client instance."""
return Minio(
endpoint=config.MINIO_ENDPOINT,
access_key=config.MINIO_ACCESS_KEY,
secret_key=config.MINIO_SECRET_KEY,
secure=config.MINIO_USE_SSL,
)
def create_bucket_if_not_exists(bucket_name):
"""Create a MinIO bucket if it doesn't already exist."""
client = get_minio_client()
if not client.bucket_exists(bucket_name):
client.make_bucket(bucket_name)
logger.info(f"Created bucket: {bucket_name}")
else:
logger.debug(f"Bucket already exists: {bucket_name}")
</file>
<file path="pipelinebase/db/postgres.py">
import psycopg2
import config
from db.validation import validate_identifier
from logging_config import setup_logging
logger = setup_logging(__name__)
def connect_to_db():
"""Connect to PostgreSQL database using configuration settings."""
try:
connection = psycopg2.connect(
dbname=config.DB_NAME,
user=config.DB_USER,
password=config.DB_PASSWORD,
host=config.DB_HOST,
port=config.DB_PORT,
)
return connection
except Exception as e:
logger.error(f"Database connection error: {e}")
return None
def copy_csv_to_db(conn, csv_file, table_name):
"""Copy CSV file data into a PostgreSQL table."""
validate_identifier(table_name, "table name")
with conn.cursor() as cur:
with open(csv_file, "r") as file:
cur.copy_expert(f"COPY {table_name} FROM STDIN WITH CSV HEADER", file)
conn.commit()
logger.info(f"Copied data from {csv_file} into the {table_name} table.")
</file>
<file path="pipelinebase/db/validation.py">
import re
def validate_identifier(name, identifier_type="identifier"):
"""
Validate that a SQL identifier (table name, column name, etc.) is safe.
Only allows alphanumeric characters and underscores.
Raises ValueError if the identifier is invalid.
"""
if not name:
raise ValueError(f"{identifier_type} cannot be empty")
if not re.match(r'^[a-zA-Z_][a-zA-Z0-9_]*$', name):
raise ValueError(
f"Invalid {identifier_type}: '{name}'. "
"Only alphanumeric characters and underscores are allowed, "
"and it must start with a letter or underscore."
)
return name
def validate_s3_path(bucket_name, file_path):
"""
Validate S3/MinIO bucket name and file path.
Bucket names: lowercase alphanumeric, hyphens, 3-63 chars
File paths: alphanumeric, underscores, hyphens, forward slashes, dots
"""
if not bucket_name:
raise ValueError("Bucket name cannot be empty")
if not re.match(r'^[a-z0-9][a-z0-9\-]{1,61}[a-z0-9]$', bucket_name):
raise ValueError(
f"Invalid bucket name: '{bucket_name}'. "
"Must be 3-63 characters, lowercase alphanumeric and hyphens only."
)
if not file_path:
raise ValueError("File path cannot be empty")
if not re.match(r'^[a-zA-Z0-9_\-./]+$', file_path):
raise ValueError(
f"Invalid file path: '{file_path}'. "
"Only alphanumeric characters, underscores, hyphens, dots, and forward slashes are allowed."
)
return bucket_name, file_path
</file>
<file path="pipelinebase/ingest_claims/schema.py">
def create_claims_table(cur):
"""Create the raw_claims table if it doesn't exist."""
ddl_statement = """
CREATE TABLE IF NOT EXISTS raw_claims (
DESYNPUF_ID TEXT,
CLM_ID TEXT,
CLM_FROM_DT TEXT,
CLM_THRU_DT TEXT,
ICD9_DG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D_4 TEXT,
LINE_ICD9_DGNS_CD_5 TEXT,
LINE_ICD9_DGNS_CD_6 TEXT,
LINE_ICD9_DGNS_CD_7 TEXT,
LINE_ICD9_DGNS_CD_8 TEXT,
LINE_ICD9_DGNS_CD_9 TEXT,
LINE_ICD9_DGNS_CD_10 TEXT,
LINE_ICD9_DGNS_CD_11 TEXT,
LINE_ICD9_DGNS_CD_12 TEXT,
LINE_ICD9_DGNS_CD_13 TEXT
);
"""
cur.execute(ddl_statement)
</file>
<file path="pipelinebase/config.py">
import os
# PostgreSQL Configuration
DB_NAME = os.getenv("DB_NAME", "postgres")
DB_USER = os.getenv("DB_USER", "postgres")
DB_PASSWORD = os.getenv("DB_PASSWORD", "postgres")
DB_HOST = os.getenv("DB_HOST", "pgduckdb")
DB_PORT = os.getenv("DB_PORT", 5432)
# MinIO Configuration
MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "minio:9000")
MINIO_ACCESS_KEY = os.getenv("MINIO_ACCESS_KEY", "admin")
MINIO_SECRET_KEY = os.getenv("MINIO_SECRET_KEY", "password")
MINIO_USE_SSL = os.getenv("MINIO_USE_SSL", "false").lower() == "true"
MINIO_DEFAULT_BUCKET = os.getenv("MINIO_DEFAULT_BUCKET", "postgres-data")
# DuckDB Configuration
DUCKDB_PATH = os.getenv("DUCKDB_PATH", "/apps/my_database.duckdb")
# Claims Data Configuration
CLAIMS_URL = os.getenv(
"CLAIMS_URL",
"http://downloads.cms.gov/files/DE1_0_2008_to_2010_Carrier_Claims_Sample_2A.zip",
)
CLAIMS_ZIP_FILE = os.getenv("CLAIMS_ZIP_FILE", "claims.zip")
CLAIMS_CSV_FILE = os.getenv("CLAIMS_CSV_FILE", "claims.csv")
CLAIMS_ORIGINAL_CSV = os.getenv(
"CLAIMS_ORIGINAL_CSV", "DE1_0_2008_to_2010_Carrier_Claims_Sample_2A.csv"
)
</file>
<file path="pipelinebase/logging_config.py">
import logging
import os
import sys
def setup_logging(name=None, level=None):
"""
Configure and return a logger instance.
Args:
name: Logger name (defaults to root logger if None)
level: Log level (defaults to INFO, can be overridden by LOG_LEVEL env var)
Returns:
Configured logger instance
"""
if level is None:
level_name = os.getenv("LOG_LEVEL", "INFO").upper()
level = getattr(logging, level_name, logging.INFO)
logger = logging.getLogger(name)
if not logger.handlers:
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(level)
return logger
</file>
<file path="pipelinebase/requirements.txt">
duckdb==1.2.2
minio==7.2.15
pandas==2.2.3
psycopg2-binary==2.9.10
pytest==8.3.5
pytest-mock==3.14.0
requests==2.32.3
ruff==0.11.9
</file>
<file path="sonnets/healthcare/medicare-claims-synthetic-public-use-files/README.md">
# Medicare Claims Synthetic Public Use Files (SynPUFs)
Source: https://www.cms.gov/data-research/statistics-trends-and-reports/medicare-claims-synthetic-public-use-files
</file>
<file path="sonnets/README.md">
</file>
<file path="pytest.ini">
[pytest]
pythonpath = pythonbase
</file>
<file path="jupyterbase/jupyter_notebook_config.py">
c = get_config()
# ServerApp settings for JupyterLab 4.x
c.ServerApp.ip = '0.0.0.0'
c.ServerApp.open_browser = False
c.ServerApp.port = 8888
c.ServerApp.allow_root = True
# Password is literally "password"
c.ServerApp.password = 'argon2:$argon2id$v=19$m=10240,t=10,p=8$gZ5o1JVUiXnSk7US+dIoeg$ogbFypNBBRxLPkr+Z36Q+w'
</file>
<file path="pipelinebase/etl_pipelines/duckdb_to_minio.py">
import config
from db.duckdb import setup_duckdb_minio_connection
from db.minio import create_bucket_if_not_exists
from logging_config import setup_logging
logger = setup_logging(__name__)
def export_csv_to_minio(con):
"""Export CSV data to MinIO as Parquet using DuckDB."""
bucket_name = config.MINIO_DEFAULT_BUCKET
create_bucket_if_not_exists(bucket_name)
con.execute(f"""
COPY (
SELECT * FROM read_csv_auto('/apps/raw_claims.csv')
) TO 's3://{bucket_name}/raw_claims.parquet' (FORMAT PARQUET);
""")
logger.info("CSV successfully converted and uploaded to MinIO.")
def main():
con = setup_duckdb_minio_connection()
export_csv_to_minio(con)
con.close()
if __name__ == "__main__":
main()
</file>
<file path="pipelinebase/etl_pipelines/minio_to_duckdb.py">
import config
from db.duckdb import setup_duckdb_minio_connection
from db.validation import validate_identifier, validate_s3_path
from logging_config import setup_logging
logger = setup_logging(__name__)
def import_minio_to_duckdb(con, bucket_name, parquet_file, duckdb_table):
"""Import Parquet data from MinIO into a DuckDB table."""
validate_s3_path(bucket_name, parquet_file)
validate_identifier(duckdb_table, "table name")
minio_url = f"s3://{bucket_name}/{parquet_file}"
con.execute(f"""
CREATE TABLE IF NOT EXISTS {duckdb_table} AS
SELECT * FROM read_parquet('{minio_url}');
""")
logger.info(f"Successfully imported '{minio_url}' into DuckDB table '{duckdb_table}'.")
def main():
con = setup_duckdb_minio_connection()
bucket_name = config.MINIO_DEFAULT_BUCKET
parquet_file = "raw_claims.parquet"
duckdb_table = "raw_claims"
import_minio_to_duckdb(con, bucket_name, parquet_file, duckdb_table)
con.close()
if __name__ == "__main__":
main()
</file>
<file path="pipelinebase/ingest_claims/load_claims_to_db.py">
import os
import requests
import zipfile
import config
from db.postgres import connect_to_db, copy_csv_to_db
from ingest_claims.schema import create_claims_table
from logging_config import setup_logging
logger = setup_logging(__name__)
def download_file(url, zip_file_name):
"""Download a file from a URL."""
response = requests.get(url, stream=True)
if response.status_code == 200:
with open(zip_file_name, "wb") as file:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
logger.info(f"{zip_file_name} downloaded successfully.")
else:
raise Exception(
f"Failed to download the file. Status code: {response.status_code}"
)
def extract_zip_file(zip_file_name, extract_to="."):
"""Extract a zip file to the specified directory."""
with zipfile.ZipFile(zip_file_name, "r") as zip_ref:
zip_ref.extractall(extract_to)
extracted_files = zip_ref.namelist()
logger.info(f"Extracted files: {zip_ref.namelist()}")
return extracted_files
def rename_csv_file(original_csv_name, csv_file_name):
"""Rename a CSV file."""
if os.path.exists(original_csv_name):
os.rename(original_csv_name, csv_file_name)
logger.info(f"Renamed {original_csv_name} to {csv_file_name}.")
else:
raise FileNotFoundError(f"{original_csv_name} not found in extracted files.")
def cleanup_files(*files):
"""Remove specified files."""
for file in files:
if os.path.exists(file):
os.remove(file)
logger.debug(f"Removed {file}.")
def main():
db = None
try:
# Download the file
download_file(config.CLAIMS_URL, config.CLAIMS_ZIP_FILE)
# Extract Zip File
extract_zip_file(config.CLAIMS_ZIP_FILE)
rename_csv_file(config.CLAIMS_ORIGINAL_CSV, config.CLAIMS_CSV_FILE)
cleanup_files(config.CLAIMS_ZIP_FILE)
# Connect to the Database
logger.info("Connecting to the database...")
db = connect_to_db()
with db.cursor() as cur:
create_claims_table(cur)
db.commit()
# Copy the dataframe to the database
logger.info("Copying data to the database...")
copy_csv_to_db(db, config.CLAIMS_CSV_FILE, "raw_claims")
logger.info("Data ingestion completed successfully.")
except Exception as e:
logger.error(f"An error occurred: {e}")
if db:
db.rollback()
finally:
logger.debug("Not removing the CSV file.")
if db:
logger.info("Closing the database connection.")
db.close()
if __name__ == "__main__":
main()
</file>
<file path="pipelinebase/tests/integration/test_pipeline.py">
import pytest
import os
from ingest_claims.load_claims_to_db import main
from db.postgres import connect_to_db
@pytest.fixture(scope="module")
def test_db():
"""Fixture to set up and tear down a real test database."""
os.environ["DB_HOST"] = "pgduckdb"
conn = connect_to_db()
yield conn
conn.close()
def test_end_to_end_pipeline(test_db):
"""Test the full ingestion pipeline."""
# Run the full pipeline
main()
# Verify that the raw_claims table contains data
with test_db.cursor() as cur:
cur.execute("SELECT COUNT(*) FROM raw_claims")
result = cur.fetchone()
assert result[0] > 0, "No data was inserted into raw_claims!"
</file>
<file path="pipelinebase/tests/unit/test_db_utils.py">
import pytest
import psycopg2
from unittest import mock
from unittest.mock import MagicMock
from db.postgres import connect_to_db
from ingest_claims.schema import create_claims_table
@pytest.fixture
def mock_cursor():
"""Fixture for a mocked database cursor."""
return MagicMock()
@pytest.fixture
def mock_conn(mock_cursor):
"""Fixture for a mocked database connection."""
mock_conn = MagicMock()
mock_conn.cursor.return_value.__enter__.return_value = mock_cursor
return mock_conn
def test_connect_to_db_success():
"""Test that connect_to_db successfully connects using a mock."""
with mock.patch("db.postgres.psycopg2.connect", return_value=MagicMock()) as mock_connect:
conn = connect_to_db()
assert conn is not None
mock_connect.assert_called_once()
def test_connect_to_db_failure():
"""Test the connect_to_db returns None if connection fails."""
with mock.patch("db.postgres.psycopg2.connect", side_effect=psycopg2.OperationalError):
conn = connect_to_db()
assert conn is None
def test_create_claims_table(mock_conn, mock_cursor):
"""Test that create_claims_table executes a SQL query."""
create_claims_table(mock_cursor)
mock_cursor.execute.assert_called_once()
assert (
"CREATE TABLE IF NOT EXISTS raw_claims" in mock_cursor.execute.call_args[0][0]
)
</file>
<file path="pipelinebase/tests/unit/test_load_claims_to_db.py">
import pytest
import os
import requests
import zipfile
from unittest import mock
from unittest.mock import MagicMock
from ingest_claims.load_claims_to_db import (
download_file,
extract_zip_file,
rename_csv_file,
cleanup_files,
)
@pytest.fixture
def temp_file(tmp_path):
"""Create a temp file for testing."""
file = tmp_path / "test_file.txt"
file.write_text("dummy content")
return file
def test_download_file_success(mocker, tmp_path):
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.iter_content = lambda chunk_size: [b"data"]
mocker.patch("ingest_claims.load_claims_to_db.requests.get", return_value=mock_response)
test_file = tmp_path / "test_download.zip"
download_file("http://example.com/file.zip", test_file)
assert os.path.exists(test_file)
def test_download_file_failure(mocker):
"""Test download failure handling."""
mock_response = MagicMock()
mock_response.status_code = 404
mocker.patch("ingest_claims.load_claims_to_db.requests.get", return_value=mock_response)
with pytest.raises(Exception, match="Failed to download the file"):
download_file("http://example.com/file.zip", "claims.zip")
def test_extract_zip_file(mocker, tmp_path):
"""Test zip extraction."""
mock_zip = MagicMock()
mock_zip.__enter__.return_value.namelist.return_value = ["test.csv"]
mock_zip.__enter__.return_value.extractall = MagicMock() # ✅ Add this!
mocker.patch("ingest_claims.load_claims_to_db.zipfile.ZipFile", return_value=mock_zip)
extracted_files = extract_zip_file("claims.zip", tmp_path)
assert extracted_files == ["test.csv"]
mock_zip.__enter__.return_value.extractall.assert_called_once_with(tmp_path)
def test_rename_csv_file_success(tmp_path):
"""Test renaming an existing CSV file."""
original = tmp_path / "priginal.csv"
renamed = tmp_path / "renamed.csv"
original.write_text("test data")
rename_csv_file(original, renamed)