forked from MrBlenny/py-d2
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsimple_sql_schema.py
More file actions
45 lines (34 loc) · 1.22 KB
/
simple_sql_schema.py
File metadata and controls
45 lines (34 loc) · 1.22 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
import os
import subprocess
from d2.diagram import Diagram
from d2.sql_table import SQLConstraint
from d2.sql_table import SQLTable
from d2.sql_table import create_foreign_key_connection
FILE_NAME = "simple_sql_schema"
# Create a new diagram
diagram = Diagram()
# Create Users table
users = SQLTable("users")
users.add_field("id", "int", SQLConstraint.PRIMARY_KEY)
users.add_field("name", "varchar(255)")
# Create Orders table
orders = SQLTable("orders")
orders.add_field("id", "int", SQLConstraint.PRIMARY_KEY)
orders.add_field("user_id", "int", SQLConstraint.FOREIGN_KEY)
orders.add_field("total", "decimal(10,2)")
# Create connection
fk = create_foreign_key_connection("orders", "user_id", "users", "id")
# Add tables and connections to the diagram
diagram.add_shape(users)
diagram.add_shape(orders)
diagram.add_connection(fk)
# Write the diagram to a file
with open(f"{FILE_NAME}.d2", "w") as f:
f.write(str(diagram))
print(f"D2 diagram file created: {FILE_NAME}.d2")
print(str(diagram))
try:
subprocess.run(["d2", "--layout", "elk", f"{FILE_NAME}.d2", f"{FILE_NAME}.svg"], check=True)
print(f"SVG diagram generated: {os.path.abspath(f'{FILE_NAME}.svg')}")
except Exception as e:
print(f"Error generating SVG: {e}")