-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccess2sql.py
More file actions
executable file
·1547 lines (1319 loc) · 56.8 KB
/
access2sql.py
File metadata and controls
executable file
·1547 lines (1319 loc) · 56.8 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
"""
access2sql.py
---------------------------
Use a system folder-picker dialog to choose a root folder, then recursively
find every .accdb / .mdb file, extract all tables + data, and produce:
- <db_name>.sql : CREATE TABLE + INSERT statements (SQLite-compatible)
Type mapping from Access → SQLite:
Text / Memo / Hyperlink → TEXT COLLATE NOCASE
Date/Time → DATETIME
Yes/No (Boolean) → BOOLEAN (0/1)
AutoNumber / Long Integer → INTEGER
Integer / Number → INTEGER
Single / Double / Decimal → REAL
Currency → CURRENCY (treated as REAL)
OLE Object / Binary → BLOB
everything else → TEXT COLLATE NOCASE
Requirements (install once):
pip install pyodbc # on macOS needs mdbtools (brew install mdbtools)
-- OR --
pip install pywin32 # Windows only (uses COM / DAO)
This script auto-detects the platform and picks the right backend.
On macOS it falls back to the `mdbtools` CLI utilities (mdb-tables, mdb-export,
mdb-schema) if pyodbc is unavailable.
"""
import os
import sys
import platform
import subprocess
import re
import shutil
import unicodedata
import tkinter as tk
from tkinter import filedialog
from datetime import datetime
from pathlib import Path
from typing import Any
HELP_TEXT = """Notes:
- Opens a folder picker and scans recursively for .accdb/.mdb files.
- Exports tables/data to SQLite-compatible .sql files.
- Exports saved Access queries to <db_name>_queries.txt files.
- If an output file already exists, a numeric suffix is added.
Requirements:
- pyodbc on Windows, or mdbtools on macOS/Linux.
- mdbtools should include: mdb-tables, mdb-export, mdb-schema, mdb-queries.
"""
# ══════════════════════════════════════════════════════════════════════════════
# Platform detection
# ══════════════════════════════════════════════════════════════════════════════
IS_WINDOWS = platform.system() == "Windows"
IS_MAC = platform.system() == "Darwin"
LAST_FOLDER_FILE = Path.home() / ".access2sql.conf"
# ══════════════════════════════════════════════════════════════════════════════
# Folder chooser (native dialog)
# ══════════════════════════════════════════════════════════════════════════════
def _load_last_folder() -> str | None:
try:
p = LAST_FOLDER_FILE.read_text(encoding="utf-8").strip()
except OSError:
return None
if p and Path(p).is_dir():
return p
return None
def _save_last_folder(folder: str) -> None:
try:
LAST_FOLDER_FILE.write_text(folder, encoding="utf-8")
except OSError:
# Non-fatal: extraction should continue even if preference cannot be saved.
pass
def pick_folder() -> Path:
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
last_folder = _load_last_folder()
kwargs = {"title": "Select root folder containing Access databases"}
if last_folder:
kwargs["initialdir"] = last_folder
folder = filedialog.askdirectory(**kwargs)
root.destroy()
if not folder:
print("No folder selected. Exiting.")
print()
print(HELP_TEXT)
sys.exit(0)
_save_last_folder(folder)
return Path(folder)
# ══════════════════════════════════════════════════════════════════════════════
# Find all Access databases recursively
# ══════════════════════════════════════════════════════════════════════════════
def find_access_files(root: Path) -> list[Path]:
files = []
for pattern in ("**/*.accdb", "**/*.mdb"):
files.extend(root.glob(pattern))
return sorted(set(files))
def unique_output_path(path: Path) -> Path:
"""Return a non-existing path by appending _1, _2, ... if needed."""
if not path.exists():
return path
stem = path.stem
suffix = path.suffix
parent = path.parent
i = 1
while True:
candidate = parent / f"{stem}_{i}{suffix}"
if not candidate.exists():
return candidate
i += 1
def order_columns_with_primary_key_first(col_names: list[str], primary_key: list[str]) -> list[str]:
"""Keep source column order, but move primary key columns to the front."""
primary_key_set = set(primary_key)
ordered = [name for name in primary_key if name in col_names]
ordered.extend(name for name in col_names if name not in primary_key_set)
return ordered
# ══════════════════════════════════════════════════════════════════════════════
# Type mapping helpers
# ══════════════════════════════════════════════════════════════════════════════
# Map Access type names (lowercase) → SQL column type declaration
_TYPE_MAP = {
# Text-like
"text": "TEXT COLLATE NOCASE",
"memo": "TEXT COLLATE NOCASE",
"hyperlink": "TEXT COLLATE NOCASE",
# Numeric
"autonumber": "INTEGER",
"long integer":"INTEGER",
"integer": "INTEGER",
"int": "INTEGER",
"smallint": "INTEGER",
"bigint": "INTEGER",
"tinyint": "INTEGER",
"byte": "INTEGER",
"number": "INTEGER",
"single": "REAL",
"double": "REAL",
"float": "REAL",
"currency": "CURRENCY",
"money": "CURRENCY",
"decimal": "REAL",
"numeric": "REAL",
# Date
"date/time": "DATETIME",
"datetime": "DATETIME",
# Boolean
"yes/no": "BOOLEAN",
"boolean": "BOOLEAN",
"bit": "BOOLEAN",
# Binary
"ole object": "BLOB",
"binary": "BLOB",
"varbinary": "BLOB",
}
def access_type_to_sqlite(access_type: str) -> str:
key = access_type.lower().strip()
key = key.split("(", 1)[0].strip()
key = re.sub(r"\s+(not\s+null|null)$", "", key).strip()
return _TYPE_MAP.get(key, "TEXT COLLATE NOCASE")
# ══════════════════════════════════════════════════════════════════════════════
# Value formatting for INSERT statements
# ══════════════════════════════════════════════════════════════════════════════
def format_value(value, sqlite_type: str) -> str:
"""Return a SQL literal for the value."""
if value is None:
return "NULL"
st = sqlite_type.upper()
if "INTEGER" in st or "BOOLEAN" in st:
# Boolean: Access stores as -1 (True) / 0 (False)
if isinstance(value, bool):
return "1" if value else "0"
try:
v = int(value)
return "1" if v == -1 else str(v) # -1 → True in Access
except (ValueError, TypeError):
return "NULL"
# Treat CURRENCY as REAL for value formatting.
if "REAL" in st or "CURRENCY" in st:
try:
return repr(float(value))
except (ValueError, TypeError):
return "NULL"
if "BLOB" in st:
if isinstance(value, (bytes, bytearray)):
return f"X'{value.hex()}'"
return "NULL"
# TEXT / DATETIME
if "DATETIME" in st:
mode = "datetime"
if isinstance(value, dict):
# Defensive fallback for accidental dict payloads
escaped = str(value).replace("'", "''")
return f"'{escaped}'"
return format_datetime_value(value, mode)
if isinstance(value, datetime):
return f"'{value.strftime('%Y-%m-%d %H:%M:%S')}'"
if hasattr(value, "isoformat"): # date / time objects
return f"'{value.isoformat()}'"
# Escape single quotes
escaped = str(value).replace("'", "''")
return f"'{escaped}'"
# ══════════════════════════════════════════════════════════════════════════════
# Backend: pyodbc (Windows / macOS with mdbtools ODBC driver)
# ══════════════════════════════════════════════════════════════════════════════
def try_pyodbc(accdb: Path):
"""Return (columns_info_per_table, rows_per_table) or raise ImportError."""
import pyodbc # noqa: F401 – imported to verify availability
if IS_WINDOWS:
conn_str = (
r"Driver={Microsoft Access Driver (*.mdb, *.accdb)};"
f"Dbq={accdb};"
)
else:
# macOS/Linux with mdbtools ODBC
conn_str = f"Driver={{MDBTools}};Dbq={accdb};"
conn = pyodbc.connect(conn_str, autocommit=True)
cursor = conn.cursor()
tables = [row.table_name for row in cursor.tables(tableType="TABLE")]
schema: dict[str, dict[str, object]] = {}
data: dict[str, list[list]] = {}
for table in tables:
cols_info = []
primary_key: list[str] = []
foreign_keys: list[dict[str, object]] = []
nullable_by_name: dict[str, bool] = {}
try:
for row in cursor.columns(table=table):
column_name = getattr(row, "column_name", None)
nullable = getattr(row, "nullable", None)
if column_name is not None and nullable is not None:
nullable_by_name[column_name] = bool(nullable)
except Exception:
nullable_by_name = {}
cursor.execute(f"SELECT * FROM [{table}] WHERE 1=0")
for col in cursor.description:
name = col[0]
type_code = col[1]
# Map pyodbc type_code to Access-like name
import pyodbc as _p
if type_code == _p.SQL_TYPE_DATE or type_code == _p.SQL_TYPE_TIMESTAMP:
atype = "date/time"
elif type_code in (_p.SQL_SMALLINT, _p.SQL_INTEGER, _p.SQL_BIGINT, _p.SQL_TINYINT):
atype = "integer"
elif type_code in (_p.SQL_FLOAT, _p.SQL_REAL, _p.SQL_DOUBLE, _p.SQL_NUMERIC, _p.SQL_DECIMAL):
atype = "double"
elif type_code == _p.SQL_BIT:
atype = "yes/no"
elif type_code in (_p.SQL_BINARY, _p.SQL_VARBINARY, _p.SQL_LONGVARBINARY):
atype = "ole object"
else:
atype = "text"
cols_info.append({
"name": name,
"access_type": atype,
"sqlite_type": access_type_to_sqlite(atype),
"not_null": not nullable_by_name.get(name, True),
"datetime_mode": "auto" if "DATETIME" in access_type_to_sqlite(atype).upper() else None,
"datetime_include_seconds": None if "DATETIME" in access_type_to_sqlite(atype).upper() else None,
})
try:
pk_rows = sorted(
cursor.primaryKeys(table=table),
key=lambda row: getattr(row, "key_seq", 0),
)
primary_key = [row.column_name for row in pk_rows if getattr(row, "column_name", None)]
except Exception:
primary_key = []
primary_key_set = set(primary_key)
for col in cols_info:
if col["name"] in primary_key_set:
col["not_null"] = True
try:
fk_groups: dict[object, list] = {}
for row in cursor.foreignKeys(table=table):
key = getattr(row, "fk_name", None) or (
getattr(row, "pktable_name", None),
getattr(row, "fktable_name", None),
)
fk_groups.setdefault(key, []).append(row)
for rows in fk_groups.values():
rows = sorted(rows, key=lambda row: getattr(row, "key_seq", 0))
fk_columns = [row.fkcolumn_name for row in rows if getattr(row, "fkcolumn_name", None)]
ref_columns = [row.pkcolumn_name for row in rows if getattr(row, "pkcolumn_name", None)]
ref_table = getattr(rows[0], "pktable_name", None)
if fk_columns and ref_columns and ref_table:
on_update = _odbc_rule_to_action(getattr(rows[0], "update_rule", None))
on_delete = _odbc_rule_to_action(getattr(rows[0], "delete_rule", None))
foreign_keys.append({
"columns": fk_columns,
"ref_table": ref_table,
"ref_columns": ref_columns,
"on_update": on_update,
"on_delete": on_delete,
})
except Exception:
foreign_keys = []
schema[table] = {
"columns": cols_info,
"primary_key": primary_key,
"foreign_keys": foreign_keys,
}
cursor.execute(f"SELECT * FROM [{table}]")
data[table] = [list(row) for row in cursor.fetchall()]
infer_datetime_modes(schema, data)
conn.close()
return schema, data
# ══════════════════════════════════════════════════════════════════════════════
# Backend: mdbtools CLI (macOS / Linux)
# ══════════════════════════════════════════════════════════════════════════════
def _run(cmd: list[str], check=True) -> str:
result = subprocess.run(cmd, capture_output=True, text=True,
encoding="utf-8", errors="replace")
if check and result.returncode != 0:
raise RuntimeError(f"Command {cmd} failed:\n{result.stderr}")
return result.stdout
def _mdbtools_available() -> bool:
return subprocess.run(["which", "mdb-tables"], capture_output=True).returncode == 0
def _mdb_queries_available() -> bool:
return shutil.which("mdb-queries") is not None
def _mdb_sql_available() -> bool:
return shutil.which("mdb-sql") is not None
def _run_mdb_sql(accdb: Path, sql: str) -> str:
"""Run a SQL statement against an Access DB via mdb-sql and return raw output."""
if not _mdb_sql_available():
return ""
result = subprocess.run(
["mdb-sql", "-P", "-H", "-F", "-d", "|", str(accdb)],
input=sql + "\nquit\n",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
if result.returncode != 0:
return ""
return result.stdout.strip()
def _lookup_query_object_id(accdb: Path, query_name: str) -> int | None:
"""Return object id in MSysObjects for a saved query name."""
escaped = query_name.replace("'", "''")
out = _run_mdb_sql(accdb, f"select Id from MSysObjects where Name='{escaped}';")
if not out:
return None
first = out.splitlines()[0].strip()
try:
return int(first)
except ValueError:
return None
def _load_msysquery_rows(accdb: Path, object_id: int) -> list[dict[str, str]]:
"""Load compact MSysQueries rows for one object id."""
out = _run_mdb_sql(
accdb,
(
"select Attribute,Flag,Name1,Name2,Expression "
f"from MSysQueries where ObjectId={object_id};"
),
)
rows: list[dict[str, str]] = []
if not out:
return rows
for line in out.splitlines():
parts = line.split("|", 4)
if len(parts) < 5:
# Some Expression values are multiline; mdb-sql emits continuation
# lines without delimiters. Attach them to previous row expression.
if rows and line.strip():
rows[-1]["expression"] = (rows[-1]["expression"] + "\n" + line.rstrip()).strip()
continue
rows.append({
"attribute": parts[0].strip(),
"flag": parts[1].strip(),
"name1": parts[2].strip(),
"name2": parts[3].strip(),
"expression": parts[4].strip(),
})
return rows
def _normalize_sql_expr(expr: str) -> str:
"""Normalize SQL expression for loose matching (case-insensitive, no spaces)."""
return re.sub(r"\s+", "", (expr or "").strip()).casefold()
def _split_sql_projection_list(text: str) -> list[str]:
"""Split a SELECT projection list by commas outside parentheses/quotes."""
items: list[str] = []
current: list[str] = []
depth = 0
in_single = False
i = 0
while i < len(text):
ch = text[i]
if ch == "'":
in_single = not in_single
current.append(ch)
i += 1
continue
if not in_single:
if ch == "(":
depth += 1
elif ch == ")" and depth > 0:
depth -= 1
elif ch == "," and depth == 0:
items.append("".join(current).strip())
current = []
i += 1
continue
current.append(ch)
i += 1
tail = "".join(current).strip()
if tail:
items.append(tail)
return items
def _lookup_select_aliases(accdb: Path, query_name: str) -> dict[str, str]:
"""Return mapping expression -> alias for SELECT projection metadata."""
object_id = _lookup_query_object_id(accdb, query_name)
if object_id is None:
return {}
rows = _load_msysquery_rows(accdb, object_id)
aliases: dict[str, str] = {}
for row in rows:
if row.get("attribute") != "6":
continue
expr = (row.get("expression") or "").strip()
alias = (row.get("name1") or "").strip()
if expr and alias:
aliases[_normalize_sql_expr(expr)] = alias
return aliases
def _apply_select_aliases_from_metadata(sql: str, aliases: dict[str, str]) -> str:
"""Inject AS aliases into SELECT projection list when missing."""
if not aliases:
return sql
m = re.search(r"(?is)^\s*SELECT\s+(.*?)\s+FROM\b", sql)
if not m:
return sql
projection = m.group(1)
fields = _split_sql_projection_list(projection)
if not fields:
return sql
rewritten: list[str] = []
changed = False
for field in fields:
norm = _normalize_sql_expr(field)
alias = aliases.get(norm)
if alias and not re.search(r"\bAS\b", field, flags=re.IGNORECASE):
rewritten.append(f"{field} AS {alias}")
changed = True
else:
rewritten.append(field)
if not changed:
return sql
new_projection = ", ".join(rewritten)
return sql[:m.start(1)] + new_projection + sql[m.end(1):]
def _reconstruct_action_query_sql(accdb: Path, query_name: str) -> str | None:
"""Reconstruct UPDATE/DELETE/INSERT query text from MSysQueries metadata."""
object_id = _lookup_query_object_id(accdb, query_name)
if object_id is None:
return None
rows = _load_msysquery_rows(accdb, object_id)
if not rows:
return None
op_row = next((r for r in rows if r["attribute"] == "1"), None)
if not op_row:
return None
try:
op_flag = int(op_row["flag"])
except ValueError:
return None
table_row = next((r for r in rows if r["attribute"] == "5" and r["name1"]), None)
where_row = next((r for r in rows if r["attribute"] == "8" and r["expression"]), None)
where_clause = where_row["expression"] if where_row else ""
# Access action query flags in MSysQueries.Attribute=1 rows:
# 3=INSERT, 4=UPDATE, 5=DELETE
if op_flag == 4:
table = table_row["name1"] if table_row else op_row["name1"]
if not table:
return None
set_rows = [r for r in rows if r["attribute"] == "6" and r["name2"]]
if not set_rows:
return None
assignments = [f"[{r['name2']}] = {r['expression'] or 'NULL'}" for r in set_rows]
sql = f"UPDATE [{table}] SET " + ", ".join(assignments)
if where_clause:
sql += f" WHERE {where_clause}"
return sql
if op_flag == 5:
table = table_row["name1"] if table_row else op_row["name1"]
if not table:
return None
sql = f"DELETE FROM [{table}]"
if where_clause:
sql += f" WHERE {where_clause}"
return sql
if op_flag == 3:
table = op_row["name1"] or (table_row["name1"] if table_row else "")
if not table:
return None
value_rows = [r for r in rows if r["attribute"] == "6"]
if not value_rows:
return None
columns = [r["name2"] for r in value_rows if r["name2"]]
values = [r["expression"] or "NULL" for r in value_rows]
if columns and len(columns) == len(values):
cols_sql = ", ".join(f"[{c}]" for c in columns)
return f"INSERT INTO [{table}] ({cols_sql}) VALUES (" + ", ".join(values) + ")"
return f"INSERT INTO [{table}] VALUES (" + ", ".join(values) + ")"
return None
def _format_alias_for_access(alias: str) -> str:
"""Return alias token using Access-style brackets when needed."""
a = (alias or "").strip()
if not a:
return a
if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", a):
return a
return f"[{a}]"
def _reconstruct_select_query_sql(accdb: Path, query_name: str) -> str | None:
"""Reconstruct SELECT query text (incl. GROUP BY/HAVING) from MSysQueries."""
object_id = _lookup_query_object_id(accdb, query_name)
if object_id is None:
return None
rows = _load_msysquery_rows(accdb, object_id)
if not rows:
return None
# If query is an action query, let action reconstruction handle it.
op_row = next((r for r in rows if r["attribute"] == "1"), None)
if op_row:
try:
if int(op_row.get("flag") or "0") in {3, 4, 5}:
return None
except ValueError:
pass
select_rows = [r for r in rows if r["attribute"] == "6" and r["expression"]]
from_rows = [r for r in rows if r["attribute"] == "5" and r["name1"]]
if not select_rows or not from_rows:
return None
projections: list[str] = []
for row in select_rows:
expr = row["expression"].strip()
alias = (row.get("name1") or "").strip()
if alias and _normalize_sql_expr(alias) != _normalize_sql_expr(expr):
projections.append(f"{expr} AS {_format_alias_for_access(alias)}")
else:
projections.append(expr)
tables = [row["name1"].strip() for row in from_rows if row["name1"].strip()]
where_clause = next((r["expression"].strip() for r in rows if r["attribute"] == "8" and r["expression"].strip()), "")
group_by_parts = [r["expression"].strip() for r in rows if r["attribute"] == "9" and r["expression"].strip()]
having_parts = [r["expression"].strip() for r in rows if r["attribute"] == "10" and r["expression"].strip()]
sql = "SELECT " + ", ".join(projections)
sql += " FROM " + ", ".join(tables)
if where_clause:
sql += " WHERE " + where_clause
if group_by_parts:
sql += " GROUP BY " + ", ".join(group_by_parts)
if having_parts:
sql += " HAVING " + " AND ".join(having_parts)
sql += ";"
return sql
def _format_query_for_display(sql: str) -> str:
"""Format query text to look closer to Access SQL view."""
s = (sql or "").strip()
if not s:
return s
# Keep brackets for multi-word names/aliases; remove for simple identifiers.
def _maybe_unbracket(match: re.Match[str]) -> str:
token = match.group(1)
if re.search(r"\s", token):
return f"[{token}]"
if re.fullmatch(r"[A-Za-z_À-ÖØ-öø-ÿ][A-Za-z0-9_À-ÖØ-öø-ÿ]*(\.[A-Za-z_À-ÖØ-öø-ÿ][A-Za-z0-9_À-ÖØ-öø-ÿ]*)*", token):
return token
return f"[{token}]"
s = re.sub(r"\[([^\[\]]+)\]", _maybe_unbracket, s)
upper = s.upper()
if upper.startswith("UPDATE "):
s = re.sub(r"\s+SET\s+", "\nSET\n ", s, flags=re.IGNORECASE)
s = re.sub(r",\s*", ",\n ", s)
s = re.sub(r"\s+WHERE\s+", "\nWHERE ", s, flags=re.IGNORECASE)
return s
if upper.startswith("DELETE FROM "):
s = re.sub(r"\s+WHERE\s+", "\nWHERE ", s, flags=re.IGNORECASE)
return s
if upper.startswith("INSERT INTO "):
s = re.sub(r"\s+VALUES\s*\(", "\nVALUES (\n ", s, flags=re.IGNORECASE)
s = re.sub(r",\s*", ",\n ", s)
if s.endswith(")"):
s = s[:-1] + "\n)"
return s
# SELECT and other query types.
for pattern, repl in (
(r"\s+FROM\s+", "\nFROM "),
(r"\s+WHERE\s+", "\nWHERE "),
(r"\s+GROUP\s+BY\s+", "\nGROUP BY "),
(r"\s+HAVING\s+", "\nHAVING "),
(r"\s+ORDER\s+BY\s+", "\nORDER BY "),
(r"\s+INNER\s+JOIN\s+", "\nINNER JOIN "),
(r"\s+LEFT\s+JOIN\s+", "\nLEFT JOIN "),
(r"\s+RIGHT\s+JOIN\s+", "\nRIGHT JOIN "),
(r"\s+FULL\s+JOIN\s+", "\nFULL JOIN "),
(r"\s+AND\s+", "\n AND "),
(r"\s+OR\s+", "\n OR "),
):
s = re.sub(pattern, repl, s, flags=re.IGNORECASE)
return s
def list_saved_queries(accdb: Path) -> list[str]:
"""Return saved query names for a database using mdbtools."""
result = subprocess.run(
["mdb-queries", "-L", "-1", str(accdb)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or "Failed to list saved queries")
return [line.strip() for line in result.stdout.splitlines() if line.strip()]
def get_saved_query_sql(accdb: Path, query_name: str) -> str:
"""Return SQL text for one saved query using mdbtools."""
reconstructed = _reconstruct_action_query_sql(accdb, query_name)
if reconstructed:
return _format_query_for_display(reconstructed)
reconstructed_select = _reconstruct_select_query_sql(accdb, query_name)
if reconstructed_select:
return _format_query_for_display(reconstructed_select)
result = subprocess.run(
["mdb-queries", str(accdb), query_name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
check=False,
)
if result.returncode != 0:
raise RuntimeError(result.stderr.strip() or f"Failed to extract query '{query_name}'")
sql = result.stdout.strip()
sql = _apply_select_aliases_from_metadata(sql, _lookup_select_aliases(accdb, query_name))
return _format_query_for_display(sql)
def export_queries(accdb: Path) -> Path:
"""Extract all saved queries and write them into a single text file."""
output_path = unique_output_path(accdb.with_name(f"{accdb.stem}_queries.txt"))
query_names = list_saved_queries(accdb)
lines: list[str] = [
f"Source database: {accdb}",
"",
]
if not query_names:
lines.append("No saved queries found.")
else:
for query_name in query_names:
lines.append("=" * 60)
lines.append(f"QUERY NAME: {query_name}")
lines.append("-" * 60)
try:
sql = get_saved_query_sql(accdb, query_name)
lines.append(sql if sql else "(Empty SQL text)")
except Exception as exc:
lines.append(f"ERROR extracting query: {exc}")
lines.append("")
output_path.write_text("\n".join(lines), encoding="utf-8")
return output_path
# mdbtools schema type string patterns
_MDB_SCHEMA_TYPE_RE = re.compile(
r"^\s*`?(\w+)`?\s+([\w /]+?)(?:\s*\([^)]*\))?\s*(?:NOT NULL|NULL|,|$)",
re.IGNORECASE,
)
def _parse_mdb_schema_type(col_line: str) -> str:
"""Extract Access column type from a mdb-schema DDL line."""
# mdb-schema output looks like: `ColumnName` Text (255),
# or: `DateField` DateTime,
m = re.match(r"\s*`?[^`\s]+`?\s+([\w /]+)", col_line)
if m:
return m.group(1).strip()
return "text"
def try_mdbtools(accdb: Path):
"""Extract schema + data using mdbtools CLI utilities."""
db = str(accdb)
# List tables
raw_tables = _run(["mdb-tables", "-1", db])
tables = [t.strip() for t in raw_tables.splitlines() if t.strip()]
# Get DDL for type info
ddl = _run(["mdb-schema", db, "mysql"]) # mysql dialect closest to SQL
schema: dict[str, dict[str, object]] = {}
data: dict[str, list[list]] = {}
# Parse DDL to extract column types per table.
# Depending on the selected dialect, mdb-schema may emit primary keys either
# inline inside CREATE TABLE or later as ALTER TABLE ... ADD PRIMARY KEY.
table_ddl_re = re.compile(
r"CREATE\s+TABLE\s+`?([^`\s(]+)`?\s*\((.+?)\);",
re.IGNORECASE | re.DOTALL,
)
alter_pk_re = re.compile(
r"ALTER\s+TABLE\s+`?([^`\s(]+)`?\s+ADD\s+PRIMARY\s+KEY\s*\((.+?)\);",
re.IGNORECASE,
)
ddl_types: dict[str, dict[str, str]] = {}
ddl_column_order: dict[str, list[str]] = {}
ddl_primary_keys: dict[str, list[str]] = {}
ddl_foreign_keys: dict[str, list[dict[str, object]]] = {}
alter_fk_re = re.compile(
r"ALTER\s+TABLE\s+`?([^`\s(]+)`?\s+ADD\s+CONSTRAINT\s+`?([^`\s]+)`?\s+"
r"FOREIGN\s+KEY\s*\((.+?)\)\s+REFERENCES\s+`?([^`\s(]+)`?\s*\((.+?)\)\s*(.*?);",
re.IGNORECASE,
)
for m in table_ddl_re.finditer(ddl):
tname = m.group(1)
body = m.group(2)
col_types: dict[str, str] = {}
col_order: list[str] = []
col_not_null: dict[str, bool] = {}
primary_key: list[str] = []
for line in body.splitlines():
line = line.strip().rstrip(",")
if not line:
continue
normalized_line = line.lstrip(", ")
upper_line = normalized_line.upper()
if upper_line.startswith("PRIMARY KEY"):
pk_match = re.search(r"\((.+)\)", normalized_line)
if pk_match:
primary_key = [part.strip().strip("`").strip('"') for part in pk_match.group(1).split(",")]
continue
if upper_line.startswith(("UNIQUE", "INDEX", "KEY")):
continue
cm = re.match(r"`?([^`\s]+)`?\s+([\w /]+)", normalized_line)
if cm:
cname = cm.group(1)
ctype = cm.group(2).strip()
col_order.append(cname)
col_types[cname] = ctype
col_not_null[cname] = "NOT NULL" in upper_line
ddl_types[tname] = col_types
ddl_column_order[tname] = col_order
ddl_not_null = ddl_foreign_keys.setdefault("__not_null__", {})
ddl_not_null[tname] = col_not_null
ddl_primary_keys[tname] = primary_key
ddl_foreign_keys.setdefault(tname, [])
for m in alter_pk_re.finditer(ddl):
tname = m.group(1)
ddl_primary_keys[tname] = [
part.strip().strip("`").strip('"')
for part in m.group(2).split(",")
]
for m in alter_fk_re.finditer(ddl):
tname = m.group(1)
fk_columns = [part.strip().strip("`").strip('"') for part in m.group(3).split(",")]
ref_table = m.group(4).strip().strip("`").strip('"')
ref_columns = [part.strip().strip("`").strip('"') for part in m.group(5).split(",")]
tail = m.group(6) or ""
on_update = _parse_fk_action_from_tail(tail, "update")
on_delete = _parse_fk_action_from_tail(tail, "delete")
ddl_foreign_keys.setdefault(tname, []).append({
"columns": fk_columns,
"ref_table": ref_table,
"ref_columns": ref_columns,
"on_update": on_update,
"on_delete": on_delete,
})
merged_foreign_keys = merge_foreign_keys(ddl_foreign_keys, read_msys_relationships(accdb))
for table in tables:
datetime_mode_map = read_datetime_modes_from_mdb_prop(accdb, table)
currency_columns = read_currency_columns_from_mdb_prop(accdb, table)
# Export data as CSV
csv_out = _run(["mdb-export", "-H", db, table], check=False)
# With -H (no header), first run without -H to get header
csv_hdr = _run(["mdb-export", db, table], check=False)
header_line = csv_hdr.splitlines()[0] if csv_hdr.strip() else ""
exported_col_names = _parse_csv_line(header_line) if header_line else []
schema_col_names = ddl_column_order.get(table, []) or exported_col_names
if schema_col_names:
col_names = [name for name in schema_col_names if name in exported_col_names]
col_names.extend(name for name in exported_col_names if name not in schema_col_names)
else:
col_names = exported_col_names
col_names = order_columns_with_primary_key_first(col_names, ddl_primary_keys.get(table, []))
# Build schema from DDL types
type_map = ddl_types.get(table, {})
not_null_map = ddl_foreign_keys.get("__not_null__", {}).get(table, {})
primary_key_set = set(ddl_primary_keys.get(table, []))
cols_info = []
for cname in col_names:
atype = type_map.get(cname, "text")
sqlite_type = access_type_to_sqlite(atype)
if cname in currency_columns:
sqlite_type = "CURRENCY"
cols_info.append({
"name": cname,
"access_type": atype,
"sqlite_type": sqlite_type,
"not_null": not_null_map.get(cname, False) or cname in primary_key_set,
"datetime_mode": datetime_mode_map.get(cname, {}).get("mode", "auto") if "DATETIME" in sqlite_type.upper() else None,
"datetime_include_seconds": datetime_mode_map.get(cname, {}).get("include_seconds") if "DATETIME" in sqlite_type.upper() else None,
})
schema[table] = {
"columns": cols_info,
"primary_key": ddl_primary_keys.get(table, []),
"foreign_keys": merged_foreign_keys.get(table, []),
}
# Parse data rows
rows = []
lines = csv_out.splitlines()
for line in lines:
if not line.strip():
continue
raw_vals = _parse_csv_line(line)
row_by_name = dict(zip(exported_col_names, raw_vals))
typed_vals = []
for col in cols_info:
v = row_by_name.get(col["name"], "")
typed_vals.append(_coerce_value(v, col["sqlite_type"]))
rows.append(typed_vals)
data[table] = rows
infer_datetime_modes(schema, data)
return schema, data
def _normalize_access_format(fmt: str) -> str:
return re.sub(r"\s+", " ", (fmt or "").strip().lower())
def datetime_settings_from_access_format(fmt: str | None) -> dict[str, object]:
"""Map Access Format text to datetime mode and time precision."""
settings: dict[str, object] = {"mode": None, "include_seconds": None}
if not fmt:
return settings
f = _normalize_access_format(fmt)
if not f:
return settings
# Common Access named formats
if "short date" in f or "medium date" in f or "long date" in f:
settings["mode"] = "date"
return settings
if "short time" in f:
settings["mode"] = "time"
settings["include_seconds"] = False
return settings
if "medium time" in f:
settings["mode"] = "time"
settings["include_seconds"] = False
return settings
if "long time" in f:
settings["mode"] = "time"
settings["include_seconds"] = True
return settings
if "general date" in f:
settings["mode"] = "datetime"
return settings
has_date_token = bool(re.search(r"\b(d|dd|ddd|dddd|m|mm|mmm|mmmm|yy|yyyy)\b", f))
has_time_token = bool(re.search(r"\b(h|hh|n|nn|s|ss|am/pm|a/p)\b", f))
has_second_token = bool(re.search(r"\b(s|ss)\b", f))
if has_date_token and not has_time_token:
settings["mode"] = "date"
elif has_time_token and not has_date_token:
settings["mode"] = "time"
settings["include_seconds"] = has_second_token
elif has_date_token and has_time_token:
settings["mode"] = "datetime"
settings["include_seconds"] = has_second_token
return settings