-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdialects.py
More file actions
155 lines (133 loc) · 4.61 KB
/
Copy pathdialects.py
File metadata and controls
155 lines (133 loc) · 4.61 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
"""SQL dialect definitions and formatting."""
from enum import Enum
from typing import Any
class Dialect(str, Enum):
POSTGRES = "postgres"
MYSQL = "mysql"
SQLITE = "sqlite"
# Python type -> SQL type mapping per dialect
_TYPE_MAP = {
Dialect.POSTGRES: {
str: "TEXT",
int: "INTEGER",
float: "DOUBLE PRECISION",
bool: "BOOLEAN",
type(None): "TEXT", # nullable
},
Dialect.MYSQL: {
str: "VARCHAR(255)",
int: "INT",
float: "DOUBLE",
bool: "TINYINT(1)",
type(None): "TEXT",
},
Dialect.SQLITE: {
str: "TEXT",
int: "INTEGER",
float: "REAL",
bool: "INTEGER",
type(None): "TEXT",
},
}
def sql_type_for(value: Any, dialect: Dialect) -> str:
"""Infer SQL column type from a Python value."""
if value is None:
return _TYPE_MAP[dialect].get(str, "TEXT")
py_type = type(value)
if py_type is bool: # bool must be checked before int (bool is subclass of int)
return _TYPE_MAP[dialect][bool]
return _TYPE_MAP[dialect].get(py_type, "TEXT")
_TYPE_RANK = {
"BOOLEAN": 0,
"TINYINT(1)": 0,
"INTEGER": 1,
"INT": 1,
"DOUBLE PRECISION": 2,
"DOUBLE": 2,
"REAL": 2,
"TEXT": 3,
"VARCHAR(255)": 3,
}
def merge_type(current: str, value: Any, dialect: Dialect) -> str:
"""Merge a column's current inferred SQL type with a new value's type.
Widens toward the most general compatible type so a column holding mixed
values produces valid SQL. Any string in a column forces TEXT (a numeric
column cannot hold a quoted string literal). A boolean mixed with a numeric
type also widens to TEXT because a boolean literal is not assignable to
INTEGER/REAL in strict SQL dialects.
"""
new_type = sql_type_for(value, dialect)
if new_type == "TEXT" or current == "TEXT":
return "TEXT"
cur_rank = _TYPE_RANK.get(current, 3)
new_rank = _TYPE_RANK.get(new_type, 3)
# A boolean mixed with a numeric type is unsafe to keep numeric.
if 0 in (cur_rank, new_rank) and max(cur_rank, new_rank) > 0:
return "TEXT"
# Otherwise widen to the broader numeric type.
return current if cur_rank >= new_rank else new_type
def quote_identifier(name: str, dialect: Dialect) -> str:
"""Quote an identifier (table/column name) for the given dialect."""
if dialect == Dialect.MYSQL:
return f"`{name}`"
return f'"{name}"'
def format_value(value: Any, dialect: Dialect) -> str:
"""Format a Python value as a SQL literal."""
if value is None:
return "NULL"
if isinstance(value, bool):
if dialect == Dialect.POSTGRES:
return "TRUE" if value else "FALSE"
return "1" if value else "0"
if isinstance(value, str):
escaped = value.replace("'", "''")
return f"'{escaped}'"
if isinstance(value, int | float):
return str(value)
return f"'{value}'"
def create_table_sql(
table_name: str,
columns: dict[str, str],
dialect: Dialect,
) -> str:
"""Generate a CREATE TABLE statement."""
qtable = quote_identifier(table_name, dialect)
col_defs = []
for col_name, col_type in columns.items():
qcol = quote_identifier(col_name, dialect)
col_defs.append(f" {qcol} {col_type}")
col_str = ",\n".join(col_defs)
return f"CREATE TABLE {qtable} (\n{col_str}\n);"
def insert_sql(
table_name: str,
columns: list[str],
rows: list[list[str]],
dialect: Dialect,
) -> str:
"""Generate INSERT statement(s)."""
qtable = quote_identifier(table_name, dialect)
qcols = [quote_identifier(c, dialect) for c in columns]
col_str = ", ".join(qcols)
if dialect == Dialect.POSTGRES and len(rows) > 1:
# Multi-row INSERT for PostgreSQL
values_parts = []
for row in rows:
val_str = ", ".join(row)
values_parts.append(f" ({val_str})")
values_str = ",\n".join(values_parts)
return f"INSERT INTO {qtable} ({col_str})\nVALUES\n{values_str};"
elif dialect == Dialect.MYSQL and len(rows) > 1:
# Multi-row INSERT for MySQL
values_parts = []
for row in rows:
val_str = ", ".join(row)
values_parts.append(f" ({val_str})")
values_str = ",\n".join(values_parts)
return f"INSERT INTO {qtable} ({col_str})\nVALUES\n{values_str};"
else:
# Single-row INSERTs (SQLite or single row)
inserts = []
for row in rows:
val_str = ", ".join(row)
inserts.append(f"INSERT INTO {qtable} ({col_str})\nVALUES ({val_str});")
return "\n".join(inserts)