sqlite_file.py
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
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
"""本地文件数据源:上传的 CSV / Excel / JSON 导进一个只属于该数据源的 SQLite 库,之后就是普通的 SQL 数据源。
内省、问数、对象绑定、数据管道全部复用同一套管线 —— 只是方言换成 sqlite。
运行时用只读 URI 打开(mode=ro),生成的 SQL 就算绕过了 guard 也写不进去。
"""
from __future__ import annotations
import csv
import io
import json
import logging
import re
import sqlite3
import time
from pathlib import Path
from typing import Any
from sqlalchemy import create_engine, text as sa_text
from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from .base import (
ColumnInfo, ConnectionFailed, Connector, ForeignKeyInfo, Introspection,
QueryFailed, QueryResult, TableInfo,
)
from .mysql import _clean, _is_pii, _jsonable, _short
log = logging.getLogger(__name__)
FILE_TYPES = (".csv", ".tsv", ".xlsx", ".xlsm", ".json")
_BAD = re.compile(r"[^\w一-鿿]+")
def _q(name: str) -> str:
return '"' + str(name).replace('"', '""') + '"'
class SQLiteFileConnector(Connector):
dialect = "sqlite"
def __init__(self, ds: dict, password: str):
super().__init__(ds, password)
self._engine: Engine | None = None
@property
def path(self) -> Path:
return Path(self.ds.get("db_name") or "")
@property
def engine(self) -> Engine:
if self._engine is None:
if not self.path.exists():
raise ConnectionFailed(f"数据文件不存在:{self.path.name}(请重新上传)")
uri = f"file:{self.path.as_posix()}?mode=ro"
self._engine = create_engine("sqlite://", future=True,
creator=lambda: sqlite3.connect(uri, uri=True,
check_same_thread=False))
return self._engine
def dispose(self) -> None:
if self._engine is not None:
self._engine.dispose()
self._engine = None
def test(self) -> dict:
try:
with self.engine.connect() as c:
n = c.execute(sa_text("SELECT COUNT(*) FROM sqlite_master WHERE type IN ('table','view')")).scalar_one()
ver = c.execute(sa_text("SELECT sqlite_version()")).scalar_one()
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return {"version": f"SQLite {ver}(本地文件)", "database": self.path.name,
"table_count": int(n), "account_writable": False}
def introspect(self) -> Introspection:
try:
with self.engine.connect() as c:
tables = []
fks: list[ForeignKeyInfo] = []
for name, ttype in c.execute(sa_text(
"SELECT name, type FROM sqlite_master WHERE type IN ('table','view') "
"AND name NOT LIKE 'sqlite_%' AND name != '_onto_files' ORDER BY name")).fetchall():
t = TableInfo(name=name, kind=ttype, comment="")
t.row_count_est = int(c.execute(sa_text(f"SELECT COUNT(*) FROM {_q(name)}")).scalar_one() or 0)
for _, cname, ctype, notnull, default, pk in c.execute(
sa_text(f"PRAGMA table_info({_q(name)})")).fetchall():
t.columns.append(ColumnInfo(name=cname, data_type=str(ctype or "TEXT"),
nullable=not notnull,
default="" if default is None else str(default)))
if pk:
t.primary_key.append(cname)
for row in c.execute(sa_text(f"PRAGMA foreign_key_list({_q(name)})")).fetchall():
fks.append(ForeignKeyInfo(from_table=name, from_column=row[3], to_table=row[2],
to_column=row[4]))
tables.append(t)
meta = {}
try:
meta = {r[0]: r[1] for r in c.execute(sa_text(
"SELECT table_name, source FROM _onto_files")).fetchall()}
except SQLAlchemyError:
pass
for t in tables:
if t.name in meta:
t.comment = f"来自文件 {meta[t.name]}"
except SQLAlchemyError as e:
raise ConnectionFailed(_clean(e)) from e
return Introspection(tables=tables, foreign_keys=fks)
def sample_values(self, table: str, column: str, limit: int, max_distinct: int) -> tuple[list[str], int]:
if limit <= 0 or _is_pii(column):
return [], 0
try:
with self.engine.connect() as c:
total = int(c.execute(sa_text(
f"SELECT COUNT(*) FROM (SELECT DISTINCT {_q(column)} FROM {_q(table)} "
f"WHERE {_q(column)} IS NOT NULL LIMIT {int(max_distinct) + 1})")).scalar_one() or 0)
if total == 0 or total > max_distinct:
return [], total
rows = c.execute(sa_text(
f"SELECT {_q(column)}, COUNT(*) AS c FROM {_q(table)} WHERE {_q(column)} IS NOT NULL "
f"GROUP BY {_q(column)} ORDER BY c DESC LIMIT {int(limit)}")).fetchall()
except SQLAlchemyError:
return [], 0
return [_short(r[0]) for r in rows], total
def null_ratios(self, table: str, columns: list[str], sample: int = 50000) -> dict[str, float]:
if not columns:
return {}
parts = ", ".join(f"SUM(CASE WHEN {_q(c)} IS NULL OR {_q(c)} = '' THEN 1 ELSE 0 END)"
for c in columns)
try:
with self.engine.connect() as c:
row = c.execute(sa_text(f"SELECT COUNT(*), {parts} FROM "
f"(SELECT * FROM {_q(table)} LIMIT {int(sample)})")).fetchone()
except SQLAlchemyError:
return {}
total = int((row or [0])[0] or 0)
if not total:
return {}
return {col: float(row[i + 1] or 0) / total for i, col in enumerate(columns)}
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
started = time.time()
deadline = started + timeout_ms / 1000.0
try:
with self.engine.connect() as c:
raw = c.connection.driver_connection
raw.set_progress_handler(lambda: 1 if time.time() > deadline else 0, 10000)
cur = c.execute(sa_text(sql))
cols = list(cur.keys())
rows = cur.fetchmany(row_limit + 1)
raw.set_progress_handler(None, 0)
except SQLAlchemyError as e:
msg = _clean(e)
raise QueryFailed("查询超时" if "interrupted" in msg else msg) from e
truncated = len(rows) > row_limit
rows = rows[:row_limit]
return QueryResult(columns=cols, rows=[[_jsonable(v) for v in r] for r in rows],
row_count=len(rows), duration_ms=int((time.time() - started) * 1000),
truncated=truncated)
# ---------------- 导入 ----------------
def _table_name(stem: str, used: set[str]) -> str:
base = _BAD.sub("_", stem).strip("_").lower() or "sheet"
if base[0].isdigit():
base = f"t_{base}"
name, i = base[:48], 2
while name in used:
name = f"{base[:44]}_{i}"
i += 1
used.add(name)
return name
def _rows_from(name: str, raw: bytes) -> list[tuple[str, list[str], list[list[Any]]]]:
"""返回 [(表名来源, 表头, 行)]。Excel 每个工作表一张表。"""
suffix = Path(name).suffix.lower()
stem = Path(name).stem
if suffix in (".csv", ".tsv"):
from ...ingest.parse import decode_text
text, _ = decode_text(raw)
reader = list(csv.reader(io.StringIO(text), delimiter="\t" if suffix == ".tsv" else ","))
reader = [r for r in reader if any(str(x).strip() for x in r)]
return [(stem, reader[0], reader[1:])] if reader else []
if suffix in (".xlsx", ".xlsm"):
import openpyxl
wb = openpyxl.load_workbook(io.BytesIO(raw), read_only=True, data_only=True)
out = []
for ws in wb.worksheets:
rows = [list(r) for r in ws.iter_rows(values_only=True) if any(v not in (None, "") for v in r)]
if rows:
out.append((f"{stem}_{ws.title}" if len(wb.worksheets) > 1 else stem,
[str(x or f"col{i + 1}") for i, x in enumerate(rows[0])], rows[1:]))
return out
if suffix == ".json":
data = json.loads(raw.decode("utf-8-sig"))
if isinstance(data, dict):
data = next((v for v in data.values() if isinstance(v, list)), [data])
data = [x for x in data if isinstance(x, dict)]
head = list(dict.fromkeys(k for x in data for k in x))
return [(stem, head, [[x.get(k) for k in head] for x in data])] if head else []
raise ValueError(f"暂不支持的文件类型:{suffix}(支持 {'、'.join(FILE_TYPES)})")
def _col_type(vals: list[Any]) -> str:
seen = [v for v in vals if v not in (None, "")]
if not seen:
return "TEXT"
def isint(v):
return isinstance(v, bool) is False and (isinstance(v, int) or (isinstance(v, str) and re.fullmatch(r"-?\d{1,18}", v.strip())))
def isnum(v):
if isinstance(v, (int, float)) and not isinstance(v, bool):
return True
try:
float(str(v).replace(",", ""))
return True
except ValueError:
return False
if all(isint(v) for v in seen):
return "INTEGER"
if all(isnum(v) for v in seen):
return "REAL"
return "TEXT"
def import_files(path: Path, files: list[tuple[str, bytes]]) -> list[dict]:
"""把文件导进 SQLite 库(同名表覆盖)。返回每张表的导入结果。"""
path.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(path)
out = []
try:
con.execute("CREATE TABLE IF NOT EXISTS _onto_files (table_name TEXT PRIMARY KEY, source TEXT)")
used = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")}
for fname, raw in files:
for stem, head, rows in _rows_from(fname, raw):
prev = con.execute("SELECT table_name FROM _onto_files WHERE source = ?",
(f"{fname}:{stem}",)).fetchone()
table = prev[0] if prev else _table_name(stem, used)
cols, seen = [], set()
for i, h in enumerate(head):
c = _BAD.sub("_", str(h or "")).strip("_") or f"col{i + 1}"
while c in seen:
c = f"{c}_{i + 1}"
seen.add(c)
cols.append(c)
width = len(cols)
rows = [list(r[:width]) + [None] * (width - len(r)) for r in rows]
types = [_col_type([r[i] for r in rows[:2000]]) for i in range(width)]
def conv(v, t):
if v in (None, ""):
return None
if t == "INTEGER":
return int(str(v).strip()) if not isinstance(v, int) else v
if t == "REAL":
return float(str(v).replace(",", "")) if not isinstance(v, (int, float)) else v
return v.isoformat() if hasattr(v, "isoformat") else str(v)
con.execute(f"DROP TABLE IF EXISTS {_q(table)}")
con.execute(f"CREATE TABLE {_q(table)} ("
+ ", ".join(f"{_q(c)} {t}" for c, t in zip(cols, types)) + ")")
con.executemany(f"INSERT INTO {_q(table)} VALUES ({', '.join('?' * width)})",
[[conv(v, t) for v, t in zip(r, types)] for r in rows])
con.execute("INSERT OR REPLACE INTO _onto_files VALUES (?, ?)", (table, f"{fname}:{stem}"))
out.append({"table": table, "file": fname, "rows": len(rows), "columns": width})
con.commit()
finally:
con.close()
return out