sql-agent-mcp 0.2.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.
@@ -0,0 +1,483 @@
1
+ # Golden set for the bundled sample database.
2
+ #
3
+ # Each case carries a reference SQL query written by hand against the real
4
+ # schema and verified by running it. Scoring does NOT compare the agent's
5
+ # prose, and does not compare its SQL text either — two correct queries rarely
6
+ # look alike. It runs the agent's final SQL and the reference query against the
7
+ # same database and compares the *result sets*.
8
+ #
9
+ # Fields:
10
+ # id stable, referred to by --only and by the README
11
+ # question asked verbatim, in the language a user would ask it
12
+ # traps what the case is actually testing; a case with no trap is
13
+ # there to check the agent doesn't over-think the easy ones
14
+ # ordered true when the ranking is part of the answer. Left out, row
15
+ # order is not graded, because a question that never asked for
16
+ # an order cannot be wrong about it
17
+ # ambiguous true when the question has more than one defensible reading.
18
+ # The reference encodes one of them and these cases are
19
+ # reported apart from the headline accuracy: they measure the
20
+ # question at least as much as the agent
21
+ # reference_sql SQLite, since that is what the sample database is
22
+ #
23
+ # Every result set here is 50 rows or fewer on purpose. `run_sql` shows the
24
+ # agent at most 50, so a wider case would grade it on rows it never saw.
25
+ #
26
+ # `ordered` is left off wherever the reference has tied values at or before the
27
+ # cut, even when the question reads like a ranking. Two equally correct queries
28
+ # break a tie differently, and a grader that fails one of them is measuring its
29
+ # own ORDER BY. Every ordered case here was checked for ties by running it.
30
+ #
31
+ # To evaluate against your own database, write your own file in this shape and
32
+ # point `--golden` or the `evaluate` MCP tool at it.
33
+
34
+ # --- the easy ones, to check the agent doesn't over-think -------------------
35
+
36
+ - id: count_orders
37
+ question: "How many orders are in the database?"
38
+ traps: []
39
+ reference_sql: "SELECT count(*) AS n FROM orders"
40
+
41
+ - id: count_customers_who_ordered
42
+ question: "How many different customers have placed at least one order?"
43
+ traps: [distinct_count]
44
+ reference_sql: "SELECT count(DISTINCT customer_id) AS n FROM orders"
45
+
46
+ - id: unresolved_high_tickets
47
+ question: "How many high-severity support tickets are still unresolved?"
48
+ traps: [distractor_table, boolean_as_integer]
49
+ reference_sql: |
50
+ SELECT count(*) AS n
51
+ FROM support_tickets
52
+ WHERE severity = 'high' AND resolved = 0
53
+
54
+ # --- the schema traps ------------------------------------------------------
55
+
56
+ - id: top_customers_net
57
+ ordered: true
58
+ question: >
59
+ Who are the top 5 customers by how much they actually spent?
60
+ Exclude cancelled orders and subtract any refunds.
61
+ traps: [no_total_column, cents, cancelled_orders, refunds, join_fanout]
62
+ reference_sql: |
63
+ SELECT c.name,
64
+ (SUM(oi.quantity * oi.unit_price_cents)
65
+ - COALESCE((SELECT SUM(r.amount_cents)
66
+ FROM refunds r
67
+ JOIN orders o2 ON o2.id = r.order_id
68
+ WHERE o2.customer_id = c.id), 0)) / 100.0 AS spend
69
+ FROM customers c
70
+ JOIN orders o ON o.customer_id = c.id AND o.status != 'cancelled'
71
+ JOIN order_items oi ON oi.order_id = o.id
72
+ GROUP BY c.id
73
+ ORDER BY spend DESC
74
+ LIMIT 5
75
+
76
+ - id: revenue_by_category
77
+ question: "What is the total revenue per product category, excluding cancelled orders?"
78
+ traps: [no_total_column, cents, cancelled_orders, join_through_items]
79
+ reference_sql: |
80
+ SELECT p.category,
81
+ SUM(oi.quantity * oi.unit_price_cents) / 100.0 AS revenue
82
+ FROM products p
83
+ JOIN order_items oi ON oi.product_id = p.id
84
+ JOIN orders o ON o.id = oi.order_id AND o.status != 'cancelled'
85
+ GROUP BY p.category
86
+ ORDER BY revenue DESC
87
+
88
+ - id: avg_order_value
89
+ question: "What is the average order value for completed orders?"
90
+ traps: [no_total_column, cents, status_filter, avg_of_sums]
91
+ reference_sql: |
92
+ SELECT AVG(order_total) / 100.0 AS avg_order_value
93
+ FROM (
94
+ SELECT o.id, SUM(oi.quantity * oi.unit_price_cents) AS order_total
95
+ FROM orders o
96
+ JOIN order_items oi ON oi.order_id = o.id
97
+ WHERE o.status = 'completed'
98
+ GROUP BY o.id
99
+ )
100
+
101
+ - id: price_drift
102
+ # Not `ordered`: the two smallest gaps are both 8.00, so two equally correct
103
+ # queries can return them in either order. Grading the order here would
104
+ # measure the tie-break, not the answer.
105
+ question: >
106
+ Which products were sold for less than their current list price,
107
+ and what is the largest gap?
108
+ traps: [historic_vs_list_price, missing_group_by]
109
+ reference_sql: |
110
+ SELECT p.name,
111
+ MAX(p.list_price_cents - oi.unit_price_cents) / 100.0 AS max_gap
112
+ FROM products p
113
+ JOIN order_items oi ON oi.product_id = p.id
114
+ WHERE oi.unit_price_cents < p.list_price_cents
115
+ GROUP BY p.id
116
+ ORDER BY max_gap DESC
117
+
118
+ - id: net_revenue_total
119
+ question: >
120
+ What is our total net revenue? Count only orders that were not cancelled,
121
+ and subtract every refund on those orders.
122
+ traps: [no_total_column, cents, cancelled_orders, refunds, join_fanout]
123
+ reference_sql: |
124
+ SELECT (
125
+ (SELECT SUM(oi.quantity * oi.unit_price_cents)
126
+ FROM order_items oi
127
+ JOIN orders o ON o.id = oi.order_id
128
+ WHERE o.status != 'cancelled')
129
+ -
130
+ (SELECT COALESCE(SUM(r.amount_cents), 0)
131
+ FROM refunds r
132
+ JOIN orders o ON o.id = r.order_id
133
+ WHERE o.status != 'cancelled')
134
+ ) / 100.0 AS net_revenue
135
+
136
+ - id: cancelled_order_value
137
+ question: "How much order value did we lose to cancelled orders?"
138
+ traps: [no_total_column, cents, status_filter]
139
+ reference_sql: |
140
+ SELECT SUM(oi.quantity * oi.unit_price_cents) / 100.0 AS lost
141
+ FROM orders o
142
+ JOIN order_items oi ON oi.order_id = o.id
143
+ WHERE o.status = 'cancelled'
144
+
145
+ # --- join fan-out ----------------------------------------------------------
146
+
147
+ - id: net_spend_by_country
148
+ ordered: true
149
+ question: >
150
+ What is the net spend per country? Take the value of the items on orders
151
+ that were not cancelled, and subtract the refunds on those same orders.
152
+ traps: [join_fanout, refunds, cents, cancelled_orders, nulls_without_coalesce]
153
+ reference_sql: |
154
+ WITH gross AS (
155
+ SELECT c.country, SUM(oi.quantity * oi.unit_price_cents) AS cents
156
+ FROM customers c
157
+ JOIN orders o ON o.customer_id = c.id AND o.status != 'cancelled'
158
+ JOIN order_items oi ON oi.order_id = o.id
159
+ GROUP BY c.country
160
+ ),
161
+ refunded AS (
162
+ SELECT c.country, SUM(r.amount_cents) AS cents
163
+ FROM customers c
164
+ JOIN orders o ON o.customer_id = c.id AND o.status != 'cancelled'
165
+ JOIN refunds r ON r.order_id = o.id
166
+ GROUP BY c.country
167
+ )
168
+ SELECT g.country,
169
+ (g.cents - COALESCE(r.cents, 0)) / 100.0 AS net
170
+ FROM gross g
171
+ LEFT JOIN refunded r ON r.country = g.country
172
+ ORDER BY net DESC
173
+
174
+ - id: refunded_customers
175
+ question: "How many customers have ever had a refund?"
176
+ traps: [join_fanout, distinct_count]
177
+ reference_sql: |
178
+ SELECT count(DISTINCT o.customer_id) AS n
179
+ FROM refunds r
180
+ JOIN orders o ON o.id = r.order_id
181
+
182
+ - id: items_and_refunds_per_order
183
+ ordered: true
184
+ question: >
185
+ For the five orders with the largest refunds, show the order id, how many
186
+ line items it has and how much was refunded.
187
+ traps: [join_fanout, cents]
188
+ reference_sql: |
189
+ SELECT o.id,
190
+ (SELECT count(*) FROM order_items oi WHERE oi.order_id = o.id) AS items,
191
+ SUM(r.amount_cents) / 100.0 AS refunded
192
+ FROM orders o
193
+ JOIN refunds r ON r.order_id = o.id
194
+ GROUP BY o.id
195
+ ORDER BY refunded DESC
196
+ LIMIT 5
197
+
198
+ # --- a missing GROUP BY ----------------------------------------------------
199
+
200
+ - id: units_per_product
201
+ question: "How many units of each product have been sold?"
202
+ traps: [missing_group_by, join_through_items]
203
+ reference_sql: |
204
+ SELECT p.name, SUM(oi.quantity) AS units
205
+ FROM products p
206
+ JOIN order_items oi ON oi.product_id = p.id
207
+ GROUP BY p.id
208
+
209
+ - id: orders_per_product
210
+ question: "In how many separate orders does each product appear?"
211
+ traps: [missing_group_by, distinct_count]
212
+ reference_sql: |
213
+ SELECT p.name, count(DISTINCT oi.order_id) AS orders
214
+ FROM products p
215
+ JOIN order_items oi ON oi.product_id = p.id
216
+ GROUP BY p.id
217
+
218
+ - id: top_category_by_units
219
+ ordered: true
220
+ question: "Which product category has sold the most units?"
221
+ traps: [missing_group_by, join_through_items]
222
+ reference_sql: |
223
+ SELECT p.category, SUM(oi.quantity) AS units
224
+ FROM products p
225
+ JOIN order_items oi ON oi.product_id = p.id
226
+ GROUP BY p.category
227
+ ORDER BY units DESC
228
+ LIMIT 1
229
+
230
+ - id: avg_items_per_order
231
+ question: "On average, how many line items does an order have?"
232
+ traps: [avg_of_counts, missing_group_by]
233
+ reference_sql: |
234
+ SELECT AVG(items) AS avg_items
235
+ FROM (
236
+ SELECT o.id, count(*) AS items
237
+ FROM orders o
238
+ JOIN order_items oi ON oi.order_id = o.id
239
+ GROUP BY o.id
240
+ )
241
+
242
+ - id: channel_order_value
243
+ ordered: true
244
+ question: "What is the average value of a completed order, per channel?"
245
+ traps: [no_total_column, cents, status_filter, avg_of_sums, missing_group_by]
246
+ reference_sql: |
247
+ SELECT channel, AVG(order_total) / 100.0 AS avg_value
248
+ FROM (
249
+ SELECT o.id, o.channel, SUM(oi.quantity * oi.unit_price_cents) AS order_total
250
+ FROM orders o
251
+ JOIN order_items oi ON oi.order_id = o.id
252
+ WHERE o.status = 'completed'
253
+ GROUP BY o.id
254
+ )
255
+ GROUP BY channel
256
+ ORDER BY avg_value DESC
257
+
258
+ # --- NULLs that need COALESCE ---------------------------------------------
259
+
260
+ - id: bottom_customers_net
261
+ # Not `ordered`: six customers come out at exactly 0.00 — fully refunded —
262
+ # so the order within the bottom ten is arbitrary. Which ten they are is not:
263
+ # rank 10 is 49.50 and rank 11 is 108.00.
264
+ question: >
265
+ Of the customers who have ordered, which ten spent the least once refunds
266
+ are taken off? Customers who were never refunded still count.
267
+ traps: [nulls_without_coalesce, refunds, cents, cancelled_orders]
268
+ reference_sql: |
269
+ SELECT c.name,
270
+ (SUM(oi.quantity * oi.unit_price_cents)
271
+ - COALESCE((SELECT SUM(r.amount_cents)
272
+ FROM refunds r
273
+ JOIN orders o2 ON o2.id = r.order_id
274
+ WHERE o2.customer_id = c.id
275
+ AND o2.status != 'cancelled'), 0)) / 100.0 AS net
276
+ FROM customers c
277
+ JOIN orders o ON o.customer_id = c.id AND o.status != 'cancelled'
278
+ JOIN order_items oi ON oi.order_id = o.id
279
+ GROUP BY c.id
280
+ ORDER BY net ASC, c.id ASC
281
+ LIMIT 10
282
+
283
+ - id: refund_total_per_channel
284
+ question: >
285
+ How much has been refunded per order channel? Channels with no refunds at
286
+ all should show zero, not disappear.
287
+ traps: [nulls_without_coalesce, left_join, cents]
288
+ reference_sql: |
289
+ SELECT o.channel,
290
+ COALESCE(SUM(r.amount_cents), 0) / 100.0 AS refunded
291
+ FROM orders o
292
+ LEFT JOIN refunds r ON r.order_id = o.id
293
+ GROUP BY o.channel
294
+
295
+ - id: tickets_per_customer_including_none
296
+ question: >
297
+ Among customers in Argentina, how many support tickets does each have?
298
+ Include the ones with no tickets, as zero.
299
+ traps: [nulls_without_coalesce, left_join, distractor_table]
300
+ reference_sql: |
301
+ SELECT c.name, count(t.id) AS tickets
302
+ FROM customers c
303
+ LEFT JOIN support_tickets t ON t.customer_id = c.id
304
+ WHERE c.country = 'AR'
305
+ GROUP BY c.id
306
+
307
+ # --- date filters ----------------------------------------------------------
308
+
309
+ - id: orders_by_channel_q1
310
+ question: "How many orders came through each channel in the first quarter of 2026?"
311
+ traps: [iso_date_strings, date_boundaries]
312
+ reference_sql: |
313
+ SELECT channel, count(*) AS n
314
+ FROM orders
315
+ WHERE ordered_at >= '2026-01-01' AND ordered_at < '2026-04-01'
316
+ GROUP BY channel
317
+ ORDER BY n DESC
318
+
319
+ - id: orders_in_september
320
+ question: "How many orders were placed in September 2026?"
321
+ traps: [iso_date_strings, date_boundaries]
322
+ reference_sql: |
323
+ SELECT count(*) AS n
324
+ FROM orders
325
+ WHERE ordered_at >= '2026-09-01' AND ordered_at < '2026-10-01'
326
+
327
+ - id: monthly_revenue
328
+ ordered: true
329
+ question: >
330
+ What was the revenue for each month of 2026, excluding cancelled orders?
331
+ traps: [iso_date_strings, no_total_column, cents, cancelled_orders]
332
+ reference_sql: |
333
+ SELECT substr(o.ordered_at, 1, 7) AS month,
334
+ SUM(oi.quantity * oi.unit_price_cents) / 100.0 AS revenue
335
+ FROM orders o
336
+ JOIN order_items oi ON oi.order_id = o.id
337
+ WHERE o.status != 'cancelled'
338
+ AND o.ordered_at >= '2026-01-01' AND o.ordered_at < '2027-01-01'
339
+ GROUP BY month
340
+ ORDER BY month
341
+
342
+ - id: refund_latency
343
+ question: "On average, how many days after the order is a refund issued?"
344
+ traps: [iso_date_strings, date_arithmetic]
345
+ reference_sql: |
346
+ SELECT AVG(julianday(r.refunded_at) - julianday(o.ordered_at)) AS avg_days
347
+ FROM refunds r
348
+ JOIN orders o ON o.id = r.order_id
349
+
350
+ - id: customers_signed_up_2024_who_ordered
351
+ question: "How many customers who signed up in 2024 have placed an order?"
352
+ traps: [iso_date_strings, date_boundaries, semi_join]
353
+ reference_sql: |
354
+ SELECT count(*) AS n
355
+ FROM customers c
356
+ WHERE c.signed_up_at >= '2024-01-01' AND c.signed_up_at < '2025-01-01'
357
+ AND EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
358
+
359
+ - id: refunds_within_a_week
360
+ question: "How many refunds were issued within seven days of the order?"
361
+ traps: [iso_date_strings, date_arithmetic]
362
+ reference_sql: |
363
+ SELECT count(*) AS n
364
+ FROM refunds r
365
+ JOIN orders o ON o.id = r.order_id
366
+ WHERE julianday(r.refunded_at) - julianday(o.ordered_at) <= 7
367
+
368
+ # --- set logic -------------------------------------------------------------
369
+
370
+ - id: customers_without_orders
371
+ question: "How many customers have never placed an order?"
372
+ traps: [anti_join]
373
+ reference_sql: |
374
+ SELECT count(*) AS n
375
+ FROM customers c
376
+ WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
377
+
378
+ - id: repeat_customers
379
+ question: "How many customers placed more than one order that was not cancelled?"
380
+ traps: [having, cancelled_orders]
381
+ reference_sql: |
382
+ SELECT count(*) AS n
383
+ FROM (
384
+ SELECT o.customer_id
385
+ FROM orders o
386
+ WHERE o.status != 'cancelled'
387
+ GROUP BY o.customer_id
388
+ HAVING count(*) > 1
389
+ )
390
+
391
+ - id: refund_rate
392
+ question: "What percentage of non-cancelled orders ended up with a refund?"
393
+ traps: [cancelled_orders, ratio]
394
+ reference_sql: |
395
+ SELECT ROUND(
396
+ 100.0 * COUNT(DISTINCT r.order_id) / COUNT(DISTINCT o.id), 2
397
+ ) AS pct
398
+ FROM orders o
399
+ LEFT JOIN refunds r ON r.order_id = o.id
400
+ WHERE o.status != 'cancelled'
401
+
402
+ - id: refund_reasons_share
403
+ ordered: true
404
+ question: "How much was refunded for each reason, and what share of all refunds is that?"
405
+ traps: [ratio, cents]
406
+ reference_sql: |
407
+ SELECT reason,
408
+ SUM(amount_cents) / 100.0 AS refunded,
409
+ ROUND(100.0 * SUM(amount_cents)
410
+ / (SELECT SUM(amount_cents) FROM refunds), 2) AS pct
411
+ FROM refunds
412
+ GROUP BY reason
413
+ ORDER BY refunded DESC
414
+
415
+ # --- questions with more than one right answer -----------------------------
416
+ #
417
+ # These are marked ambiguous and reported apart from the headline accuracy.
418
+ # The reference encodes one defensible reading, named in `reference_reading`,
419
+ # and the agent is asked by its system prompt to state the choice it made.
420
+
421
+ - id: best_selling_product
422
+ ambiguous: true
423
+ ordered: true
424
+ reference_reading: "best-selling = most units sold, not most revenue"
425
+ question: "What is our best-selling product?"
426
+ traps: [ambiguous_metric, join_through_items]
427
+ reference_sql: |
428
+ SELECT p.name, SUM(oi.quantity) AS units
429
+ FROM products p
430
+ JOIN order_items oi ON oi.product_id = p.id
431
+ GROUP BY p.id
432
+ ORDER BY units DESC
433
+ LIMIT 1
434
+
435
+ - id: how_much_did_we_make
436
+ ambiguous: true
437
+ reference_reading: "net of refunds, cancelled orders excluded, shipped counted"
438
+ question: "How much money have we made?"
439
+ traps: [ambiguous_scope, cancelled_orders, refunds, cents, no_total_column]
440
+ reference_sql: |
441
+ SELECT (
442
+ (SELECT SUM(oi.quantity * oi.unit_price_cents)
443
+ FROM order_items oi
444
+ JOIN orders o ON o.id = oi.order_id
445
+ WHERE o.status != 'cancelled')
446
+ -
447
+ (SELECT COALESCE(SUM(r.amount_cents), 0)
448
+ FROM refunds r
449
+ JOIN orders o ON o.id = r.order_id
450
+ WHERE o.status != 'cancelled')
451
+ ) / 100.0 AS made
452
+
453
+ - id: most_loyal_customer
454
+ ambiguous: true
455
+ ordered: true
456
+ reference_reading: "loyal = most non-cancelled orders, not most spend or longest tenure"
457
+ question: "Who is our most loyal customer?"
458
+ traps: [ambiguous_metric, cancelled_orders]
459
+ reference_sql: |
460
+ SELECT c.name, count(*) AS orders
461
+ FROM customers c
462
+ JOIN orders o ON o.customer_id = c.id AND o.status != 'cancelled'
463
+ GROUP BY c.id
464
+ ORDER BY orders DESC, c.id ASC
465
+ LIMIT 1
466
+
467
+ - id: refunded_share_of_revenue
468
+ ambiguous: true
469
+ reference_reading: "a percentage between 0 and 100, not a fraction between 0 and 1"
470
+ question: "What share of our revenue has been refunded?"
471
+ traps: [ambiguous_units, ratio, cents, cancelled_orders]
472
+ reference_sql: |
473
+ SELECT ROUND(
474
+ 100.0
475
+ * (SELECT SUM(r.amount_cents)
476
+ FROM refunds r
477
+ JOIN orders o ON o.id = r.order_id
478
+ WHERE o.status != 'cancelled')
479
+ / (SELECT SUM(oi.quantity * oi.unit_price_cents)
480
+ FROM order_items oi
481
+ JOIN orders o ON o.id = oi.order_id
482
+ WHERE o.status != 'cancelled'), 2
483
+ ) AS pct
sql_agent/db.py ADDED
@@ -0,0 +1,213 @@
1
+ """Deterministic sample database.
2
+
3
+ The seed is fixed, so every run of the evaluation sees byte-identical data and
4
+ the golden answers stay valid. Regenerating the database on another machine
5
+ produces the same numbers.
6
+
7
+ This module only ever builds the sample database when it is *asked* to —
8
+ `--demo`, `SQL_AGENT_DEMO=1` or `--build-db`. It used to build it from
9
+ `connect()` whenever the file was missing, which meant a typo in a path
10
+ silently produced a working agent answering questions about fictional data.
11
+ A path that is not there is an error now.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import random
18
+ import sqlite3
19
+ from datetime import date, timedelta
20
+ from pathlib import Path
21
+
22
+ from sql_agent.adapters import ConfigError
23
+
24
+ SCHEMA_PATH = Path(__file__).with_name("schema.sql")
25
+
26
+
27
+ def _default_db_path() -> Path:
28
+ """Where the sample database lives.
29
+
30
+ In a checkout that is the repository root, which is what every example in
31
+ the README assumes. Installed from a wheel, `parents[1]` is site-packages:
32
+ writing there is wrong even when it is writable, because nobody looks for
33
+ their data inside a virtual environment, and `uvx sql-agent-mcp --demo`
34
+ would scatter a database into a throwaway one. So an installed copy uses
35
+ the user's data directory instead.
36
+ """
37
+ root = Path(__file__).resolve().parents[1]
38
+ if (root / "pyproject.toml").exists():
39
+ return root / "shop.db"
40
+ base = os.getenv("XDG_DATA_HOME") or str(Path.home() / ".local" / "share")
41
+ return Path(base).expanduser() / "sql-agent" / "shop.db"
42
+
43
+
44
+ DEFAULT_DB_PATH = _default_db_path()
45
+
46
+ SEED = 20261109
47
+ START = date(2026, 1, 1)
48
+ DAYS = 300
49
+
50
+ COUNTRIES = ["AR", "CL", "MX", "ES", "US", "BR"]
51
+ CHANNELS = ["web", "mobile", "phone"]
52
+ SEVERITIES = ["low", "medium", "high"]
53
+ REFUND_REASONS = ["damaged", "wrong item", "late delivery", "changed mind"]
54
+
55
+ FIRST = ["Ignacio", "Camila", "Lucas", "Valentina", "Mateo", "Sofía", "Benjamín",
56
+ "Isabella", "Thiago", "Emilia", "Joaquín", "Renata", "Bruno", "Olivia",
57
+ "Facundo", "Martina", "Tomás", "Agustina", "Dante", "Paz"]
58
+ LAST = ["Duque", "Sandoval", "Rojas", "Figueroa", "Muñoz", "Correa", "Vera",
59
+ "Bustos", "Peralta", "Ibarra", "Salazar", "Cabrera", "Ponce", "Lagos"]
60
+
61
+ CATALOGUE = [
62
+ ("Mate imperial", "drinkware", 18_900),
63
+ ("Bombilla de alpaca", "drinkware", 7_500),
64
+ ("Termo 1L acero", "drinkware", 32_000),
65
+ ("Yerba orgánica 1kg", "pantry", 4_200),
66
+ ("Alfajores artesanales x6", "pantry", 6_800),
67
+ ("Café de especialidad 500g", "pantry", 9_900),
68
+ ("Cuaderno cosido A5", "stationery", 5_400),
69
+ ("Pluma estilográfica", "stationery", 24_500),
70
+ ("Tinta azul 30ml", "stationery", 3_900),
71
+ ("Mochila 20L", "gear", 48_000),
72
+ ("Riñonera impermeable", "gear", 21_000),
73
+ ("Gorra de lona", "gear", 11_500),
74
+ ("Taza de cerámica", "drinkware", 8_900),
75
+ ("Set de posavasos", "home", 6_200),
76
+ ("Lámpara de escritorio", "home", 39_900),
77
+ ]
78
+
79
+
80
+ def build(db_path: Path | str | None = None, *, overwrite: bool = True) -> Path:
81
+ """Create the sample database and return its path."""
82
+ db_path = Path(db_path if db_path is not None else DEFAULT_DB_PATH)
83
+ if db_path.exists():
84
+ if not overwrite:
85
+ return db_path
86
+ db_path.unlink()
87
+
88
+ db_path.parent.mkdir(parents=True, exist_ok=True)
89
+ rng = random.Random(SEED)
90
+ conn = sqlite3.connect(db_path)
91
+ conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8"))
92
+
93
+ # --- products -------------------------------------------------------
94
+ products: list[tuple[int, str, str, int, int]] = []
95
+ for pid, (name, category, price) in enumerate(CATALOGUE, start=1):
96
+ discontinued = 1 if rng.random() < 0.13 else 0
97
+ products.append((pid, name, category, price, discontinued))
98
+ conn.executemany("INSERT INTO products VALUES (?,?,?,?,?)", products)
99
+
100
+ # --- customers ------------------------------------------------------
101
+ customers: list[tuple[int, str, str, str, str]] = []
102
+ seen_emails: set[str] = set()
103
+ for cid in range(1, 121):
104
+ name = f"{rng.choice(FIRST)} {rng.choice(LAST)}"
105
+ base = name.lower().replace(" ", ".").replace("í", "i").replace("á", "a")
106
+ base = base.replace("é", "e").replace("ó", "o").replace("ú", "u").replace("ñ", "n")
107
+ email = f"{base}{cid}@example.com"
108
+ assert email not in seen_emails
109
+ seen_emails.add(email)
110
+ signed_up = START - timedelta(days=rng.randint(0, 540))
111
+ customers.append((cid, name, email, rng.choice(COUNTRIES), signed_up.isoformat()))
112
+ conn.executemany("INSERT INTO customers VALUES (?,?,?,?,?)", customers)
113
+
114
+ # --- orders and items -----------------------------------------------
115
+ orders: list[tuple[int, int, str, str, str]] = []
116
+ items: list[tuple[int, int, int, int, int]] = []
117
+ refunds: list[tuple[int, int, int, str, str]] = []
118
+
119
+ order_id = 0
120
+ item_id = 0
121
+ refund_id = 0
122
+
123
+ for cid, *_ in customers:
124
+ # A long tail: most customers order rarely, a few order a lot — and a
125
+ # real customer table always has people who signed up and never bought.
126
+ n_orders = 0 if rng.random() < 0.15 else min(int(rng.paretovariate(1.4)), 14)
127
+ for _ in range(n_orders):
128
+ order_id += 1
129
+ ordered = START + timedelta(days=rng.randint(0, DAYS - 1))
130
+ roll = rng.random()
131
+ status = "cancelled" if roll < 0.09 else ("shipped" if roll < 0.35 else "completed")
132
+ orders.append((order_id, cid, ordered.isoformat(), status, rng.choice(CHANNELS)))
133
+
134
+ order_cents = 0
135
+ for _ in range(rng.randint(1, 4)):
136
+ item_id += 1
137
+ pid, _n, _c, list_price, _d = rng.choice(products)
138
+ qty = rng.randint(1, 3)
139
+ # Price actually paid drifts from today's catalogue price.
140
+ drift = rng.choice([0.80, 0.85, 0.90, 1.00, 1.00, 1.05])
141
+ paid = int(round(list_price * drift / 100.0)) * 100
142
+ items.append((item_id, order_id, pid, qty, paid))
143
+ order_cents += qty * paid
144
+
145
+ # Refunds only ever attach to orders that were not cancelled.
146
+ if status != "cancelled" and rng.random() < 0.18:
147
+ refund_id += 1
148
+ partial = rng.choice([0.25, 0.5, 1.0])
149
+ refunded = ordered + timedelta(days=rng.randint(1, 30))
150
+ refunds.append((
151
+ refund_id, order_id, int(order_cents * partial),
152
+ refunded.isoformat(), rng.choice(REFUND_REASONS),
153
+ ))
154
+
155
+ conn.executemany("INSERT INTO orders VALUES (?,?,?,?,?)", orders)
156
+ conn.executemany("INSERT INTO order_items VALUES (?,?,?,?,?)", items)
157
+ conn.executemany("INSERT INTO refunds VALUES (?,?,?,?,?)", refunds)
158
+
159
+ # --- support tickets (distractor) ------------------------------------
160
+ tickets: list[tuple[int, int, str, str, int]] = []
161
+ for tid in range(1, 181):
162
+ cid = rng.randint(1, len(customers))
163
+ opened = START + timedelta(days=rng.randint(0, DAYS - 1))
164
+ tickets.append((tid, cid, opened.isoformat(), rng.choice(SEVERITIES),
165
+ 1 if rng.random() < 0.72 else 0))
166
+ conn.executemany("INSERT INTO support_tickets VALUES (?,?,?,?,?)", tickets)
167
+
168
+ conn.commit()
169
+ conn.close()
170
+ return db_path
171
+
172
+
173
+ def ensure_demo(db_path: Path | str | None = None) -> Path:
174
+ """Build the sample database if it is not there yet, and return its path.
175
+
176
+ The only function that creates a database as a side effect, and it is
177
+ reached only from an explicit `--demo` / `SQL_AGENT_DEMO=1` / `--build-db`.
178
+ """
179
+ db_path = Path(db_path if db_path is not None else DEFAULT_DB_PATH)
180
+ if db_path.exists():
181
+ return db_path
182
+ return build(db_path, overwrite=False)
183
+
184
+
185
+ def connect(db_path: Path | str | None = None) -> sqlite3.Connection:
186
+ """Open a SQLite database read-only, so no agent can write to it.
187
+
188
+ Raises `ConfigError` when the file is not there. It does *not* build the
189
+ sample database: see `ensure_demo`.
190
+ """
191
+ db_path = Path(db_path if db_path is not None else DEFAULT_DB_PATH)
192
+ if not db_path.exists():
193
+ raise ConfigError(
194
+ f"no SQLite database at {db_path}. Point SQL_AGENT_DSN at an "
195
+ "existing file, or pass --demo (or set SQL_AGENT_DEMO=1) to build "
196
+ "the bundled sample database."
197
+ )
198
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
199
+ conn.row_factory = sqlite3.Row
200
+ return conn
201
+
202
+
203
+ if __name__ == "__main__":
204
+ path = build()
205
+ conn = sqlite3.connect(path)
206
+ counts = {
207
+ t: conn.execute(f"SELECT count(*) FROM {t}").fetchone()[0]
208
+ for t in ("customers", "products", "orders", "order_items", "refunds", "support_tickets")
209
+ }
210
+ conn.close()
211
+ print(f"built {path}")
212
+ for table, n in counts.items():
213
+ print(f" {table:<16} {n:>6}")