phantomas34 commited on
Commit
fe8a793
·
1 Parent(s): ec35b32

feat: complete IMS migration — all 24 files in PostgreSQL including ACE14 via UTM/VBA export

Browse files
Files changed (1) hide show
  1. load_ims_p_csvs.py +134 -0
load_ims_p_csvs.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ load_ims_p_csvs.py
3
+ ──────────────────────────────────────────────────────────────────────────────
4
+ Loads all CSV files exported from ims_be_p.accdb into PostgreSQL.
5
+ Tables are prefixed with 'p_' to identify their source.
6
+
7
+ Usage:
8
+ python load_ims_p_csvs.py
9
+
10
+ Configuration: edit DB_* and CSV_DIR below if needed.
11
+ ──────────────────────────────────────────────────────────────────────────────
12
+ """
13
+
14
+ import os
15
+ import sys
16
+ import re
17
+ import pandas as pd
18
+ from pathlib import Path
19
+ from sqlalchemy import create_engine, text
20
+
21
+ # ── CONFIGURATION ─────────────────────────────────────────────────────────────
22
+ DB_HOST = "localhost"
23
+ DB_PORT = 5433
24
+ DB_NAME = "sales_db"
25
+ DB_USER = os.popen("whoami").read().strip()
26
+ DB_PASS = ""
27
+ CSV_DIR = Path.home() / "Desktop" / "ims_p_csvs"
28
+
29
+ # ── HELPERS ───────────────────────────────────────────────────────────────────
30
+
31
+ def clean_table_name(filename: str) -> str:
32
+ """Convert CSV filename to a clean PostgreSQL table name with p_ prefix."""
33
+ name = Path(filename).stem
34
+ name = re.sub(r"[^a-zA-Z0-9]", "_", name).lower()
35
+ name = re.sub(r"_+", "_", name).strip("_")
36
+ return f"p_{name}"
37
+
38
+
39
+ def infer_dtype(series: pd.Series) -> str:
40
+ """Infer a basic PostgreSQL type from a pandas Series."""
41
+ if pd.api.types.is_integer_dtype(series):
42
+ return "BIGINT"
43
+ elif pd.api.types.is_float_dtype(series):
44
+ return "DOUBLE PRECISION"
45
+ else:
46
+ return "TEXT"
47
+
48
+
49
+ # ── MAIN ─────────────────────────────────────────────────────────────────────
50
+
51
+ def main():
52
+ print("\n" + "═" * 60)
53
+ print(" IMS-P CSV Loader → PostgreSQL")
54
+ print("═" * 60)
55
+
56
+ # Connect
57
+ print(f"\n[1/3] Connecting to {DB_NAME} on port {DB_PORT}...")
58
+ engine = create_engine(
59
+ f"postgresql+psycopg2://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
60
+ )
61
+ try:
62
+ with engine.connect() as conn:
63
+ conn.execute(text("SELECT 1"))
64
+ print(" ✓ Connected")
65
+ except Exception as e:
66
+ print(f" ✗ Connection failed: {e}")
67
+ sys.exit(1)
68
+
69
+ # Find CSV files
70
+ print(f"\n[2/3] Scanning {CSV_DIR}...")
71
+ csv_files = sorted(CSV_DIR.glob("*.csv"))
72
+ if not csv_files:
73
+ print(f" ✗ No CSV files found in {CSV_DIR}")
74
+ sys.exit(1)
75
+ print(f" Found {len(csv_files)} CSV files")
76
+
77
+ # Load each CSV
78
+ print(f"\n[3/3] Loading tables...")
79
+ success = 0
80
+ failed = 0
81
+ total_rows = 0
82
+
83
+ for csv_path in csv_files:
84
+ table_name = clean_table_name(csv_path.name)
85
+ try:
86
+ df = pd.read_csv(
87
+ csv_path,
88
+ encoding = "latin-1",
89
+ low_memory = False,
90
+ on_bad_lines = "skip"
91
+ )
92
+
93
+ if df.empty:
94
+ print(f" → {table_name:<45} 0 rows (empty, skipped)")
95
+ continue
96
+
97
+ # Clean column names
98
+ df.columns = [
99
+ re.sub(r"[^a-zA-Z0-9]", "_", c).lower().strip("_")
100
+ for c in df.columns
101
+ ]
102
+ df.columns = [re.sub(r"_+", "_", c) for c in df.columns]
103
+
104
+ # Write to PostgreSQL
105
+ df.to_sql(
106
+ table_name,
107
+ engine,
108
+ if_exists = "replace",
109
+ index = False,
110
+ method = "multi",
111
+ chunksize = 500
112
+ )
113
+
114
+ total_rows += len(df)
115
+ success += 1
116
+ print(f" → {table_name:<45} {len(df):>6,} rows ✓")
117
+
118
+ except Exception as e:
119
+ failed += 1
120
+ print(f" → {table_name:<45} FAILED: {e}")
121
+
122
+ # Summary
123
+ print(f"\n{'═' * 60}")
124
+ print(f" LOAD COMPLETE")
125
+ print(f"{'═' * 60}")
126
+ print(f" Tables loaded: {success}")
127
+ print(f" Tables failed: {failed}")
128
+ print(f" Total rows: {total_rows:,}")
129
+ print(f"\n All p_* tables are now in sales_db.")
130
+ print(f" Run the Phase 2 query in pgAdmin next.\n")
131
+
132
+
133
+ if __name__ == "__main__":
134
+ main()