sqlprove 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.
sqlprove/fuzzer.py ADDED
@@ -0,0 +1,312 @@
1
+ """DuckDB concrete counterexample confirmation and randomized differential fuzzing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import Counter
6
+ import datetime as dt
7
+ import random
8
+ from typing import Any
9
+
10
+ import duckdb
11
+ import sqlglot
12
+
13
+ from sqlprove.schema import ColumnSpec, Schema, TableSpec
14
+
15
+ _EPOCH_DATE = dt.date(1970, 1, 1)
16
+ _EPOCH_DT = dt.datetime(1970, 1, 1, 0, 0, 0)
17
+
18
+
19
+ def _to_duckdb_sql(sql: str, dialect: str, schema: Schema | None = None) -> str:
20
+ ast = sqlglot.parse_one(sql, read=dialect)
21
+ if schema is not None:
22
+ # Strip warehouse catalog/database qualifiers on base tables loaded locally in DuckDB
23
+ for tbl in ast.find_all(sqlglot.exp.Table):
24
+ if tbl.name and (tbl.catalog or tbl.db) and schema.has_table(tbl.name):
25
+ tbl.set("catalog", None)
26
+ tbl.set("db", None)
27
+ duck_sql = ast.sql(dialect="duckdb")
28
+ # Normalize Snowflake / BigQuery 2-row cross-join idioms for DuckDB execution
29
+ duck_sql = duck_sql.replace(
30
+ "CROSS JOIN (SELECT column1 AS _branch FROM (VALUES (0), (1))) AS _s",
31
+ "CROSS JOIN (VALUES (0), (1)) AS _s(_branch)",
32
+ )
33
+ return duck_sql
34
+
35
+
36
+ def _duckdb_col_type(col: ColumnSpec) -> str:
37
+ ct = col.canonical_dtype
38
+ if ct == "BOOL":
39
+ return "BOOLEAN"
40
+ if ct == "STRING":
41
+ return "VARCHAR"
42
+ if ct == "DATE":
43
+ return "DATE"
44
+ if ct == "TIMESTAMP":
45
+ return "TIMESTAMP"
46
+ return "BIGINT"
47
+
48
+
49
+ def _coerce_value_for_duckdb(col: ColumnSpec, val: Any) -> Any:
50
+ if val is None:
51
+ return None
52
+ ct = col.canonical_dtype
53
+ if ct == "BOOL":
54
+ return bool(val)
55
+ if ct == "STRING":
56
+ return str(val)
57
+ if ct == "DATE":
58
+ if isinstance(val, dt.date) and not isinstance(val, dt.datetime):
59
+ return val
60
+ if isinstance(val, int):
61
+ return _EPOCH_DATE + dt.timedelta(days=val)
62
+ return dt.date.fromisoformat(str(val))
63
+ if ct == "TIMESTAMP":
64
+ if isinstance(val, dt.datetime):
65
+ return val
66
+ if isinstance(val, int):
67
+ return _EPOCH_DT + dt.timedelta(seconds=val)
68
+ return dt.datetime.fromisoformat(str(val))
69
+ return int(val)
70
+
71
+
72
+ def _load_tables(
73
+ con: duckdb.DuckDBPyConnection,
74
+ schema: Schema,
75
+ tables_data: dict[str, list[dict[str, Any]]],
76
+ ) -> None:
77
+ for tname, tspec in schema.tables.items():
78
+ col_defs = ", ".join(f'"{c.name}" {_duckdb_col_type(c)}' for c in tspec.columns)
79
+ con.execute(f'CREATE TABLE "{tname}" ({col_defs})')
80
+ rows = tables_data.get(tname, [])
81
+ if rows:
82
+ placeholders = ", ".join(["?"] * len(tspec.columns))
83
+ col_list = ", ".join(f'"{c.name}"' for c in tspec.columns)
84
+ tuples = [
85
+ tuple(_coerce_value_for_duckdb(c, r.get(c.name)) for c in tspec.columns)
86
+ for r in rows
87
+ ]
88
+ con.executemany(f'INSERT INTO "{tname}" ({col_list}) VALUES ({placeholders})', tuples)
89
+
90
+
91
+ def _normalize_cell(v: Any) -> Any:
92
+ if v is None:
93
+ return None
94
+ if isinstance(v, bool):
95
+ return bool(v)
96
+ if isinstance(v, dt.datetime):
97
+ return ("TS", v.isoformat())
98
+ if isinstance(v, dt.date):
99
+ return ("DATE", v.isoformat())
100
+ return v
101
+
102
+
103
+ def _normalize_row(row: tuple[Any, ...]) -> tuple[Any, ...]:
104
+ return tuple(_normalize_cell(v) for v in row)
105
+
106
+
107
+ def confirm_counterexample_in_duckdb(
108
+ q1_sql: str,
109
+ q2_sql: str,
110
+ schema: Schema,
111
+ tables_data: dict[str, list[dict[str, Any]]],
112
+ *,
113
+ dialect: str = "duckdb",
114
+ ) -> tuple[bool, list[tuple[Any, ...]], list[tuple[Any, ...]]]:
115
+ """Execute q1 and q2 on concrete tables in DuckDB; return (differs, rows1, rows2)."""
116
+ con = duckdb.connect(":memory:")
117
+ try:
118
+ _load_tables(con, schema, tables_data)
119
+ d1 = _to_duckdb_sql(q1_sql, dialect, schema)
120
+ d2 = _to_duckdb_sql(q2_sql, dialect, schema)
121
+ rows1 = [_normalize_row(r) for r in con.execute(d1).fetchall()]
122
+ rows2 = [_normalize_row(r) for r in con.execute(d2).fetchall()]
123
+ return Counter(rows1) != Counter(rows2), rows1, rows2
124
+ finally:
125
+ con.close()
126
+
127
+
128
+ def _topo_sort_tables(schema: Schema) -> list[str]:
129
+ """Order tables so FK target tables are populated before referencing tables."""
130
+ visited: set[str] = set()
131
+ order: list[str] = []
132
+
133
+ def dfs(name: str, stack: set[str]) -> None:
134
+ if name in visited or name in stack:
135
+ return
136
+ stack.add(name)
137
+ tspec = schema.tables[name]
138
+ for fk in tspec.foreign_keys:
139
+ if schema.has_table(fk.ref_table):
140
+ ref_actual = schema.get_table(fk.ref_table).name
141
+ if ref_actual != name:
142
+ dfs(ref_actual, stack)
143
+ stack.remove(name)
144
+ visited.add(name)
145
+ order.append(name)
146
+
147
+ for tname in schema.tables:
148
+ dfs(tname, set())
149
+ return order
150
+
151
+
152
+ def _random_value(col: ColumnSpec, rng: random.Random, extra_strings: list[str]) -> Any:
153
+ ct = col.canonical_dtype
154
+ if ct == "BOOL":
155
+ return rng.choice([False, True])
156
+ if ct == "STRING":
157
+ pool = ["", "a", "b", "paid", "pending", "refunded", *extra_strings]
158
+ return rng.choice(pool)
159
+ if ct == "DATE":
160
+ # Cluster around month/year/leap-day boundaries
161
+ base_days = [
162
+ (dt.date(2024, 2, 28) - _EPOCH_DATE).days,
163
+ (dt.date(2024, 2, 29) - _EPOCH_DATE).days,
164
+ (dt.date(2024, 3, 1) - _EPOCH_DATE).days,
165
+ (dt.date(2025, 12, 19) - _EPOCH_DATE).days,
166
+ (dt.date(2025, 12, 20) - _EPOCH_DATE).days,
167
+ (dt.date(2025, 12, 31) - _EPOCH_DATE).days,
168
+ (dt.date(2026, 1, 1) - _EPOCH_DATE).days,
169
+ ]
170
+ return rng.choice(base_days)
171
+ if ct == "TIMESTAMP":
172
+ # Cluster around exact midnight / 23:59:59 / 00:00:01 boundary timestamps!
173
+ samples = [
174
+ dt.datetime(2024, 2, 29, 23, 59, 59),
175
+ dt.datetime(2024, 3, 1, 0, 0, 0),
176
+ dt.datetime(2025, 11, 30, 23, 59, 59),
177
+ dt.datetime(2025, 12, 1, 0, 0, 0),
178
+ dt.datetime(2025, 12, 19, 23, 59, 59),
179
+ dt.datetime(2025, 12, 20, 0, 0, 0),
180
+ dt.datetime(2025, 12, 20, 0, 0, 1),
181
+ dt.datetime(2025, 12, 20, 12, 30, 0),
182
+ dt.datetime(2025, 12, 31, 23, 59, 59),
183
+ dt.datetime(2026, 1, 1, 0, 0, 0),
184
+ ]
185
+ return int((rng.choice(samples) - _EPOCH_DT).total_seconds())
186
+ return rng.choice([-1, 0, 1, 2, 5])
187
+
188
+
189
+ def _random_table(
190
+ tspec: TableSpec,
191
+ rng: random.Random,
192
+ max_rows: int,
193
+ populated: dict[str, list[dict[str, Any]]],
194
+ schema: Schema,
195
+ extra_strings: list[str],
196
+ ) -> list[dict[str, Any]]:
197
+ n = rng.randint(0, max_rows)
198
+ rows: list[dict[str, Any]] = []
199
+ unique_constraints = tspec.all_unique_constraints()
200
+
201
+ attempts = 0
202
+ while len(rows) < n and attempts < n * 15 + 15:
203
+ attempts += 1
204
+ rec: dict[str, Any] = {}
205
+ for col in tspec.columns:
206
+ if tspec.is_nullable(col.name) and rng.random() < 0.30:
207
+ rec[col.name] = None
208
+ else:
209
+ rec[col.name] = _random_value(col, rng, extra_strings)
210
+
211
+ # Enforce FOREIGN KEY constraints by sampling from already-populated parent rows
212
+ fk_ok = True
213
+ for fk in tspec.foreign_keys:
214
+ if not schema.has_table(fk.ref_table):
215
+ continue
216
+ ref_name = schema.get_table(fk.ref_table).name
217
+ ref_rows = populated.get(ref_name, [])
218
+ # If any FK col is nullable and already None, MATCH SIMPLE allows it
219
+ if any(rec[c] is None for c in fk.columns):
220
+ continue
221
+ valid_parent_tuples = [
222
+ tuple(pr[rc] for rc in fk.ref_columns)
223
+ for pr in ref_rows
224
+ if all(pr[rc] is not None for rc in fk.ref_columns)
225
+ ]
226
+ if not valid_parent_tuples:
227
+ # Can't satisfy non-null FK if parent table has no matching non-null row
228
+ if all(tspec.is_nullable(c) for c in fk.columns):
229
+ for c in fk.columns:
230
+ rec[c] = None
231
+ else:
232
+ fk_ok = False
233
+ break
234
+ else:
235
+ chosen = rng.choice(valid_parent_tuples)
236
+ for c, v in zip(fk.columns, chosen):
237
+ rec[c] = v
238
+ if not fk_ok:
239
+ continue
240
+
241
+ conflict = False
242
+ for uk in unique_constraints:
243
+ key = tuple(rec[c] for c in uk)
244
+ if any(v is None for v in key):
245
+ continue
246
+ if any(tuple(prev[c] for c in uk) == key for prev in rows):
247
+ conflict = True
248
+ break
249
+ if not conflict:
250
+ rows.append(rec)
251
+ return rows
252
+
253
+
254
+ def _extract_string_literals(sql: str, dialect: str) -> list[str]:
255
+ try:
256
+ ast = sqlglot.parse_one(sql, read=dialect)
257
+ return sorted({str(lit.this) for lit in ast.find_all(sqlglot.exp.Literal) if lit.is_string})
258
+ except Exception:
259
+ return []
260
+
261
+
262
+ def differential_fuzz(
263
+ q1_sql: str,
264
+ q2_sql: str,
265
+ schema: Schema,
266
+ *,
267
+ trials: int = 100,
268
+ max_rows: int = 6,
269
+ dialect: str = "duckdb",
270
+ seed: int = 20261204,
271
+ ) -> dict[str, Any] | None:
272
+ """Run randomized NULL/duplicate/FK-aware DuckDB fuzzing.
273
+
274
+ Returns None if all trials matched, or a dict with the first failing counterexample.
275
+ """
276
+ rng = random.Random(seed)
277
+ extra_strings = sorted(
278
+ set(_extract_string_literals(q1_sql, dialect)) | set(_extract_string_literals(q2_sql, dialect))
279
+ )
280
+ table_order = _topo_sort_tables(schema)
281
+ d1 = _to_duckdb_sql(q1_sql, dialect, schema)
282
+ d2 = _to_duckdb_sql(q2_sql, dialect, schema)
283
+
284
+ con = duckdb.connect(":memory:")
285
+ try:
286
+ for tname, tspec in schema.tables.items():
287
+ col_defs = ", ".join(f'"{c.name}" {_duckdb_col_type(c)}' for c in tspec.columns)
288
+ con.execute(f'CREATE TABLE "{tname}" ({col_defs})')
289
+
290
+ for trial in range(trials):
291
+ data: dict[str, list[dict[str, Any]]] = {}
292
+ for tname in table_order:
293
+ tspec = schema.tables[tname]
294
+ rows = _random_table(tspec, rng, max_rows, data, schema, extra_strings)
295
+ data[tname] = rows
296
+ con.execute(f'DELETE FROM "{tname}"')
297
+ if rows:
298
+ placeholders = ", ".join(["?"] * len(tspec.columns))
299
+ col_list = ", ".join(f'"{c.name}"' for c in tspec.columns)
300
+ tuples = [
301
+ tuple(_coerce_value_for_duckdb(c, r.get(c.name)) for c in tspec.columns)
302
+ for r in rows
303
+ ]
304
+ con.executemany(f'INSERT INTO "{tname}" ({col_list}) VALUES ({placeholders})', tuples)
305
+
306
+ r1 = [_normalize_row(r) for r in con.execute(d1).fetchall()]
307
+ r2 = [_normalize_row(r) for r in con.execute(d2).fetchall()]
308
+ if Counter(r1) != Counter(r2):
309
+ return {"trial": trial, "tables": data, "q1_rows": r1, "q2_rows": r2}
310
+ return None
311
+ finally:
312
+ con.close()