Repository navigation
Expand file tree
/
Copy pathduckdb2dbml.py
More file actions
101 lines (75 loc) · 2.49 KB
/
Copy pathduckdb2dbml.py
File metadata and controls
101 lines (75 loc) · 2.49 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
import duckdb
DB = "lahman-cmudb2025.db"
con = duckdb.connect(DB)
# -----------------------------
# columns
# -----------------------------
columns = con.execute("""
SELECT
table_name,
column_name,
data_type,
ordinal_position
FROM information_schema.columns
WHERE table_schema='main'
ORDER BY table_name, ordinal_position;
""").fetchall()
# -----------------------------
# primary key
# -----------------------------
pk = {}
try:
rows = con.execute("""
SELECT
kcu.table_name,
kcu.column_name
FROM information_schema.table_constraints tc
JOIN information_schema.key_column_usage kcu
ON tc.constraint_name = kcu.constraint_name
WHERE tc.constraint_type='PRIMARY KEY';
""").fetchall()
for t,c in rows:
pk.setdefault(t,set()).add(c)
except:
pass
# -----------------------------
# foreign key
# -----------------------------
fks = []
try:
rows = con.execute("""
SELECT
fk.table_name,
fk.column_name,
pk.table_name,
pk.column_name
FROM information_schema.referential_constraints rc
JOIN information_schema.key_column_usage fk
ON rc.constraint_name=fk.constraint_name
JOIN information_schema.key_column_usage pk
ON rc.unique_constraint_name=pk.constraint_name;
""").fetchall()
fks.extend(rows)
except:
pass
# -----------------------------
# output table
# -----------------------------
current = None
for table,col,tp,pos in columns:
if table != current:
if current is not None:
print("}\n")
print(f"Table {table} {{")
current = table
line = f" {col} {tp.lower()}"
if table in pk and col in pk[table]:
line += " [pk]"
print(line)
print("}")
print()
# -----------------------------
# output ref
# -----------------------------
for ft,fc,tt,tc in fks:
print(f"Ref: {ft}.{fc} > {tt}.{tc}")