Repository navigation
Expand file tree
/
Copy pathcreate_table.py
More file actions
68 lines (54 loc) · 2.12 KB
/
Copy pathcreate_table.py
File metadata and controls
68 lines (54 loc) · 2.12 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
import re
import json
import os
class Table:
def __init__(self, name, columns, indexes=None):
self.name = name
self.columns = columns
self.indexes = indexes or []
self.rows = []
def parse_create_table(sql):
match = re.match(r'CREATE TABLE (\w+)\s*\((.*)\)', sql, re.IGNORECASE | re.DOTALL)
if not match:
raise ValueError("Invalid CREATE TABLE syntax")
table_name = match.group(1)
columns_str = match.group(2)
columns = []
indexes = []
for part in re.split(r',(?![^()]*\))', columns_str):
part = part.strip()
if part.upper().startswith('INDEX'):
idx_match = re.match(r'INDEX (\w+)\s*\((\w+)\)', part, re.IGNORECASE)
if idx_match:
indexes.append({'name': idx_match.group(1), 'column': idx_match.group(2)})
else:
col_match = re.match(r'(\w+)\s+([A-Z0-9()]+)(?:\s+(PRIMARY KEY|NOT NULL|DEFAULT .+))*', part, re.IGNORECASE)
if col_match:
col_name = col_match.group(1)
col_type = col_match.group(2)
constraints = part[len(col_name) + len(col_type):].strip()
columns.append({'name': col_name, 'type': col_type, 'constraints': constraints})
return table_name, columns, indexes
def create_table(db_path, sql):
table_name, columns, indexes = parse_create_table(sql)
table = Table(table_name, columns, indexes)
os.makedirs(db_path, exist_ok=True)
table_file = os.path.join(db_path, f"{table_name}.json")
with open(table_file, 'w') as f:
json.dump({
'name': table.name,
'columns': table.columns,
'indexes': table.indexes,
'rows': table.rows
}, f, indent=2)
return table
# Example usage
if __name__ == "__main__":
sql = """CREATE TABLE users (
id BINARY(16) PRIMARY KEY DEFAULT (UUID_TO_BIN(UUID())),
name VARCHAR(100)
)"""
table = create_table("./demo_db", sql)
print(f"Created table: {table.name}")
print(f"Columns: {table.columns}")
print(f"Indexes: {table.indexes}")