codecop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codecop/__init__.py +7 -0
- codecop/access.py +140 -0
- codecop/access_postgres.py +284 -0
- codecop/advisor.py +1512 -0
- codecop/advisor_bench.py +493 -0
- codecop/advisor_ch.py +2080 -0
- codecop/advisor_view.py +381 -0
- codecop/advisors.py +184 -0
- codecop/agent.py +221 -0
- codecop/agentfacts.py +745 -0
- codecop/apply/__init__.py +327 -0
- codecop/apply/check.py +344 -0
- codecop/apply/cli.py +162 -0
- codecop/apply/clickhouse.py +379 -0
- codecop/apply/common.py +238 -0
- codecop/apply/html.py +264 -0
- codecop/apply/patch.py +213 -0
- codecop/apply/postgres.py +102 -0
- codecop/apply/trial.py +166 -0
- codecop/assemble.py +104 -0
- codecop/baseline.py +1043 -0
- codecop/bench.py +2464 -0
- codecop/blockers.py +935 -0
- codecop/budget.py +980 -0
- codecop/catalog_profile.py +525 -0
- codecop/changed.py +261 -0
- codecop/cicmd.py +1002 -0
- codecop/cli.py +5421 -0
- codecop/client.py +729 -0
- codecop/coverage.py +1067 -0
- codecop/coverage_reasons.py +116 -0
- codecop/crashlog.py +70 -0
- codecop/datagen.py +766 -0
- codecop/datagen_postgres.py +630 -0
- codecop/datagen_sqlite.py +323 -0
- codecop/dbcli.py +885 -0
- codecop/definitions.py +457 -0
- codecop/discover/__init__.py +702 -0
- codecop/discover/arms.py +160 -0
- codecop/discover/base.py +234 -0
- codecop/discover/dialect.py +296 -0
- codecop/discover/elixir.py +64 -0
- codecop/discover/engine_go.py +320 -0
- codecop/discover/go.py +1947 -0
- codecop/discover/java.py +1528 -0
- codecop/discover/loops.py +1671 -0
- codecop/discover/named_go.py +258 -0
- codecop/discover/origins.py +4565 -0
- codecop/discover/origins_ts.py +1584 -0
- codecop/discover/orm_django.py +2772 -0
- codecop/discover/orm_django_models.py +814 -0
- codecop/discover/orm_django_sql.py +662 -0
- codecop/discover/orm_ent.py +565 -0
- codecop/discover/orm_ex_ecto.py +2138 -0
- codecop/discover/orm_go.py +2134 -0
- codecop/discover/orm_go_bun.py +602 -0
- codecop/discover/orm_go_run.py +636 -0
- codecop/discover/orm_go_types.py +1082 -0
- codecop/discover/orm_java.py +1450 -0
- codecop/discover/orm_jdbi.py +743 -0
- codecop/discover/orm_jooq.py +806 -0
- codecop/discover/orm_jpa.py +1307 -0
- codecop/discover/orm_mybatis.py +730 -0
- codecop/discover/orm_py.py +557 -0
- codecop/discover/orm_py_peewee.py +1266 -0
- codecop/discover/orm_py_prisma.py +298 -0
- codecop/discover/orm_rb_activerecord.py +1906 -0
- codecop/discover/orm_rust.py +1248 -0
- codecop/discover/orm_rust_seaorm.py +734 -0
- codecop/discover/orm_sqlalchemy.py +2475 -0
- codecop/discover/orm_stats.py +307 -0
- codecop/discover/orm_tables.py +29 -0
- codecop/discover/orm_ts.py +503 -0
- codecop/discover/orm_ts_drizzle.py +697 -0
- codecop/discover/orm_ts_knex.py +1117 -0
- codecop/discover/orm_ts_kysely.py +861 -0
- codecop/discover/orm_ts_prisma.py +1045 -0
- codecop/discover/orm_ts_schema.py +169 -0
- codecop/discover/orm_ts_sequelize.py +1401 -0
- codecop/discover/orm_ts_typeorm.py +1067 -0
- codecop/discover/probes.py +323 -0
- codecop/discover/python.py +595 -0
- codecop/discover/ruby.py +793 -0
- codecop/discover/rust.py +2378 -0
- codecop/discover/schema.py +520 -0
- codecop/discover/schema_ent.py +145 -0
- codecop/discover/schema_ts.py +420 -0
- codecop/discover/tsresolve.py +257 -0
- codecop/discover/typescript.py +1728 -0
- codecop/discover/xml_mapper.py +526 -0
- codecop/engines/__init__.py +515 -0
- codecop/engines/base.py +498 -0
- codecop/engines/clickhouse.py +1558 -0
- codecop/engines/pg_ddl.py +444 -0
- codecop/engines/pg_hints.py +137 -0
- codecop/engines/postgres.py +1060 -0
- codecop/engines/sqlite.py +742 -0
- codecop/families/__init__.py +3 -0
- codecop/families/build.py +280 -0
- codecop/families/cli.py +177 -0
- codecop/families/coverage_hook.py +62 -0
- codecop/families/driver.py +221 -0
- codecop/families/goslice.py +229 -0
- codecop/families/goslice_tool/go.mod +3 -0
- codecop/families/goslice_tool/main.go +403 -0
- codecop/families/holes.py +451 -0
- codecop/families/images/Dockerfile.go +5 -0
- codecop/families/images/Dockerfile.python +4 -0
- codecop/families/images/Dockerfile.rust +4 -0
- codecop/families/isolate.py +171 -0
- codecop/families/locate.py +270 -0
- codecop/families/model.py +301 -0
- codecop/families/plangate.py +271 -0
- codecop/families/tagpatch.py +174 -0
- codecop/fidelity.py +671 -0
- codecop/fixgroups.py +130 -0
- codecop/formerly.py +91 -0
- codecop/grantscript.py +254 -0
- codecop/groupbench.py +1375 -0
- codecop/groups.py +594 -0
- codecop/groups_view.py +186 -0
- codecop/heat.py +1405 -0
- codecop/heatcli.py +219 -0
- codecop/joins.py +1749 -0
- codecop/joins_view.py +127 -0
- codecop/kinds/__init__.py +507 -0
- codecop/kinds/calls/__init__.py +501 -0
- codecop/kinds/calls/extract.py +1097 -0
- codecop/kinds/calls/harness.py +408 -0
- codecop/kinds/calls/measure.py +342 -0
- codecop/kinds/calls/rules.py +139 -0
- codecop/kinds/calls/runners/RunCalls.java +167 -0
- codecop/kinds/calls/runners/run_go.go +141 -0
- codecop/kinds/calls/runners/run_node.js +186 -0
- codecop/kinds/calls/runners/run_python.py +319 -0
- codecop/kinds/calls/runners/run_rust.rs +200 -0
- codecop/kinds/calls/standin.py +340 -0
- codecop/kinds/pipeline.py +288 -0
- codecop/kinds/regex/__init__.py +1167 -0
- codecop/kinds/regex/engines/RegexHarness.java +129 -0
- codecop/kinds/regex/engines/run_go.go +294 -0
- codecop/kinds/regex/engines/run_node.js +99 -0
- codecop/kinds/regex/engines/run_python.py +295 -0
- codecop/kinds/regex/engines/run_rust.rs +149 -0
- codecop/kinds/regex/extract.py +1438 -0
- codecop/kinds/regex/harness.py +235 -0
- codecop/kinds/regex/measure.py +270 -0
- codecop/kinds/regex/shapes.py +418 -0
- codecop/kinds/regex/syntax.py +1721 -0
- codecop/kinds/testkind.py +107 -0
- codecop/kinds/transaction/__init__.py +228 -0
- codecop/kinds/transaction/bind.py +355 -0
- codecop/kinds/transaction/measure.py +264 -0
- codecop/kinds/transaction/plan.py +462 -0
- codecop/kinds/transaction/rules.py +540 -0
- codecop/kinds/transaction/sandbox.py +94 -0
- codecop/kinds/transaction/scenarios.py +520 -0
- codecop/kinds/transaction/schedule.py +483 -0
- codecop/kinds/transaction/shapes.py +418 -0
- codecop/kinds/transaction/verify.py +293 -0
- codecop/live.py +237 -0
- codecop/loopbench.py +2071 -0
- codecop/loopschema.py +591 -0
- codecop/mcpserver.py +120 -0
- codecop/mechanism.py +214 -0
- codecop/members.py +200 -0
- codecop/multi.py +443 -0
- codecop/observed.py +1868 -0
- codecop/parts.py +102 -0
- codecop/patterns.py +830 -0
- codecop/patterns_view.py +559 -0
- codecop/plangate.py +242 -0
- codecop/profile.py +439 -0
- codecop/prompts/areas.md +19 -0
- codecop/prompts/observed_variants.md +20 -0
- codecop/prompts/profile.md +60 -0
- codecop/prompts/profile_postgres.md +68 -0
- codecop/prompts/profile_sizes.md +26 -0
- codecop/prompts/profile_sqlite.md +69 -0
- codecop/prompts/rank.md +84 -0
- codecop/prompts/rank_postgres.md +96 -0
- codecop/prompts/rank_sqlite.md +94 -0
- codecop/prompts/scenario_variants.md +20 -0
- codecop/rank.py +1473 -0
- codecop/realdb/__init__.py +688 -0
- codecop/realdb/clickhouse.py +1223 -0
- codecop/realdb/facts.py +815 -0
- codecop/realdb/locality.py +964 -0
- codecop/realdb/locks.py +355 -0
- codecop/realdb/match.py +531 -0
- codecop/realdb/postgres.py +643 -0
- codecop/realdb/ratios.py +77 -0
- codecop/realdb/sample.py +126 -0
- codecop/relations.py +227 -0
- codecop/report.py +1854 -0
- codecop/resources.py +332 -0
- codecop/resources_view.py +266 -0
- codecop/rules/entry_points.toml +1013 -0
- codecop/rules/sinks.toml +362 -0
- codecop/runsonce.py +8 -0
- codecop/sandboxschema.py +555 -0
- codecop/scenario_agent.py +172 -0
- codecop/scenario_bind.py +507 -0
- codecop/scenario_sql.py +971 -0
- codecop/scenarios.py +675 -0
- codecop/scenarios_view.py +274 -0
- codecop/schemacli.py +67 -0
- codecop/schemas/areas_output.schema.json +21 -0
- codecop/schemas/profile_output.schema.json +362 -0
- codecop/schemas/rank_output.schema.json +385 -0
- codecop/sizes.py +200 -0
- codecop/sqlinfo.py +558 -0
- codecop/typedparams.py +576 -0
- codecop/verdicts.py +212 -0
- codecop/writebench.py +720 -0
- codecop/writecost.py +440 -0
- codecop/writes.py +1208 -0
- codecop-0.1.0.dist-info/METADATA +42 -0
- codecop-0.1.0.dist-info/RECORD +222 -0
- codecop-0.1.0.dist-info/WHEEL +4 -0
- codecop-0.1.0.dist-info/entry_points.txt +2 -0
- codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,742 @@
|
|
|
1
|
+
"""SQLite sandbox adapter: an in-process database file, driven through Python's sqlite3. No container, no server.
|
|
2
|
+
|
|
3
|
+
The database is one file in a directory of its own under the run's work directory (`work_dir`, else the system's
|
|
4
|
+
temporary directory), removed when the sandbox closes. The application's own SQLite build, version, page size and
|
|
5
|
+
pragmas may differ from this one: the version measured is the library this Python links (`sqlite3.sqlite_version`),
|
|
6
|
+
and the run says so.
|
|
7
|
+
|
|
8
|
+
What is measured, and why
|
|
9
|
+
-------------------------
|
|
10
|
+
SQLite has no bytes-read counter and no EXPLAIN ANALYZE. It does count, per prepared statement and per connection,
|
|
11
|
+
what the C API reports through sqlite3_stmt_status and sqlite3_db_status. Python's sqlite3 module does not expose
|
|
12
|
+
them, so the measuring connection is opened on the same file through the same C library with ctypes (`Meter`). From
|
|
13
|
+
the last of `runs` timed executions (after one warm-up):
|
|
14
|
+
|
|
15
|
+
read_bytes pages the statement asked the pager for (SQLITE_DBSTATUS_CACHE_HIT + CACHE_MISS) x page size. The
|
|
16
|
+
analogue of PostgreSQL's shared buffers hit + read: a page counts whether or not it was cached, so the
|
|
17
|
+
number depends on the plan and the data, not on what happens to be in memory, and repeats exactly.
|
|
18
|
+
This is what decides (`pages_decide`), as buffer pages do on PostgreSQL.
|
|
19
|
+
read_rows rows a full table scan stepped over (SQLITE_STMTSTATUS_FULLSCAN_STEP). An index search adds nothing
|
|
20
|
+
here: a statement that only searches indexes reads 0 such rows however many pages it touches. Stated
|
|
21
|
+
beside the pages, never deciding.
|
|
22
|
+
vm_steps virtual machine instructions the statement ran (SQLITE_STMTSTATUS_VM_STEP): the CPU side of the same
|
|
23
|
+
work, exact and repeatable. Recorded, not deciding.
|
|
24
|
+
sorts sorts the statement ran (a temp B-tree for ORDER BY or GROUP BY: SQLITE_STMTSTATUS_SORT)
|
|
25
|
+
autoindexes rows inserted into automatic indexes SQLite built for the statement (SQLITE_STMTSTATUS_AUTOINDEX):
|
|
26
|
+
a join with no usable index makes one on every run
|
|
27
|
+
plan EXPLAIN QUERY PLAN: every SCAN (a full pass over a table or a covering index) and SEARCH (a lookup
|
|
28
|
+
through an index or the rowid), the index used, USE TEMP B-TREE for a sort.
|
|
29
|
+
duration_ms wall time of the fastest timed run, in this process: secondary.
|
|
30
|
+
|
|
31
|
+
`conn.set_progress_handler` was tried for the step count and set aside: it is called back at jump instructions only
|
|
32
|
+
once every N instructions, so the count is approximate unless N is 1, and with N = 1 a Python call per instruction
|
|
33
|
+
makes a full scan of a million rows take seconds. The C counters are exact and cost nothing. When the C library can not
|
|
34
|
+
be loaded (a Python whose sqlite3 module is linked statically and exports nothing), the sandbox can not measure and
|
|
35
|
+
says so before anything is loaded.
|
|
36
|
+
|
|
37
|
+
Data: the generator (datagen_sqlite.py) is set-based SQL with a few deterministic functions registered on the loading
|
|
38
|
+
connection (FUNCTIONS). Measured statements run on the measuring connection, which has none of them.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
from __future__ import annotations
|
|
42
|
+
|
|
43
|
+
import ctypes
|
|
44
|
+
import ctypes.util
|
|
45
|
+
import hashlib
|
|
46
|
+
import json
|
|
47
|
+
import os
|
|
48
|
+
import re
|
|
49
|
+
import shutil
|
|
50
|
+
import sqlite3
|
|
51
|
+
import tempfile
|
|
52
|
+
import threading
|
|
53
|
+
import time
|
|
54
|
+
from dataclasses import dataclass, field
|
|
55
|
+
|
|
56
|
+
from .base import Measurement, QueryError, SandboxError, fill_resources, outside_quotes
|
|
57
|
+
from .pg_ddl import parse_table, split_statements, statement_kind, strip_constraints
|
|
58
|
+
|
|
59
|
+
PARAM = re.compile(r"\{(\w+)(?::([^{}]+))?\}")
|
|
60
|
+
MAX_QUERY_SECONDS = 180 # the same limit as the other sandboxes
|
|
61
|
+
# sqlite3_stmt_status and sqlite3_db_status codes (sqlite3.h)
|
|
62
|
+
STMT_FULLSCAN_STEP, STMT_SORT, STMT_AUTOINDEX, STMT_VM_STEP = 1, 2, 3, 4
|
|
63
|
+
DB_CACHE_HIT, DB_CACHE_MISS = 7, 8
|
|
64
|
+
SQLITE_ROW, SQLITE_DONE = 100, 101
|
|
65
|
+
_MASK62 = (1 << 62) - 1
|
|
66
|
+
_M64 = (1 << 64) - 1
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# ---------------------------------------------------------------------------- the generator's functions
|
|
70
|
+
|
|
71
|
+
def _mix(n: int, seed: int) -> int:
|
|
72
|
+
"""splitmix64 of the row number and a seed: a non-negative 62-bit integer."""
|
|
73
|
+
x = (int(n) * 0x9E3779B97F4A7C15 + (int(seed) + 1) * 0xBF58476D1CE4E5B9) & _M64
|
|
74
|
+
x ^= x >> 30
|
|
75
|
+
x = (x * 0xBF58476D1CE4E5B9) & _M64
|
|
76
|
+
x ^= x >> 27
|
|
77
|
+
x = (x * 0x94D049BB133111EB) & _M64
|
|
78
|
+
x ^= x >> 31
|
|
79
|
+
return x & _MASK62
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _uniform(n, seed) -> float:
|
|
83
|
+
return (_mix(n, seed) % 1000000007) / 1000000007.0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _skewed(n, seed, distinct) -> int:
|
|
87
|
+
import math
|
|
88
|
+
d = max(int(distinct), 1)
|
|
89
|
+
return min(int(math.floor(math.exp(_uniform(n, seed) * math.log(d)))) - 1, d - 1)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _text(n, seed, length) -> str:
|
|
96
|
+
"""`length` characters that depend only on the row number and the seed (a hash chain, base64 letters)."""
|
|
97
|
+
length = max(int(length or 0), 0)
|
|
98
|
+
out, i = [], 0
|
|
99
|
+
while sum(map(len, out)) < length:
|
|
100
|
+
block = hashlib.sha512(f"{n}/{seed}/{i}".encode()).digest()
|
|
101
|
+
out.append("".join(_ALPHABET[b & 63] for b in block))
|
|
102
|
+
i += 1
|
|
103
|
+
if i >= 64 and length > 64 * 64:
|
|
104
|
+
whole = "".join(out)
|
|
105
|
+
return (whole * (length // len(whole) + 1))[:length]
|
|
106
|
+
return "".join(out)[:length]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _length(n, seed, median, sigma, scale, cap, most) -> int:
|
|
110
|
+
import math
|
|
111
|
+
u1 = _uniform(n, seed) + 1e-12
|
|
112
|
+
u2 = _uniform(n, seed + 7919)
|
|
113
|
+
z = min(math.sqrt(-2 * math.log(u1)) * math.cos(6.283185307179586 * u2), float(cap))
|
|
114
|
+
value = float(median) * math.exp(float(sigma) * z) * float(scale or 1)
|
|
115
|
+
return int(min(max(round(value), 1), int(most)))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
FUNCTIONS = {"codecop_hash": (2, _mix), "codecop_u": (2, _uniform), "codecop_skewed": (3, _skewed), "codecop_text": (3, _text),
|
|
119
|
+
"codecop_length": (7, _length)}
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------------------- the C library's counters
|
|
123
|
+
|
|
124
|
+
def _library():
|
|
125
|
+
"""The C library Python's sqlite3 module runs on: its own extension module first (which resolves the symbols of the
|
|
126
|
+
library it links), then the system's."""
|
|
127
|
+
import _sqlite3
|
|
128
|
+
tried = []
|
|
129
|
+
for path in (getattr(_sqlite3, "__file__", None), ctypes.util.find_library("sqlite3")):
|
|
130
|
+
if not path:
|
|
131
|
+
continue
|
|
132
|
+
try:
|
|
133
|
+
lib = ctypes.CDLL(path)
|
|
134
|
+
lib.sqlite3_libversion.restype = ctypes.c_char_p
|
|
135
|
+
lib.sqlite3_stmt_status.restype = ctypes.c_int
|
|
136
|
+
lib.sqlite3_db_status.restype = ctypes.c_int
|
|
137
|
+
lib.sqlite3_errmsg.restype = ctypes.c_char_p
|
|
138
|
+
return lib, lib.sqlite3_libversion().decode()
|
|
139
|
+
except (OSError, AttributeError) as e:
|
|
140
|
+
tried.append(f"{path}: {e}")
|
|
141
|
+
raise SandboxError("SQLite sandbox: the SQLite C library this Python's sqlite3 module uses could not be loaded, so its page and "
|
|
142
|
+
"step counters can not be read (" + "; ".join(tried)[:300] + ")")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass
|
|
146
|
+
class Counted:
|
|
147
|
+
pages: int = 0
|
|
148
|
+
full_scan_rows: int = 0
|
|
149
|
+
vm_steps: int = 0
|
|
150
|
+
sorts: int = 0
|
|
151
|
+
autoindexes: int = 0
|
|
152
|
+
rows: int = 0
|
|
153
|
+
ms: float = 0.0
|
|
154
|
+
memory_bytes: int | None = None # the library's memory high-water during the step loop, over what it held before
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
SQLITE_STATUS_MEMORY_USED = 0
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class Meter:
|
|
161
|
+
"""A read-only connection to the sandbox file through the C API, which returns the counters of one execution."""
|
|
162
|
+
|
|
163
|
+
def __init__(self, path: str):
|
|
164
|
+
self.lib, self.version = _library()
|
|
165
|
+
self.db = ctypes.c_void_p()
|
|
166
|
+
# SQLITE_OPEN_READONLY = 1
|
|
167
|
+
rc = self.lib.sqlite3_open_v2(path.encode(), ctypes.byref(self.db), 1, None)
|
|
168
|
+
if rc != 0:
|
|
169
|
+
raise SandboxError(f"SQLite sandbox: could not open the measuring connection (code {rc})")
|
|
170
|
+
self._timer: threading.Timer | None = None
|
|
171
|
+
|
|
172
|
+
def close(self) -> None:
|
|
173
|
+
if self.db:
|
|
174
|
+
self.lib.sqlite3_close_v2(self.db)
|
|
175
|
+
self.db = ctypes.c_void_p()
|
|
176
|
+
|
|
177
|
+
def _db_status(self, op: int) -> int:
|
|
178
|
+
cur, hi = ctypes.c_int(), ctypes.c_int()
|
|
179
|
+
self.lib.sqlite3_db_status(self.db, op, ctypes.byref(cur), ctypes.byref(hi), 1)
|
|
180
|
+
return cur.value
|
|
181
|
+
|
|
182
|
+
def _memory(self, reset: bool = False) -> tuple[int | None, int | None]:
|
|
183
|
+
"""(memory in use, its high-water mark) of the SQLite library, process-wide; `reset` starts a new mark. (None, None)
|
|
184
|
+
where the library has no sqlite3_status64 or counts no memory (SQLITE_CONFIG_MEMSTATUS off)."""
|
|
185
|
+
fn = getattr(self.lib, "sqlite3_status64", None)
|
|
186
|
+
if fn is None:
|
|
187
|
+
return None, None
|
|
188
|
+
cur, hi = ctypes.c_int64(), ctypes.c_int64()
|
|
189
|
+
if fn(SQLITE_STATUS_MEMORY_USED, ctypes.byref(cur), ctypes.byref(hi), 1 if reset else 0) != 0 or cur.value <= 0:
|
|
190
|
+
return None, None
|
|
191
|
+
return cur.value, hi.value
|
|
192
|
+
|
|
193
|
+
def run(self, sql: str, timeout_s: float) -> Counted:
|
|
194
|
+
stmt = ctypes.c_void_p()
|
|
195
|
+
raw = sql.encode()
|
|
196
|
+
rc = self.lib.sqlite3_prepare_v2(self.db, raw, len(raw), ctypes.byref(stmt), None)
|
|
197
|
+
if rc != 0:
|
|
198
|
+
raise QueryError(self.lib.sqlite3_errmsg(self.db).decode(errors="replace"))
|
|
199
|
+
timer = threading.Timer(timeout_s, lambda: self.lib.sqlite3_interrupt(self.db))
|
|
200
|
+
try:
|
|
201
|
+
self._db_status(DB_CACHE_HIT) # reset: what preparing the statement read is not the statement's
|
|
202
|
+
self._db_status(DB_CACHE_MISS)
|
|
203
|
+
held = self._memory(reset=True) # the library's high-water mark from here (sqlite3_status64, process-wide)
|
|
204
|
+
started = time.perf_counter()
|
|
205
|
+
timer.start()
|
|
206
|
+
rows = 0
|
|
207
|
+
while True:
|
|
208
|
+
rc = self.lib.sqlite3_step(stmt)
|
|
209
|
+
if rc == SQLITE_ROW:
|
|
210
|
+
rows += 1
|
|
211
|
+
continue
|
|
212
|
+
break
|
|
213
|
+
elapsed = (time.perf_counter() - started) * 1000
|
|
214
|
+
if rc != SQLITE_DONE:
|
|
215
|
+
msg = self.lib.sqlite3_errmsg(self.db).decode(errors="replace")
|
|
216
|
+
if msg == "interrupted":
|
|
217
|
+
msg = f"statement did not finish within {timeout_s:g}s (interrupted)"
|
|
218
|
+
raise QueryError(msg)
|
|
219
|
+
peak = self._memory()[1]
|
|
220
|
+
return Counted(pages=self._db_status(DB_CACHE_HIT) + self._db_status(DB_CACHE_MISS),
|
|
221
|
+
full_scan_rows=self.lib.sqlite3_stmt_status(stmt, STMT_FULLSCAN_STEP, 0),
|
|
222
|
+
vm_steps=self.lib.sqlite3_stmt_status(stmt, STMT_VM_STEP, 0),
|
|
223
|
+
sorts=self.lib.sqlite3_stmt_status(stmt, STMT_SORT, 0),
|
|
224
|
+
autoindexes=self.lib.sqlite3_stmt_status(stmt, STMT_AUTOINDEX, 0), rows=rows, ms=elapsed,
|
|
225
|
+
memory_bytes=max(peak - held[0], 0) if peak is not None and held[0] is not None else None)
|
|
226
|
+
finally:
|
|
227
|
+
timer.cancel()
|
|
228
|
+
self.lib.sqlite3_finalize(stmt)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# ---------------------------------------------------------------------------- statements
|
|
232
|
+
|
|
233
|
+
def render_params(sql: str, params: dict | None) -> str:
|
|
234
|
+
"""{name:type} -> a literal the way a driver binds it: a number bare for a numeric type, else a quoted string. A
|
|
235
|
+
parameter with no value is left as written, so SQLite names it in its error."""
|
|
236
|
+
from ..datagen_sqlite import affinity
|
|
237
|
+
params = params or {}
|
|
238
|
+
|
|
239
|
+
def one(m: re.Match) -> str:
|
|
240
|
+
name, typ = m.group(1), (m.group(2) or "").strip()
|
|
241
|
+
if name not in params:
|
|
242
|
+
return m.group(0)
|
|
243
|
+
value = params[name]
|
|
244
|
+
if value is None or str(value).upper() == "NULL":
|
|
245
|
+
return "NULL"
|
|
246
|
+
if isinstance(value, bool):
|
|
247
|
+
return "1" if value else "0"
|
|
248
|
+
text = str(value)
|
|
249
|
+
if (affinity(typ) in ("INTEGER", "REAL", "NUMERIC") or not typ) and re.fullmatch(r"-?\d+(\.\d+)?([eE][-+]?\d+)?", text) \
|
|
250
|
+
and not re.search(r"DATE|TIME|CHAR|TEXT|CLOB|UUID", typ, re.I):
|
|
251
|
+
return text
|
|
252
|
+
if re.match(r"^\s*BOOL", typ, re.I) and text.lower() in ("true", "false"):
|
|
253
|
+
return "1" if text.lower() == "true" else "0"
|
|
254
|
+
return "'" + text.replace("'", "''") + "'"
|
|
255
|
+
return PARAM.sub(one, sql)
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def normalize_ddl(stmt: str) -> str:
|
|
259
|
+
"""`name` and [name] quoting as "name", outside strings: the DDL reader speaks double quotes only."""
|
|
260
|
+
def change(text: str) -> str:
|
|
261
|
+
return re.sub(r"\[([^\]\n]+)\]", lambda m: '"' + m.group(1) + '"', text)
|
|
262
|
+
stmt = re.sub(r"`([^`\n]+)`", lambda m: '"' + m.group(1) + '"', stmt)
|
|
263
|
+
return outside_quotes(stmt, change)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
CLOCK_WORDS = re.compile(r"\bCURRENT_TIMESTAMP\b|\bCURRENT_DATE\b|\bCURRENT_TIME\b", re.I)
|
|
267
|
+
NOW_ARG = re.compile(r"(\b(?:datetime|date|time|julianday|strftime|unixepoch|timediff)\s*\((?:\s*'[^']*'\s*,)?\s*)'now'", re.I)
|
|
268
|
+
UNIXEPOCH_NOW = re.compile(r"\bunixepoch\s*\(\s*\)", re.I)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
@dataclass
|
|
272
|
+
class SqliteMeasurement(Measurement):
|
|
273
|
+
vm_steps: int = 0
|
|
274
|
+
pages: int = 0
|
|
275
|
+
full_scan_rows: int = 0
|
|
276
|
+
sorts: int = 0
|
|
277
|
+
autoindexes: int = 0
|
|
278
|
+
page_size: int = 4096
|
|
279
|
+
plan: list[dict] = field(default_factory=list) # EXPLAIN QUERY PLAN: [{id, parent, detail}]
|
|
280
|
+
scans: list[dict] = field(default_factory=list) # each SCAN / SEARCH: {node, relation, index, detail}
|
|
281
|
+
node_types: list[str] = field(default_factory=list) # distinct: SCAN, SEARCH, TEMP B-TREE, AUTOMATIC INDEX
|
|
282
|
+
repeatable: bool = True # the pages of every timed run were the same
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
PLAN_LINE = re.compile(r"^(SCAN|SEARCH)\s+(?:TABLE\s+)?(\S+)(?:\s+AS\s+\S+)?(?:\s+USING\s+(?:(COVERING|INTEGER PRIMARY KEY|PRIMARY KEY|AUTOMATIC(?:\s+PARTIAL)?(?:\s+COVERING)?)\s+)?(?:INDEX\s+([^\s(]+))?)?", re.I)
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def read_plan(rows: list[tuple]) -> tuple[list[dict], list[dict], list[str]]:
|
|
289
|
+
plan = [{"id": r[0], "parent": r[1], "detail": r[3]} for r in rows]
|
|
290
|
+
scans, kinds = [], set()
|
|
291
|
+
for p in plan:
|
|
292
|
+
d = p["detail"]
|
|
293
|
+
m = PLAN_LINE.match(d)
|
|
294
|
+
if m:
|
|
295
|
+
how = (m.group(3) or "").upper()
|
|
296
|
+
index = m.group(4) or ("rowid" if "PRIMARY KEY" in how else "")
|
|
297
|
+
scans.append({"node": m.group(1).upper(), "relation": m.group(2), "index": index, "covering": "COVERING" in how,
|
|
298
|
+
"automatic": how.startswith("AUTOMATIC"), "detail": d[:200]})
|
|
299
|
+
kinds.add(m.group(1).upper())
|
|
300
|
+
if how.startswith("AUTOMATIC"):
|
|
301
|
+
kinds.add("AUTOMATIC INDEX")
|
|
302
|
+
if "TEMP B-TREE" in d.upper():
|
|
303
|
+
kinds.add("TEMP B-TREE")
|
|
304
|
+
return plan, scans, sorted(kinds)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _head(stmt: str) -> str:
|
|
308
|
+
return re.sub(r"\s+", " ", stmt[:70])
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def plan_text(plan: list[dict]) -> str:
|
|
312
|
+
depth = {0: -1}
|
|
313
|
+
lines = []
|
|
314
|
+
for p in plan:
|
|
315
|
+
d = depth.get(p["parent"], -1) + 1
|
|
316
|
+
depth[p["id"]] = d
|
|
317
|
+
lines.append(" " * d + ("-> " if d else "") + p["detail"])
|
|
318
|
+
return "\n".join(lines)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class SqliteSandbox:
|
|
322
|
+
engine = "sqlite"
|
|
323
|
+
label = "SQLite"
|
|
324
|
+
copy_kinds = ("column_type",)
|
|
325
|
+
pages_decide = True # pages asked of the pager decide; full-scan rows are stated beside them (bench.verdict)
|
|
326
|
+
floor_rows = 200
|
|
327
|
+
floor_bytes = 16 * 4096 # set again from the page size on start
|
|
328
|
+
statement_timeout_s: float = MAX_QUERY_SECONDS
|
|
329
|
+
runtime = "in-process"
|
|
330
|
+
|
|
331
|
+
def __init__(self, version: str = "", name: str | None = None, runtime: str | None = None, work_dir: str | None = None):
|
|
332
|
+
self.requested_version = version
|
|
333
|
+
self.work_dir = work_dir
|
|
334
|
+
self.dir = ""
|
|
335
|
+
self.path = ""
|
|
336
|
+
self.conn: sqlite3.Connection | None = None
|
|
337
|
+
self.meter: Meter | None = None
|
|
338
|
+
self.page_size = 4096
|
|
339
|
+
self.floor_bytes = 16 * 4096
|
|
340
|
+
self.stripped: list[str] = []
|
|
341
|
+
self._deferred: dict[str, list[str]] = {}
|
|
342
|
+
self._notes: dict[str, list[str]] = {}
|
|
343
|
+
self._meta: dict[str, dict[str, dict]] = {}
|
|
344
|
+
self._load_notes: dict[str, list[str]] = {}
|
|
345
|
+
self._real: dict[str, str] = {}
|
|
346
|
+
self._before: set[tuple[str, str]] | None = None
|
|
347
|
+
self.clock: str | None = None
|
|
348
|
+
self.started_epoch = int(time.time())
|
|
349
|
+
|
|
350
|
+
# ---- lifecycle ------------------------------------------------------
|
|
351
|
+
def start(self) -> None:
|
|
352
|
+
base = self.work_dir or None
|
|
353
|
+
if base:
|
|
354
|
+
os.makedirs(base, exist_ok=True)
|
|
355
|
+
self.dir = tempfile.mkdtemp(prefix="codecop-sqlite-", dir=base)
|
|
356
|
+
self.path = os.path.join(self.dir, "sandbox.db")
|
|
357
|
+
try:
|
|
358
|
+
self.conn = sqlite3.connect(self.path, isolation_level=None, check_same_thread=False)
|
|
359
|
+
self.conn.execute(f"PRAGMA page_size = {self.page_size}")
|
|
360
|
+
# durability off while loading: the data is disposable. None of these change a plan.
|
|
361
|
+
self.conn.execute("PRAGMA journal_mode = OFF")
|
|
362
|
+
self.conn.execute("PRAGMA synchronous = OFF")
|
|
363
|
+
self.conn.execute("PRAGMA temp_store = MEMORY")
|
|
364
|
+
for fname, (n, fn) in FUNCTIONS.items():
|
|
365
|
+
self.conn.create_function(fname, n, fn, deterministic=True)
|
|
366
|
+
self.conn.execute("CREATE TABLE IF NOT EXISTS codecop_probe (x)")
|
|
367
|
+
self.conn.execute("DROP TABLE codecop_probe")
|
|
368
|
+
self.page_size = int(self.conn.execute("PRAGMA page_size").fetchone()[0])
|
|
369
|
+
self.floor_bytes = 16 * self.page_size
|
|
370
|
+
self.meter = Meter(self.path)
|
|
371
|
+
except Exception:
|
|
372
|
+
self.stop()
|
|
373
|
+
raise
|
|
374
|
+
|
|
375
|
+
def stop(self) -> None:
|
|
376
|
+
if self.meter is not None:
|
|
377
|
+
self.meter.close()
|
|
378
|
+
self.meter = None
|
|
379
|
+
if self.conn is not None:
|
|
380
|
+
try:
|
|
381
|
+
self.conn.close()
|
|
382
|
+
except sqlite3.Error:
|
|
383
|
+
pass
|
|
384
|
+
self.conn = None
|
|
385
|
+
if self.dir and os.path.isdir(self.dir):
|
|
386
|
+
shutil.rmtree(self.dir, ignore_errors=True)
|
|
387
|
+
|
|
388
|
+
def __enter__(self) -> "SqliteSandbox":
|
|
389
|
+
self.start()
|
|
390
|
+
return self
|
|
391
|
+
|
|
392
|
+
def __exit__(self, *exc) -> None:
|
|
393
|
+
self.stop()
|
|
394
|
+
|
|
395
|
+
def revive(self, timeout_s: int = 0) -> str:
|
|
396
|
+
"""Nothing to bring back: the database is a file in this process."""
|
|
397
|
+
return ""
|
|
398
|
+
|
|
399
|
+
def server_version(self) -> str:
|
|
400
|
+
return self.meter.version if self.meter else sqlite3.sqlite_version
|
|
401
|
+
|
|
402
|
+
def set_statement_timeout(self, seconds: float) -> None:
|
|
403
|
+
self.statement_timeout_s = max(float(seconds), 0.001)
|
|
404
|
+
|
|
405
|
+
# ---- statements -----------------------------------------------------
|
|
406
|
+
def _run(self, sql: str, fetch: bool = False):
|
|
407
|
+
deadline = time.monotonic() + self.statement_timeout_s * 10 # loads get ten times a query's time
|
|
408
|
+
self.conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 100_000)
|
|
409
|
+
try:
|
|
410
|
+
cur = self.conn.execute(sql)
|
|
411
|
+
return cur.fetchall() if fetch else None
|
|
412
|
+
except sqlite3.OperationalError as e:
|
|
413
|
+
raise QueryError(str(e)) from e
|
|
414
|
+
except (sqlite3.DatabaseError, sqlite3.Warning, sqlite3.ProgrammingError) as e:
|
|
415
|
+
raise QueryError(str(e)) from e
|
|
416
|
+
finally:
|
|
417
|
+
self.conn.set_progress_handler(None, 0)
|
|
418
|
+
|
|
419
|
+
def execute(self, sql: str, params: dict | None = None, settings: dict | None = None) -> str:
|
|
420
|
+
self._run(self.frozen(render_params(sql.strip().rstrip(";"), params)))
|
|
421
|
+
return ""
|
|
422
|
+
|
|
423
|
+
def rows(self, sql: str, params: dict | None = None) -> list[dict]:
|
|
424
|
+
text = self.frozen(render_params(sql.strip().rstrip(";"), params))
|
|
425
|
+
deadline = time.monotonic() + self.statement_timeout_s
|
|
426
|
+
self.conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 100_000)
|
|
427
|
+
try:
|
|
428
|
+
cur = self.conn.execute(text)
|
|
429
|
+
names = [d[0] for d in cur.description or []]
|
|
430
|
+
return [dict(zip(names, r)) for r in cur.fetchall()]
|
|
431
|
+
except sqlite3.Error as e:
|
|
432
|
+
raise QueryError(str(e)) from e
|
|
433
|
+
finally:
|
|
434
|
+
self.conn.set_progress_handler(None, 0)
|
|
435
|
+
|
|
436
|
+
def _try(self, sql: str) -> str:
|
|
437
|
+
try:
|
|
438
|
+
self._run(sql)
|
|
439
|
+
return ""
|
|
440
|
+
except QueryError as e:
|
|
441
|
+
return str(e)
|
|
442
|
+
|
|
443
|
+
def _note(self, table: str, text: str) -> None:
|
|
444
|
+
self._notes.setdefault(table, [])
|
|
445
|
+
if text not in self._notes[table]:
|
|
446
|
+
self._notes[table].append(text)
|
|
447
|
+
self.stripped.append(f"{table}: {text}")
|
|
448
|
+
|
|
449
|
+
def _name(self, name: str) -> str:
|
|
450
|
+
bare = name.replace('"', "").replace("`", "").split(".")[-1]
|
|
451
|
+
return self._real.get(bare.lower(), bare)
|
|
452
|
+
|
|
453
|
+
def _q(self, name: str) -> str:
|
|
454
|
+
return '"' + self._name(name).replace('"', '""') + '"'
|
|
455
|
+
|
|
456
|
+
# ---- tables ---------------------------------------------------------
|
|
457
|
+
def create_table(self, definition: dict | str) -> list[str]:
|
|
458
|
+
"""Drop and rebuild one table: its CREATE TABLE, then its unique indexes; other indexes wait for finish_table.
|
|
459
|
+
|
|
460
|
+
Kept as written: types, defaults, NOT NULL, primary keys, unique constraints, WITHOUT ROWID, STRICT. Left out and
|
|
461
|
+
said: FOREIGN KEY and REFERENCES (the sandbox keeps PRAGMA foreign_keys off, as SQLite does by default) and CHECK
|
|
462
|
+
constraints (generated data does not honour them, and with INSERT OR IGNORE a row that broke one would be
|
|
463
|
+
dropped without a word), triggers. A view the definition creates is created after the table."""
|
|
464
|
+
if isinstance(definition, str):
|
|
465
|
+
first = parse_table(normalize_ddl(split_statements(definition)[0]))
|
|
466
|
+
definition = {"name": first.name if first else "t", "create_sql": definition}
|
|
467
|
+
given = definition["name"].replace('"', "").replace("`", "").split(".")[-1]
|
|
468
|
+
name = given
|
|
469
|
+
script = normalize_ddl(definition.get("create_sql") or "")
|
|
470
|
+
statements = split_statements(script)
|
|
471
|
+
for stmt in statements:
|
|
472
|
+
if statement_kind(stmt) == "table":
|
|
473
|
+
t = parse_table(stmt)
|
|
474
|
+
if t and t.name.split(".")[-1].lower() == given.lower():
|
|
475
|
+
name = t.name.split(".")[-1]
|
|
476
|
+
break
|
|
477
|
+
self._real[given.lower()] = name
|
|
478
|
+
self._real[name.lower()] = name
|
|
479
|
+
self._notes[name], self._deferred[name] = [], []
|
|
480
|
+
self._run(f"DROP TABLE IF EXISTS {self._q(name)}")
|
|
481
|
+
created = False
|
|
482
|
+
later: list[str] = []
|
|
483
|
+
for stmt in statements:
|
|
484
|
+
kind = statement_kind(stmt)
|
|
485
|
+
head = re.sub(r"\s+", " ", stmt[:70])
|
|
486
|
+
low = stmt.lstrip().upper()
|
|
487
|
+
if kind == "comment" or low.startswith("PRAGMA"):
|
|
488
|
+
continue
|
|
489
|
+
if kind == "table":
|
|
490
|
+
t = parse_table(stmt)
|
|
491
|
+
if t and t.name.split(".")[-1].lower() != name.lower():
|
|
492
|
+
self._note(name, f"left out `{head}` (another table)")
|
|
493
|
+
continue
|
|
494
|
+
stmt, notes = strip_constraints(stmt)
|
|
495
|
+
for n in notes:
|
|
496
|
+
self._note(name, n + " (SQLite does not enforce foreign keys unless the application turns them on)"
|
|
497
|
+
if n.startswith(tuple("0123456789")) and "foreign key" in n else n)
|
|
498
|
+
stmt = re.sub(r"^(\s*CREATE\s+)(?:(?:TEMP|TEMPORARY)\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:\"?\w+\"?\.)?",
|
|
499
|
+
r"\1TABLE IF NOT EXISTS ", stmt, count=1, flags=re.I)
|
|
500
|
+
error = self._try(stmt)
|
|
501
|
+
if error:
|
|
502
|
+
raise QueryError(error)
|
|
503
|
+
created = True
|
|
504
|
+
elif kind == "unique_index":
|
|
505
|
+
error = self._try(self._index_on_main(stmt))
|
|
506
|
+
if error:
|
|
507
|
+
self._note(name, f"index left out (`{head}`): {error.splitlines()[0][:160]}")
|
|
508
|
+
elif kind == "index":
|
|
509
|
+
self._deferred[name].append(self._index_on_main(stmt))
|
|
510
|
+
elif re.match(r"CREATE\s+VIRTUAL\s+TABLE\b", low):
|
|
511
|
+
error = self._try(stmt)
|
|
512
|
+
if error:
|
|
513
|
+
self._note(name, f"could not run `{head}`: {error[:160]}")
|
|
514
|
+
created = created or not error
|
|
515
|
+
elif re.match(r"CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?VIEW\b", low):
|
|
516
|
+
later.append(stmt)
|
|
517
|
+
elif re.match(r"CREATE\s+(?:TEMP\s+|TEMPORARY\s+)?TRIGGER\b", low):
|
|
518
|
+
self._note(name, f"left out `{head}` (a trigger)")
|
|
519
|
+
elif kind == "alter":
|
|
520
|
+
error = self._try(stmt)
|
|
521
|
+
if error:
|
|
522
|
+
self._note(name, f"could not run `{head}`: {error[:160]}")
|
|
523
|
+
else:
|
|
524
|
+
self._note(name, f"left out `{head}` (not a table, index or view)")
|
|
525
|
+
if not created:
|
|
526
|
+
raise QueryError(f"no CREATE TABLE statement for {name} in its definition")
|
|
527
|
+
for stmt in later:
|
|
528
|
+
error = self._try(re.sub(r"^(\s*CREATE\s+)(?:TEMP\s+|TEMPORARY\s+)?VIEW\s+(?:IF\s+NOT\s+EXISTS\s+)?", r"\1VIEW IF NOT EXISTS ",
|
|
529
|
+
stmt, count=1, flags=re.I))
|
|
530
|
+
if error:
|
|
531
|
+
self._note(name, f"view left out (`{_head(stmt)}`): {error[:160]}")
|
|
532
|
+
return list(self._notes[name])
|
|
533
|
+
|
|
534
|
+
@staticmethod
|
|
535
|
+
def _index_on_main(stmt: str) -> str:
|
|
536
|
+
"""A schema qualifier (temp., main.) on the index or table name is dropped: the sandbox has one database."""
|
|
537
|
+
stmt = re.sub(r"(\bINDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?)\"?(?:temp|main)\"?\.", r"\1", stmt, count=1, flags=re.I)
|
|
538
|
+
return re.sub(r"(\bON\s+)\"?(?:temp|main)\"?\.", r"\1", stmt, count=1, flags=re.I)
|
|
539
|
+
|
|
540
|
+
def column_types(self, name: str) -> dict[str, str]:
|
|
541
|
+
name = self._name(name)
|
|
542
|
+
cols = self._run(f"PRAGMA table_xinfo({self._q(name)})", fetch=True) or []
|
|
543
|
+
pks = [c for c in cols if c[5]]
|
|
544
|
+
without_rowid = bool(self._run(f"SELECT 1 FROM sqlite_master WHERE name = '{name}' AND sql LIKE '%WITHOUT%ROWID%'", fetch=True))
|
|
545
|
+
uniques = set()
|
|
546
|
+
for ix in self._run(f"PRAGMA index_list({self._q(name)})", fetch=True) or []:
|
|
547
|
+
# (seq, name, unique, origin, partial)
|
|
548
|
+
if ix[2] and not ix[4]:
|
|
549
|
+
info = self._run(f"PRAGMA index_info(\"{ix[1]}\")", fetch=True) or []
|
|
550
|
+
if len(info) == 1 and info[0][2]:
|
|
551
|
+
uniques.add(info[0][2])
|
|
552
|
+
meta = {}
|
|
553
|
+
for cid, col, typ, notnull, default, pk, hidden in cols:
|
|
554
|
+
meta[col] = {"name": col, "type": typ or "", "notnull": bool(notnull) or (bool(pk) and without_rowid),
|
|
555
|
+
"has_default": default is not None, "default": default or "",
|
|
556
|
+
"rowid": bool(pk) and len(pks) == 1 and (typ or "").upper() == "INTEGER" and not without_rowid,
|
|
557
|
+
"generated": hidden in (2, 3), "unique_alone": col in uniques or (bool(pk) and len(pks) == 1)}
|
|
558
|
+
self._meta[name] = meta
|
|
559
|
+
return {c[1]: c[2] or "" for c in cols if c[6] in (0, 2, 3)}
|
|
560
|
+
|
|
561
|
+
def insert_statements(self, name: str, rows: int, columns: list[dict], types: dict[str, str], *,
|
|
562
|
+
fixtures: list[dict] | None = None, placed: dict | None = None, relations: list[dict] | None = None) -> list[str]:
|
|
563
|
+
from ..datagen import REALISM
|
|
564
|
+
from ..datagen_sqlite import insert_statements
|
|
565
|
+
name = self._name(name)
|
|
566
|
+
notes: list[str] = []
|
|
567
|
+
out = insert_statements(name, rows, columns, types, clock=self.started_epoch, fixtures=fixtures, placed=placed,
|
|
568
|
+
meta=self._meta.get(name), realism=tuple(getattr(self, "realism", REALISM)), notes=notes)
|
|
569
|
+
self._load_notes[name] = notes
|
|
570
|
+
return out
|
|
571
|
+
|
|
572
|
+
def load(self, name: str, statements: list[str]) -> None:
|
|
573
|
+
for stmt in statements:
|
|
574
|
+
self._run("BEGIN")
|
|
575
|
+
try:
|
|
576
|
+
self._run(stmt)
|
|
577
|
+
self._run("COMMIT")
|
|
578
|
+
except QueryError:
|
|
579
|
+
self._try("ROLLBACK")
|
|
580
|
+
raise
|
|
581
|
+
|
|
582
|
+
def finish_table(self, definition: dict) -> dict:
|
|
583
|
+
"""After the load: build the remaining indexes. No ANALYZE: an application rarely runs it, and without
|
|
584
|
+
sqlite_stat1 the planner uses its own estimates, as it does there (said in the engine's limits)."""
|
|
585
|
+
name = self._name(definition["name"])
|
|
586
|
+
built = 0
|
|
587
|
+
for stmt in self._deferred.pop(name, []):
|
|
588
|
+
error = self._try(stmt)
|
|
589
|
+
if error:
|
|
590
|
+
self._note(name, f"index left out (`{_head(stmt)}`): {error[:160]}")
|
|
591
|
+
else:
|
|
592
|
+
built += 1
|
|
593
|
+
out: dict = {"indexes_built_after_load": built}
|
|
594
|
+
if self._notes.get(name):
|
|
595
|
+
out["stripped"] = list(self._notes[name])
|
|
596
|
+
missing = [n for n in self._notes.get(name) or [] if n.startswith("index left out")]
|
|
597
|
+
if missing:
|
|
598
|
+
out["indexes_left_out"] = missing
|
|
599
|
+
if self._load_notes.get(name):
|
|
600
|
+
out["generator_notes"] = list(self._load_notes[name])
|
|
601
|
+
return out
|
|
602
|
+
|
|
603
|
+
def _objects(self) -> set[tuple[str, str]]:
|
|
604
|
+
return {(r[0], r[1]) for r in self._run("SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'", fetch=True) or []}
|
|
605
|
+
|
|
606
|
+
def table_stats(self, table: str) -> dict:
|
|
607
|
+
name = self._name(table)
|
|
608
|
+
rows = int((self._run(f"SELECT count(*) FROM {self._q(name)}", fetch=True) or [[0]])[0][0])
|
|
609
|
+
indexes = [r[0] for r in self._run(f"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = '{name}'", fetch=True) or []]
|
|
610
|
+
out = {"rows": rows, "indexes": len(indexes), "page_size": self.page_size}
|
|
611
|
+
try:
|
|
612
|
+
heap = int((self._run(f"SELECT coalesce(sum(pgsize), 0) FROM dbstat WHERE name = '{name}'", fetch=True) or [[0]])[0][0])
|
|
613
|
+
idx = int((self._run("SELECT coalesce(sum(pgsize), 0) FROM dbstat WHERE name IN (SELECT name FROM sqlite_master "
|
|
614
|
+
f"WHERE type = 'index' AND tbl_name = '{name}')", fetch=True) or [[0]])[0][0])
|
|
615
|
+
out.update(bytes_on_disk=heap + idx, heap_bytes=heap, index_bytes=idx)
|
|
616
|
+
except QueryError: # a library built without the dbstat table
|
|
617
|
+
out["bytes_on_disk"] = self.storage_bytes([], [])
|
|
618
|
+
return out
|
|
619
|
+
|
|
620
|
+
def free_bytes(self) -> int:
|
|
621
|
+
try:
|
|
622
|
+
return int(shutil.disk_usage(self.dir or tempfile.gettempdir()).free)
|
|
623
|
+
except OSError:
|
|
624
|
+
return 0
|
|
625
|
+
|
|
626
|
+
# ---- variants -------------------------------------------------------
|
|
627
|
+
def storage_bytes(self, tables: list[str], setup_sql: list[str]) -> int:
|
|
628
|
+
pages = int(self._run("PRAGMA page_count", fetch=True)[0][0]) - int(self._run("PRAGMA freelist_count", fetch=True)[0][0])
|
|
629
|
+
return pages * self.page_size
|
|
630
|
+
|
|
631
|
+
def apply_setup(self, statements: list[str]) -> None:
|
|
632
|
+
self._before = self._objects()
|
|
633
|
+
for script in statements or []:
|
|
634
|
+
for stmt in split_statements(normalize_ddl(script)):
|
|
635
|
+
if not stmt.strip():
|
|
636
|
+
continue
|
|
637
|
+
error = self._try(re.sub(r"\bCONCURRENTLY\s+", "", self._index_on_main(stmt), count=1, flags=re.I))
|
|
638
|
+
if error:
|
|
639
|
+
raise QueryError(error)
|
|
640
|
+
|
|
641
|
+
def undo_setup(self, statements: list[str]) -> None:
|
|
642
|
+
if self._before is None:
|
|
643
|
+
return
|
|
644
|
+
new = self._objects() - self._before
|
|
645
|
+
self._before = None
|
|
646
|
+
order = {"trigger": 0, "view": 1, "index": 2, "table": 3}
|
|
647
|
+
for kind, name in sorted(new, key=lambda kn: order.get(kn[0], 9)):
|
|
648
|
+
self._try(f'DROP {kind.upper()} IF EXISTS "{name}"')
|
|
649
|
+
|
|
650
|
+
# ---- the clock ------------------------------------------------------
|
|
651
|
+
def freeze_clock(self) -> str:
|
|
652
|
+
"""Every reading of the clock in a measured statement ('now', CURRENT_TIMESTAMP, unixepoch()) is one instant from
|
|
653
|
+
here on: the one the data was generated against."""
|
|
654
|
+
self.clock = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(self.started_epoch))
|
|
655
|
+
return self.clock
|
|
656
|
+
|
|
657
|
+
def frozen(self, sql: str) -> str:
|
|
658
|
+
if not self.clock:
|
|
659
|
+
return sql
|
|
660
|
+
ts, day, tod = self.clock, self.clock[:10], self.clock[11:]
|
|
661
|
+
sql = NOW_ARG.sub(lambda m: m.group(1) + f"'{ts}'", sql)
|
|
662
|
+
|
|
663
|
+
def change(text: str) -> str:
|
|
664
|
+
text = UNIXEPOCH_NOW.sub(str(self.started_epoch), text)
|
|
665
|
+
return CLOCK_WORDS.sub(lambda m: {"CURRENT_TIMESTAMP": f"'{ts}'", "CURRENT_DATE": f"'{day}'",
|
|
666
|
+
"CURRENT_TIME": f"'{tod}'"}[m.group(0).upper()], text)
|
|
667
|
+
return outside_quotes(sql, change)
|
|
668
|
+
|
|
669
|
+
# ---- measurement ----------------------------------------------------
|
|
670
|
+
def measure(self, sql: str, params: dict | None = None, runs: int = 3) -> SqliteMeasurement:
|
|
671
|
+
"""Run a SELECT on the measuring connection: one warm-up, then `runs` timed runs. The counters are the last run's."""
|
|
672
|
+
text = self.frozen(render_params(sql.strip().rstrip(";"), params))
|
|
673
|
+
m = SqliteMeasurement(ok=False, page_size=self.page_size)
|
|
674
|
+
try:
|
|
675
|
+
plan_rows = self._run(f"EXPLAIN QUERY PLAN {text}", fetch=True) or []
|
|
676
|
+
m.plan, m.scans, m.node_types = read_plan(plan_rows)
|
|
677
|
+
self.meter.run(text, self.statement_timeout_s)
|
|
678
|
+
timed = [self.meter.run(text, self.statement_timeout_s) for _ in range(max(runs, 1))]
|
|
679
|
+
last = timed[-1]
|
|
680
|
+
m.repeatable = len({t.pages for t in timed}) == 1
|
|
681
|
+
m.pages, m.full_scan_rows, m.vm_steps, m.sorts, m.autoindexes = last.pages, last.full_scan_rows, last.vm_steps, last.sorts, last.autoindexes
|
|
682
|
+
m.read_bytes = last.pages * self.page_size
|
|
683
|
+
m.read_rows = last.full_scan_rows
|
|
684
|
+
m.result_rows = last.rows
|
|
685
|
+
m.runs = [round(t.ms, 3) for t in timed]
|
|
686
|
+
m.duration_ms = min(m.runs)
|
|
687
|
+
# SQLite's CPU work is its VM steps (exact, repeats); its memory the library's high-water mark during the run
|
|
688
|
+
fill_resources(m, [{"memory_bytes": t.memory_bytes, "duration_ms": round(t.ms, 3)} for t in timed], "vm_steps", "highwater")
|
|
689
|
+
m.cpu_kind = "vm_steps"
|
|
690
|
+
highs = sorted(t.memory_bytes for t in timed if t.memory_bytes is not None)
|
|
691
|
+
if highs:
|
|
692
|
+
m.memory_bytes = highs[len(highs) // 2]
|
|
693
|
+
m.explain = plan_text(m.plan) + (f"\n(pages {m.pages}, full-scan rows {m.full_scan_rows}, vm steps {m.vm_steps}, "
|
|
694
|
+
f"sorts {m.sorts}, automatic index rows {m.autoindexes})")
|
|
695
|
+
m.result_hash = self.result_hash(text)
|
|
696
|
+
m.ok = True
|
|
697
|
+
except QueryError as e:
|
|
698
|
+
m.error = str(e)
|
|
699
|
+
return m
|
|
700
|
+
|
|
701
|
+
def sample(self, statements: list[tuple[str, dict | None]]) -> list[dict]:
|
|
702
|
+
"""Run each statement once, in the order given: its VM steps (SQLite's CPU work), memory high-water and time."""
|
|
703
|
+
out = []
|
|
704
|
+
for sql, params in statements:
|
|
705
|
+
got = self.meter.run(self.frozen(render_params(sql.strip().rstrip(";"), params)), self.statement_timeout_s)
|
|
706
|
+
out.append({"vm_steps": got.vm_steps, "memory_bytes": got.memory_bytes, "duration_ms": round(got.ms, 3)})
|
|
707
|
+
return out
|
|
708
|
+
|
|
709
|
+
def measure_many(self, sql: str, plist: list[dict]) -> Measurement:
|
|
710
|
+
"""One statement run once per parameter set (a loop's N statements), its counters summed. No warm-up: the
|
|
711
|
+
counters do not depend on what is cached."""
|
|
712
|
+
m = SqliteMeasurement(ok=True, page_size=self.page_size)
|
|
713
|
+
try:
|
|
714
|
+
for p in plist:
|
|
715
|
+
got = self.meter.run(self.frozen(render_params(sql.strip().rstrip(";"), p)), self.statement_timeout_s)
|
|
716
|
+
m.pages += got.pages
|
|
717
|
+
m.full_scan_rows += got.full_scan_rows
|
|
718
|
+
m.vm_steps += got.vm_steps
|
|
719
|
+
m.sorts += got.sorts
|
|
720
|
+
m.autoindexes += got.autoindexes
|
|
721
|
+
m.result_rows += got.rows
|
|
722
|
+
m.duration_ms += got.ms
|
|
723
|
+
except QueryError as e:
|
|
724
|
+
m.ok, m.error = False, str(e)
|
|
725
|
+
m.read_bytes, m.read_rows = m.pages * self.page_size, m.full_scan_rows
|
|
726
|
+
return m
|
|
727
|
+
|
|
728
|
+
def result_hash(self, sql: str, params: dict | None = None) -> str:
|
|
729
|
+
"""Hash of the result ignoring row order: the row count plus a sum of per-row hashes."""
|
|
730
|
+
text = self.frozen(render_params(sql.strip().rstrip(";"), params))
|
|
731
|
+
deadline = time.monotonic() + self.statement_timeout_s
|
|
732
|
+
self.conn.set_progress_handler(lambda: 1 if time.monotonic() > deadline else 0, 100_000)
|
|
733
|
+
try:
|
|
734
|
+
n, total = 0, 0
|
|
735
|
+
for row in self.conn.execute(text):
|
|
736
|
+
n += 1
|
|
737
|
+
total = (total + int.from_bytes(hashlib.sha1(json.dumps(list(row), default=repr).encode()).digest()[:8], "big")) & _M64
|
|
738
|
+
except sqlite3.Error as e:
|
|
739
|
+
raise QueryError(str(e)) from e
|
|
740
|
+
finally:
|
|
741
|
+
self.conn.set_progress_handler(None, 0)
|
|
742
|
+
return hashlib.sha1(f"{n}|{total}".encode()).hexdigest()[:16]
|