platybus-samples 0.1.1__tar.gz

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,46 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ .venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+
14
+ # Node
15
+ web/node_modules/
16
+ web/dist/
17
+ src/platybus/server/static/
18
+ web/*.tsbuildinfo
19
+ # Playwright artifacts
20
+ web/playwright-report/
21
+ web/test-results/
22
+ web/blob-report/
23
+ web/playwright/.cache/
24
+
25
+ # Platybus local state and demos
26
+ .platybus/
27
+ .tmp/
28
+ *.duckdb
29
+ *.duckdb.wal
30
+
31
+ # Secrets
32
+ .env
33
+ .env.*
34
+ !.env.example
35
+
36
+ # Editors / OS
37
+ .idea/
38
+ .vscode/
39
+ .DS_Store
40
+ Thumbs.db
41
+
42
+ # Claude Code local settings
43
+ .claude/settings.local.json
44
+ .claude
45
+ # MkDocs output
46
+ site/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yaroslav Ozerov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.5
2
+ Name: platybus-samples
3
+ Version: 0.1.1
4
+ Summary: Platybus plugin: sample datasets (TPC-H, jaffle shop, web events, taxi trips) generated locally.
5
+ Project-URL: Homepage, https://github.com/RobbyTheFish/platybus
6
+ Project-URL: Documentation, https://robbythefish.github.io/platybus/
7
+ Project-URL: Repository, https://github.com/RobbyTheFish/platybus
8
+ Project-URL: Issues, https://github.com/RobbyTheFish/platybus/issues
9
+ Project-URL: Changelog, https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md
10
+ Author: Yaroslav Ozerov
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: duckdb,platybus,platybus-plugin,samples
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Requires-Dist: platybus>=0.1.1
24
+ Description-Content-Type: text/markdown
25
+
26
+ # platybus-samples
27
+
28
+ sample datasets (TPC-H, jaffle shop, web events, taxi trips) generated locally.
29
+
30
+ A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
31
+ a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
32
+ ETL, dbt and dashboards.
33
+
34
+ ```bash
35
+ pip install platybus platybus-samples
36
+ ```
37
+
38
+ Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
39
+ is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/datasets/>).
40
+
41
+ License: MIT.
@@ -0,0 +1,16 @@
1
+ # platybus-samples
2
+
3
+ sample datasets (TPC-H, jaffle shop, web events, taxi trips) generated locally.
4
+
5
+ A plugin for [Platybus](https://github.com/RobbyTheFish/platybus), a compact data platform:
6
+ a hub of projects with pluggable stores (DuckLake, Iceberg, PostgreSQL), a DuckDB engine,
7
+ ETL, dbt and dashboards.
8
+
9
+ ```bash
10
+ pip install platybus platybus-samples
11
+ ```
12
+
13
+ Platybus discovers the plugin through the `platybus.plugins` entry point; no configuration
14
+ is needed. Documentation: <https://robbythefish.github.io/platybus/> (this plugin: <https://robbythefish.github.io/platybus/datasets/>).
15
+
16
+ License: MIT.
@@ -0,0 +1,43 @@
1
+ [project]
2
+ name = "platybus-samples"
3
+ version = "0.1.1" # x-release-please-version
4
+ description = "Platybus plugin: sample datasets (TPC-H, jaffle shop, web events, taxi trips) generated locally."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Yaroslav Ozerov" }]
9
+ requires-python = ">=3.12"
10
+ keywords = ["platybus", "platybus-plugin", "duckdb", "samples"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Intended Audience :: Developers",
14
+ "Operating System :: OS Independent",
15
+ "Programming Language :: Python :: 3",
16
+ "Programming Language :: Python :: 3.12",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Topic :: Database",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = [
22
+ "platybus>=0.1.1", # x-release-please-version
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/RobbyTheFish/platybus"
27
+ Documentation = "https://robbythefish.github.io/platybus/"
28
+ Repository = "https://github.com/RobbyTheFish/platybus"
29
+ Issues = "https://github.com/RobbyTheFish/platybus/issues"
30
+ Changelog = "https://github.com/RobbyTheFish/platybus/blob/main/CHANGELOG.md"
31
+
32
+ [project.entry-points."platybus.plugins"]
33
+ samples = "platybus_samples:plugin"
34
+
35
+ [build-system]
36
+ requires = ["hatchling>=1.26"]
37
+ build-backend = "hatchling.build"
38
+
39
+ [tool.hatch.build.targets.wheel]
40
+ packages = ["src/platybus_samples"]
41
+
42
+ [tool.uv.sources]
43
+ platybus = { workspace = true }
@@ -0,0 +1,26 @@
1
+ """Platybus plugin: sample datasets generated locally (no downloads).
2
+
3
+ - ``tpch`` - the TPC-H benchmark schema (DuckDB ``tpch`` extension), scale 0.01 / 0.1 / 1.
4
+ - ``jaffle_shop`` - customers / orders / payments of dbt's demo shop.
5
+ - ``web_events`` - a synthetic clickstream: users, sessions, events.
6
+ - ``taxi_trips`` - synthetic taxi rides and zones.
7
+
8
+ Every dataset is deterministic (same options, same rows) and is written with the
9
+ store-aware SQL helpers, so it loads into any store type.
10
+ """
11
+
12
+ from platybus.plugins import Plugin
13
+ from platybus_samples import jaffle, taxi, tpch, web_events
14
+
15
+ DATASETS = (tpch.DATASET, jaffle.DATASET, web_events.DATASET, taxi.DATASET)
16
+
17
+ plugin = Plugin(
18
+ name="samples",
19
+ kind="datasets",
20
+ title="Sample datasets",
21
+ description="TPC-H, jaffle shop, web events and taxi trips, generated locally and "
22
+ "sized by options.",
23
+ datasets=DATASETS,
24
+ )
25
+
26
+ __all__ = ["DATASETS", "plugin"]
@@ -0,0 +1,54 @@
1
+ """SQL helpers shared by the synthetic datasets.
2
+
3
+ The data is generated inside DuckDB from ``range()`` with integer hashing instead of
4
+ ``random()``: the same row number always gives the same values, on every machine and at
5
+ any degree of parallelism, so row counts and contents are reproducible.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Sequence
11
+
12
+ from platybus.datasets import DatasetContext
13
+ from platybus.etl.sql import create_table_as, qualified
14
+ from platybus.sqlutil import quote_literal
15
+
16
+ _MASK = 4294967296 # 2**32
17
+
18
+
19
+ def rnd(expr: str, salt: int) -> str:
20
+ """A uniform DOUBLE in [0, 1) derived from the BIGINT ``expr`` and a salt."""
21
+ first = f"((({expr}) * 2654435761 + {salt * 40503 + 7919}) % {_MASK})"
22
+ mixed = f"((xor({first}, {first} >> 13) * 1597334677) % {_MASK})"
23
+ return f"(xor({mixed}, {mixed} >> 16) / {float(_MASK)})"
24
+
25
+
26
+ def pick(values: Sequence[str], r: str) -> str:
27
+ """One of ``values`` (uniformly) for a uniform ``r`` in [0, 1)."""
28
+ items = ", ".join(quote_literal(v) for v in values)
29
+ return f"([{items}])[1 + floor({r} * {len(values)})::INTEGER]"
30
+
31
+
32
+ def weighted(choices: Sequence[tuple[str, float]], r: str) -> str:
33
+ """One of the values, with the given relative weights, for a uniform ``r``."""
34
+ total = sum(w for _, w in choices)
35
+ acc = 0.0
36
+ branches = []
37
+ for value, weight in choices[:-1]:
38
+ acc += weight / total
39
+ branches.append(f"WHEN {r} < {acc:.6f} THEN {quote_literal(value)}")
40
+ return f"CASE {' '.join(branches)} ELSE {quote_literal(choices[-1][0])} END"
41
+
42
+
43
+ def create_tables(ctx: DatasetContext, tables: Sequence[tuple[str, str]]) -> dict[str, int]:
44
+ """(Re)create each ``(name, select_sql)`` in the target schema; returns row counts."""
45
+
46
+ counts: dict[str, int] = {}
47
+ with ctx.engine.connection() as con:
48
+ for name, select_sql in tables:
49
+ create_table_as(con, ctx.store, ctx.schema, name, select_sql)
50
+ row = con.execute(
51
+ f"SELECT count(*) FROM {qualified(ctx.store.name, ctx.schema, name)}"
52
+ ).fetchone()
53
+ counts[name] = int(row[0]) if row else 0
54
+ return counts
@@ -0,0 +1,157 @@
1
+ """Jaffle shop: the customers / orders / payments of dbt's classic demo, synthetic.
2
+
3
+ At the default size the rows are exactly the seed CSVs of ``examples/jaffle-shop``
4
+ (``scripts/generate_jaffle_seeds.py`` writes those files with :func:`generate`).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import random
10
+ import uuid
11
+ from dataclasses import dataclass
12
+ from datetime import date, timedelta
13
+ from itertools import accumulate
14
+
15
+ import pyarrow as pa
16
+ from pydantic import BaseModel, ConfigDict, Field
17
+
18
+ from platybus.datasets import DatasetContext, DatasetSpec, DatasetTable
19
+ from platybus.etl.sql import create_table_as
20
+ from platybus.sqlutil import quote_ident
21
+
22
+ SEED = 20260101
23
+ START = date(2026, 1, 1)
24
+ END = date(2026, 9, 30)
25
+
26
+ FIRST_NAMES = [
27
+ "Michael", "Shawn", "Kathleen", "Jimmy", "Katherine", "Sarah", "Martin", "Frank",
28
+ "Jennifer", "Henry", "Fred", "Amy", "Kathleen", "Steve", "Teresa", "Amanda", "Kimberly",
29
+ "Johnny", "Virginia", "Anna", "Willie", "Sean", "Mildred", "David", "Victor", "Aaron",
30
+ "Irene", "Mary", "Jacqueline", "Adam", "Nancy", "Norma", "Laura", "Lillian", "Olga",
31
+ "Gerald", "Harold", "Rose", "Emily", "Paula", "Ruth", "Diana", "Roger", "Eugene",
32
+ ] # fmt: skip
33
+ LAST_INITIALS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
34
+ METHODS = [("credit_card", 0.55), ("bank_transfer", 0.2), ("coupon", 0.15), ("gift_card", 0.1)]
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class JaffleRows:
39
+ customers: list[tuple[int, str, str]]
40
+ orders: list[tuple[int, int, date, str]]
41
+ payments: list[tuple[int, int, str, int]]
42
+
43
+
44
+ def _status(order_date: date, rng: random.Random) -> str:
45
+ age = (END - order_date).days
46
+ if age <= 3:
47
+ return rng.choice(["placed", "placed", "shipped"])
48
+ if age <= 10:
49
+ return rng.choice(["shipped", "completed", "completed", "return_pending"])
50
+ return rng.choices(["completed", "returned", "return_pending"], weights=[92, 6, 2])[0]
51
+
52
+
53
+ def _method(rng: random.Random) -> str:
54
+ return rng.choices([m for m, _ in METHODS], weights=[w for _, w in METHODS])[0]
55
+
56
+
57
+ def generate(customers: int = 100, orders: int = 1000, seed: int = SEED) -> JaffleRows:
58
+ """Deterministic rows: ``orders`` orders of ``customers`` customers (2026-01..09),
59
+ 1-2 payments per order, amounts in cents."""
60
+ rng = random.Random(seed) # noqa: S311 - synthetic demo data, not crypto
61
+ days = (END - START).days
62
+ customer_rows = [
63
+ (i, rng.choice(FIRST_NAMES), f"{rng.choice(LAST_INITIALS)}.")
64
+ for i in range(1, customers + 1)
65
+ ]
66
+ # Some customers order a lot, some never: a skewed choice. Precomputed cumulative
67
+ # weights give the same draws as `weights=` without O(customers) work per order.
68
+ ids = [c[0] for c in customer_rows]
69
+ cum_weights = list(accumulate(rng.paretovariate(2.5) for _ in customer_rows))
70
+ picked = []
71
+ for _ in range(orders):
72
+ customer_id = rng.choices(ids, cum_weights=cum_weights)[0]
73
+ picked.append((customer_id, START + timedelta(days=rng.randint(0, days))))
74
+ picked.sort(key=lambda o: (o[1], o[0]))
75
+
76
+ order_rows = []
77
+ payment_rows = []
78
+ payment_id = 0
79
+ for order_id, (customer_id, order_date) in enumerate(picked, start=1):
80
+ order_rows.append((order_id, customer_id, order_date, _status(order_date, rng)))
81
+ total = rng.randint(5, 60) * 100 + rng.choice([0, 0, 50, 99])
82
+ parts = [total] if rng.random() < 0.85 else [total // 2, total - total // 2]
83
+ for amount in parts:
84
+ payment_id += 1
85
+ payment_rows.append((payment_id, order_id, _method(rng), amount))
86
+ return JaffleRows(customer_rows, order_rows, payment_rows)
87
+
88
+
89
+ class JaffleOptions(BaseModel):
90
+ model_config = ConfigDict(extra="forbid")
91
+
92
+ customers: int = Field(100, ge=1, le=100_000, description="Number of customers.")
93
+ orders: int = Field(1000, ge=1, le=500_000, description="Number of orders.")
94
+
95
+
96
+ def _tables(rows: JaffleRows) -> dict[str, pa.Table]:
97
+ c, o, p = rows.customers, rows.orders, rows.payments
98
+ return {
99
+ "customers": pa.table(
100
+ {
101
+ "id": pa.array([r[0] for r in c], pa.int32()),
102
+ "first_name": [r[1] for r in c],
103
+ "last_name": [r[2] for r in c],
104
+ }
105
+ ),
106
+ "orders": pa.table(
107
+ {
108
+ "id": pa.array([r[0] for r in o], pa.int32()),
109
+ "user_id": pa.array([r[1] for r in o], pa.int32()),
110
+ "order_date": pa.array([r[2] for r in o], pa.date32()),
111
+ "status": [r[3] for r in o],
112
+ }
113
+ ),
114
+ "payments": pa.table(
115
+ {
116
+ "id": pa.array([r[0] for r in p], pa.int32()),
117
+ "order_id": pa.array([r[1] for r in p], pa.int32()),
118
+ "payment_method": [r[2] for r in p],
119
+ "amount": pa.array([r[3] for r in p], pa.int32()),
120
+ }
121
+ ),
122
+ }
123
+
124
+
125
+ def load(ctx: DatasetContext) -> dict[str, int]:
126
+ rows = generate(int(ctx.options.get("customers", 100)), int(ctx.options.get("orders", 1000)))
127
+ counts: dict[str, int] = {}
128
+ with ctx.engine.connection() as con:
129
+ for name, table in _tables(rows).items():
130
+ view = f"_jaffle_{name}_{uuid.uuid4().hex[:8]}"
131
+ con.register(view, table)
132
+ try:
133
+ create_table_as(
134
+ con, ctx.store, ctx.schema, name, f"SELECT * FROM {quote_ident(view)}"
135
+ )
136
+ finally:
137
+ con.unregister(view)
138
+ counts[name] = table.num_rows
139
+ return counts
140
+
141
+
142
+ DATASET = DatasetSpec(
143
+ key="jaffle_shop",
144
+ title="Jaffle shop",
145
+ description="The customers, orders and payments of dbt's classic demo shop "
146
+ "(synthetic, 2026-01..09; amounts in cents). The default size matches the seeds of "
147
+ "examples/jaffle-shop.",
148
+ load=load,
149
+ tables=(
150
+ DatasetTable("customers", "Customers: id, first and last name."),
151
+ DatasetTable("orders", "Orders: customer (user_id), date and status."),
152
+ DatasetTable("payments", "Payments of orders: method and amount in cents."),
153
+ ),
154
+ default_schema="jaffle_shop",
155
+ options_model=JaffleOptions,
156
+ size="~2.3k rows by default",
157
+ )
File without changes
@@ -0,0 +1,113 @@
1
+ """Taxi trips: synthetic city taxi rides (times, zones, distance, fare, tip, payment)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pydantic import BaseModel, ConfigDict, Field
6
+
7
+ from platybus.datasets import DatasetContext, DatasetSpec, DatasetTable
8
+ from platybus.sqlutil import quote_literal
9
+ from platybus_samples._sql import create_tables, rnd, weighted
10
+
11
+ #: The trips are spread over this period (90 days).
12
+ START = "2026-07-01 00:00:00"
13
+ PERIOD_SECONDS = 90 * 86400
14
+
15
+ #: (zone, borough, relative demand). An invented city: names are generic.
16
+ ZONES = [
17
+ ("Central Station", "Downtown", 14), ("Financial District", "Downtown", 12),
18
+ ("Old Town", "Downtown", 9), ("Harbor Front", "Downtown", 7),
19
+ ("Theater District", "Downtown", 8), ("City Hall", "Downtown", 5),
20
+ ("University", "Northside", 6), ("Museum Mile", "Northside", 5),
21
+ ("North Park", "Northside", 3), ("Hillcrest", "Northside", 2),
22
+ ("Riverside", "Westside", 4), ("Arts Quarter", "Westside", 4),
23
+ ("Market Square", "Westside", 4), ("West End", "Westside", 2),
24
+ ("Tech Park", "Eastside", 5), ("Stadium", "Eastside", 3),
25
+ ("Eastgate", "Eastside", 2), ("Lakeside", "Eastside", 2),
26
+ ("Airport", "Airport", 7), ("Airport Cargo", "Airport", 1),
27
+ ("Southport", "Southside", 2), ("Mill District", "Southside", 2),
28
+ ("Greenfield", "Southside", 1), ("Industrial Bay", "Southside", 1),
29
+ ] # fmt: skip
30
+ PAYMENT_TYPES = [("card", 72), ("cash", 22), ("app", 4), ("no_charge", 1), ("dispute", 1)]
31
+
32
+
33
+ class TaxiOptions(BaseModel):
34
+ model_config = ConfigDict(extra="forbid")
35
+
36
+ rows: int = Field(100_000, ge=100, le=10_000_000, description="Number of trips.")
37
+
38
+
39
+ def _zone(r: str) -> str:
40
+ """Zone id (1-based) chosen by demand for a uniform ``r``."""
41
+ return weighted([(str(i), w) for i, (_, _, w) in enumerate(ZONES, start=1)], r) + "::INTEGER"
42
+
43
+
44
+ def tables(rows: int) -> list[tuple[str, str]]:
45
+ zone_values = ", ".join(
46
+ f"({i}, {quote_literal(name)}, {quote_literal(borough)})"
47
+ for i, (name, borough, _) in enumerate(ZONES, start=1)
48
+ )
49
+ zones_sql = (
50
+ f"SELECT zone_id::INTEGER AS zone_id, zone, borough "
51
+ f"FROM (VALUES {zone_values}) AS z(zone_id, zone, borough) ORDER BY zone_id"
52
+ )
53
+ trips_sql = f"""
54
+ WITH t AS (
55
+ SELECT range AS i,
56
+ {rnd("range", 31)} AS r1, {rnd("range", 32)} AS r2, {rnd("range", 33)} AS r3,
57
+ {rnd("range", 34)} AS r4, {rnd("range", 35)} AS r5, {rnd("range", 36)} AS r6,
58
+ {rnd("range", 37)} AS r7, {rnd("range", 38)} AS r8
59
+ FROM range({rows})
60
+ ), d AS (
61
+ SELECT *,
62
+ {_zone("r1")} AS pickup_zone_id,
63
+ CASE WHEN r2 < 0.25 THEN {_zone("r1")} ELSE {_zone("r3")} END AS dropoff_zone_id,
64
+ -- skewed: most rides are short, a few cross the city
65
+ round(0.4 + 24 * pow(r4, 2.2), 2) AS distance_km,
66
+ {weighted(PAYMENT_TYPES, "r6")} AS payment_type,
67
+ 1 + (CASE WHEN r7 < 0.7 THEN 0 WHEN r7 < 0.88 THEN 1 WHEN r7 < 0.95 THEN 2
68
+ ELSE 2 + floor(r8 * 4) END)::INTEGER AS passenger_count
69
+ FROM t
70
+ ), f AS (
71
+ SELECT *,
72
+ TIMESTAMP '{START}' + to_seconds((i * {PERIOD_SECONDS} // {rows})
73
+ + floor(r5 * 600)::BIGINT) AS pickup_at,
74
+ (distance_km * 2.2 + 3 + r8 * 12) AS minutes,
75
+ round(3.0 + 1.6 * distance_km + 0.35 * (distance_km * 2.2 + 3 + r8 * 12), 2)
76
+ AS fare
77
+ FROM d
78
+ )
79
+ SELECT (i + 1)::BIGINT AS trip_id,
80
+ pickup_at,
81
+ pickup_at + to_seconds(floor(minutes * 60)::BIGINT) AS dropoff_at,
82
+ pickup_zone_id,
83
+ dropoff_zone_id,
84
+ passenger_count,
85
+ distance_km::DECIMAL(8, 2) AS distance_km,
86
+ fare::DECIMAL(10, 2) AS fare_amount,
87
+ CASE WHEN payment_type IN ('card', 'app') THEN round(fare * (0.08 + 0.2 * r2), 2)
88
+ ELSE 0 END::DECIMAL(10, 2) AS tip_amount,
89
+ payment_type
90
+ FROM f
91
+ ORDER BY trip_id
92
+ """
93
+ return [("zones", zones_sql), ("trips", trips_sql)]
94
+
95
+
96
+ def load(ctx: DatasetContext) -> dict[str, int]:
97
+ return create_tables(ctx, tables(int(ctx.options.get("rows", 100_000))))
98
+
99
+
100
+ DATASET = DatasetSpec(
101
+ key="taxi_trips",
102
+ title="Taxi trips",
103
+ description="Synthetic taxi rides in an invented city over 90 days: pickup and dropoff "
104
+ "times and zones, passengers, distance, fare, tip and payment type, plus a zone lookup.",
105
+ load=load,
106
+ tables=(
107
+ DatasetTable("trips", "One row per ride; tips only for card and app payments."),
108
+ DatasetTable("zones", "Pickup / dropoff zones with their borough."),
109
+ ),
110
+ default_schema="taxi",
111
+ options_model=TaxiOptions,
112
+ size="100k trips by default",
113
+ )
@@ -0,0 +1,103 @@
1
+ """TPC-H: the classic decision-support benchmark schema, generated by DuckDB's ``tpch``
2
+ extension (``CALL dbgen``)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import shutil
7
+ import tempfile
8
+ import uuid
9
+ from pathlib import Path
10
+
11
+ import duckdb
12
+ from pydantic import BaseModel, ConfigDict, Field, field_validator
13
+
14
+ from platybus.catalog import load_extension
15
+ from platybus.datasets import DatasetContext, DatasetSpec, DatasetTable
16
+ from platybus.errors import PipelineError, PlatybusError
17
+ from platybus.etl.sql import create_table_as, qualified
18
+ from platybus.sqlutil import quote_ident, quote_literal
19
+
20
+ SCALES = (0.01, 0.1, 1.0)
21
+
22
+ TABLES = (
23
+ DatasetTable("region", "5 regions."),
24
+ DatasetTable("nation", "25 nations, each in a region."),
25
+ DatasetTable("supplier", "Suppliers (10k x scale)."),
26
+ DatasetTable("customer", "Customers (150k x scale) with market segment and balance."),
27
+ DatasetTable("part", "Parts (200k x scale)."),
28
+ DatasetTable("partsupp", "Which supplier offers which part at what cost (800k x scale)."),
29
+ DatasetTable("orders", "Orders (1.5M x scale) with status, date and priority."),
30
+ DatasetTable("lineitem", "Order lines (~6M x scale): quantity, price, discount, dates."),
31
+ )
32
+
33
+
34
+ class TpchOptions(BaseModel):
35
+ model_config = ConfigDict(extra="forbid")
36
+
37
+ scale: float = Field(
38
+ 0.01,
39
+ description="Scale factor: 0.01 (~87k rows, seconds), 0.1 (~870k rows) or 1 "
40
+ "(~8.7M rows, tens of seconds and ~1 GB of temporary disk).",
41
+ json_schema_extra={"enum": list(SCALES)},
42
+ )
43
+
44
+ @field_validator("scale")
45
+ @classmethod
46
+ def _known_scale(cls, value: float) -> float:
47
+ if value not in SCALES:
48
+ raise ValueError(f"scale must be one of {', '.join(f'{s:g}' for s in SCALES)}")
49
+ return value
50
+
51
+
52
+ def _install(con: duckdb.DuckDBPyConnection) -> None:
53
+ try:
54
+ load_extension(con, "tpch")
55
+ except PlatybusError as exc:
56
+ raise PipelineError(
57
+ "the TPC-H dataset needs the DuckDB 'tpch' extension, which could not be "
58
+ f"installed ({exc.message}). Install it once with network access, or pick "
59
+ "another dataset."
60
+ ) from None
61
+
62
+
63
+ def load(ctx: DatasetContext) -> dict[str, int]:
64
+ scale = float(ctx.options.get("scale", 0.01))
65
+ # Generated into a scratch database file (not memory: sf=1 is about a gigabyte),
66
+ # then copied table by table into the target store.
67
+ scratch_dir = Path(tempfile.mkdtemp(prefix="platybus-tpch-"))
68
+ scratch = f"tpch_scratch_{uuid.uuid4().hex[:12]}"
69
+ counts: dict[str, int] = {}
70
+ try:
71
+ with ctx.engine.connection() as con:
72
+ _install(con)
73
+ path = (scratch_dir / "tpch.duckdb").as_posix()
74
+ con.execute(f"ATTACH {quote_literal(path)} AS {quote_ident(scratch)}")
75
+ try:
76
+ con.execute(f"CALL dbgen(sf={scale}, catalog={quote_literal(scratch)})")
77
+ for table in TABLES:
78
+ source = qualified(scratch, "main", table.name)
79
+ create_table_as(
80
+ con, ctx.store, ctx.schema, table.name, f"SELECT * FROM {source}"
81
+ )
82
+ row = con.execute(
83
+ f"SELECT count(*) FROM {qualified(ctx.store.name, ctx.schema, table.name)}"
84
+ ).fetchone()
85
+ counts[table.name] = int(row[0]) if row else 0
86
+ finally:
87
+ con.execute(f"DETACH {quote_ident(scratch)}")
88
+ finally:
89
+ shutil.rmtree(scratch_dir, ignore_errors=True)
90
+ return counts
91
+
92
+
93
+ DATASET = DatasetSpec(
94
+ key="tpch",
95
+ title="TPC-H",
96
+ description="The TPC-H benchmark schema (orders, line items, customers, suppliers, "
97
+ "parts) generated locally by DuckDB; good for trying joins and aggregations at scale.",
98
+ load=load,
99
+ tables=TABLES,
100
+ default_schema="tpch",
101
+ options_model=TpchOptions,
102
+ size="~87k rows at scale 0.01, ~8.7M at scale 1",
103
+ )
@@ -0,0 +1,158 @@
1
+ """Web events: a synthetic clickstream (users, their sessions and the events of each
2
+ session) with devices, countries and UTM attribution."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from datetime import date, timedelta
7
+
8
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
9
+
10
+ from platybus.datasets import DatasetContext, DatasetSpec, DatasetTable
11
+ from platybus_samples._sql import create_tables, pick, rnd, weighted
12
+
13
+ #: Last day of the generated period (the period ends here, ``days`` long).
14
+ END = date(2026, 9, 30)
15
+ #: Upper bound of users x days (candidate user-days); keeps the largest load at a few
16
+ #: million sessions.
17
+ MAX_USER_DAYS = 3_000_000
18
+ #: At most this many events per session.
19
+ MAX_EVENTS = 12
20
+
21
+ COUNTRIES = [
22
+ ("US", 30), ("DE", 10), ("GB", 9), ("FR", 8), ("IN", 8), ("BR", 7), ("CA", 5),
23
+ ("NL", 4), ("ES", 4), ("PL", 4), ("JP", 4), ("AU", 3), ("SE", 2), ("MX", 2),
24
+ ] # fmt: skip
25
+ DEVICES = [("desktop", 45), ("mobile", 45), ("tablet", 10)]
26
+ BROWSERS = [("Chrome", 62), ("Safari", 20), ("Edge", 8), ("Firefox", 7), ("Other", 3)]
27
+ # (source, medium) pairs; campaigns only for paid traffic
28
+ UTM = [
29
+ ("(direct)", "(none)", 28), ("google", "organic", 25), ("google", "cpc", 12),
30
+ ("newsletter", "email", 9), ("facebook", "social", 8), ("linkedin", "social", 4),
31
+ ("partner", "referral", 6), ("facebook", "cpc", 5), ("bing", "organic", 3),
32
+ ] # fmt: skip
33
+ CAMPAIGNS = ["spring_sale", "summer_sale", "back_to_school", "brand", "retargeting"]
34
+ PAGES = ["/", "/catalog", "/product", "/product", "/product", "/search", "/blog", "/pricing"]
35
+ EVENT_TYPES = [("page_view", 55), ("click", 25), ("scroll", 12), ("add_to_cart", 8)]
36
+
37
+
38
+ class WebEventsOptions(BaseModel):
39
+ model_config = ConfigDict(extra="forbid")
40
+
41
+ days: int = Field(30, ge=1, le=365, description="Length of the period in days.")
42
+ users: int = Field(1000, ge=10, le=200_000, description="Number of users.")
43
+
44
+ @model_validator(mode="after")
45
+ def _bounded(self) -> WebEventsOptions:
46
+ if self.days * self.users > MAX_USER_DAYS:
47
+ raise ValueError(
48
+ f"days x users must be at most {MAX_USER_DAYS:,} (got {self.days * self.users:,})"
49
+ )
50
+ return self
51
+
52
+
53
+ def tables(days: int, users: int) -> list[tuple[str, str]]:
54
+ start = END - timedelta(days=days - 1)
55
+ utm_index = weighted([(str(i), w) for i, (_, _, w) in enumerate(UTM)], "r5")
56
+ sources = ", ".join(f"'{s}'" for s, _, _ in UTM)
57
+ mediums = ", ".join(f"'{m}'" for _, m, _ in UTM)
58
+ users_sql = f"""
59
+ WITH u AS (
60
+ SELECT range AS user_id, {rnd("range", 1)} AS r1, {rnd("range", 2)} AS r2,
61
+ {rnd("range", 3)} AS r3, {rnd("range", 4)} AS r4
62
+ FROM range(1, {users + 1})
63
+ )
64
+ SELECT user_id::INTEGER AS user_id,
65
+ DATE '{start.isoformat()}' - (floor(r1 * 400))::INTEGER AS signup_date,
66
+ {weighted(COUNTRIES, "r2")} AS country,
67
+ {weighted(DEVICES, "r3")} AS primary_device,
68
+ r4 < 0.12 AS is_customer
69
+ FROM u
70
+ ORDER BY user_id
71
+ """
72
+ # Each user-day is a candidate session; a user's activity level decides how often it
73
+ # becomes one (heavy users most days, most users rarely).
74
+ sessions_cte = f"""
75
+ WITH c AS (
76
+ SELECT range AS c, range % {users} + 1 AS user_id, range // {users} AS day,
77
+ {rnd("range", 11)} AS r1, {rnd("range", 12)} AS r2, {rnd("range", 13)} AS r3,
78
+ {rnd("range", 14)} AS r4, {rnd("range", 15)} AS r5, {rnd("range", 16)} AS r6,
79
+ {rnd("range", 17)} AS r7
80
+ FROM range({users * days})
81
+ ), activity AS (
82
+ SELECT range + 1 AS user_id, 0.02 + 0.6 * pow({rnd("range + 1", 18)}, 3) AS p
83
+ FROM range({users})
84
+ ), s AS (
85
+ SELECT row_number() OVER (ORDER BY c.c) AS session_id, c.*
86
+ FROM c JOIN activity a USING (user_id)
87
+ WHERE c.r1 < a.p
88
+ )"""
89
+ sessions_sql = f"""{sessions_cte}
90
+ SELECT session_id::BIGINT AS session_id,
91
+ user_id::INTEGER AS user_id,
92
+ TIMESTAMP '{start.isoformat()} 00:00:00' + to_days(day::INTEGER)
93
+ + to_seconds((floor(r2 * 86400))::BIGINT) AS started_at,
94
+ {weighted(DEVICES, "r3")} AS device,
95
+ {weighted(BROWSERS, "r4")} AS browser,
96
+ {weighted(COUNTRIES, "r6")} AS country,
97
+ ([{sources}])[1 + ({utm_index})::INTEGER] AS utm_source,
98
+ ([{mediums}])[1 + ({utm_index})::INTEGER] AS utm_medium,
99
+ CASE WHEN ([{mediums}])[1 + ({utm_index})::INTEGER] = 'cpc'
100
+ THEN {pick(CAMPAIGNS, "r7")} END AS utm_campaign,
101
+ {pick(PAGES, "r7")} AS landing_page
102
+ FROM s
103
+ ORDER BY session_id
104
+ """
105
+ events_sql = f"""{sessions_cte}, n AS (
106
+ SELECT session_id, user_id, day, r2,
107
+ 1 + floor({rnd("session_id", 21)} * {rnd("session_id", 22)} * {MAX_EVENTS})::INTEGER
108
+ AS events,
109
+ {rnd("session_id", 23)} < 0.05 AS converts
110
+ FROM s
111
+ ), e AS (
112
+ SELECT n.*, k.range AS k,
113
+ {rnd("session_id * 16 + k.range", 24)} AS q1,
114
+ {rnd("session_id * 16 + k.range", 25)} AS q2,
115
+ {rnd("session_id * 16 + k.range", 26)} AS q3
116
+ FROM n JOIN range({MAX_EVENTS}) AS k ON k.range < n.events
117
+ )
118
+ SELECT row_number() OVER (ORDER BY session_id, k)::BIGINT AS event_id,
119
+ session_id::BIGINT AS session_id,
120
+ user_id::INTEGER AS user_id,
121
+ TIMESTAMP '{start.isoformat()} 00:00:00' + to_days(day::INTEGER)
122
+ + to_seconds((floor(r2 * 86400) + k * 40 + floor(q1 * 30))::BIGINT) AS event_time,
123
+ CASE WHEN k = 0 THEN 'page_view'
124
+ WHEN converts AND events >= 3 AND k = events - 1 THEN 'purchase'
125
+ ELSE {weighted(EVENT_TYPES, "q2")} END AS event_type,
126
+ CASE WHEN converts AND events >= 3 AND k = events - 1 THEN '/checkout'
127
+ ELSE {pick(PAGES, "q3")} END AS page,
128
+ CASE WHEN converts AND events >= 3 AND k = events - 1
129
+ THEN round(10 + q1 * 240, 2)::DECIMAL(10, 2)
130
+ ELSE 0::DECIMAL(10, 2) END AS revenue
131
+ FROM e
132
+ ORDER BY event_id
133
+ """
134
+ return [("users", users_sql), ("sessions", sessions_sql), ("events", events_sql)]
135
+
136
+
137
+ def load(ctx: DatasetContext) -> dict[str, int]:
138
+ days = int(ctx.options.get("days", 30))
139
+ users = int(ctx.options.get("users", 1000))
140
+ return create_tables(ctx, tables(days, users))
141
+
142
+
143
+ DATASET = DatasetSpec(
144
+ key="web_events",
145
+ title="Web events",
146
+ description="A synthetic clickstream: users, their sessions (device, browser, country, "
147
+ "UTM source / medium / campaign, landing page) and the events of each session "
148
+ "(page views, clicks, add to cart, purchases with revenue).",
149
+ load=load,
150
+ tables=(
151
+ DatasetTable("users", "Users with signup date, country and primary device."),
152
+ DatasetTable("sessions", "Sessions with device, browser, country and UTM attribution."),
153
+ DatasetTable("events", "Events of each session; purchases carry revenue."),
154
+ ),
155
+ default_schema="web",
156
+ options_model=WebEventsOptions,
157
+ size="~24k rows by default (30 days, 1000 users)",
158
+ )
@@ -0,0 +1,72 @@
1
+ """Fixtures for the sample dataset tests: projects on different store types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ from samples_testkit import LimitedStore, limited_store
10
+
11
+ from platybus.config import Project, load_project
12
+ from platybus.config.stores import StoreConfig, StoresFile, dump_stores
13
+ from platybus.engine import Engine
14
+ from platybus.scaffold import create_project
15
+ from platybus.stores import StoreSpec, register_store
16
+ from platybus.stores.registry import _REGISTRY
17
+
18
+
19
+ @pytest.fixture(autouse=True)
20
+ def _sql_transform(monkeypatch: pytest.MonkeyPatch) -> None:
21
+ monkeypatch.setenv("PLATYBUS_TRANSFORM", "sql")
22
+
23
+
24
+ @pytest.fixture
25
+ def limited_type() -> Iterator[None]:
26
+ register_store(
27
+ StoreSpec(
28
+ key="limited",
29
+ title="Limited",
30
+ category="lakehouse",
31
+ factory=limited_store,
32
+ capabilities=LimitedStore.capabilities,
33
+ zero_config=True,
34
+ )
35
+ )
36
+ yield
37
+ _REGISTRY.pop("limited", None)
38
+
39
+
40
+ @pytest.fixture
41
+ def project_dir(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[Path]:
42
+ root = tmp_path / "demo"
43
+ create_project(root)
44
+ monkeypatch.chdir(root)
45
+ yield root
46
+
47
+
48
+ @pytest.fixture(params=["ducklake", "duckdb", "limited"])
49
+ def store_project(request: pytest.FixtureRequest, project_dir: Path, limited_type: None) -> Project:
50
+ """The fixture project with its primary store of each kind."""
51
+ store_type = str(request.param)
52
+ if store_type != "ducklake":
53
+ stores = {"wh": StoreConfig.model_validate({"type": store_type})}
54
+ dump_stores(project_dir / "stores.yml", StoresFile(default="wh", stores=stores))
55
+ return load_project(project_dir)
56
+
57
+
58
+ @pytest.fixture
59
+ def store_engine(store_project: Project) -> Iterator[Engine]:
60
+ with Engine.open(store_project) as eng:
61
+ yield eng
62
+
63
+
64
+ @pytest.fixture
65
+ def project(project_dir: Path) -> Project:
66
+ return load_project(project_dir)
67
+
68
+
69
+ @pytest.fixture
70
+ def engine(project: Project) -> Iterator[Engine]:
71
+ with Engine.open(project) as eng:
72
+ yield eng
@@ -0,0 +1,40 @@
1
+ """Shared data of the sample dataset tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from platybus.stores import BaseStore, StoreCapabilities, StoreContext
6
+ from platybus.stores.builtin import DuckDBStore
7
+
8
+ #: Smallest size of every dataset and the row counts it gives (deterministic).
9
+ SMALLEST: dict[str, tuple[dict[str, object], dict[str, int]]] = {
10
+ "tpch": (
11
+ {"scale": 0.01},
12
+ {
13
+ "region": 5,
14
+ "nation": 25,
15
+ "supplier": 100,
16
+ "customer": 1500,
17
+ "part": 2000,
18
+ "partsupp": 8000,
19
+ "orders": 15000,
20
+ "lineitem": 60175,
21
+ },
22
+ ),
23
+ "jaffle_shop": (
24
+ {"customers": 10, "orders": 50},
25
+ {"customers": 10, "orders": 50, "payments": 56},
26
+ ),
27
+ "web_events": ({"days": 1, "users": 10}, {"users": 10, "sessions": 5, "events": 31}),
28
+ "taxi_trips": ({"rows": 100}, {"zones": 24, "trips": 100}),
29
+ }
30
+
31
+
32
+ class LimitedStore(DuckDBStore):
33
+ """A DuckDB file that pretends to lack REPLACE, views and MERGE (like Iceberg)."""
34
+
35
+ type = "limited"
36
+ capabilities = StoreCapabilities(replace_table=False, views=False, merge=False)
37
+
38
+
39
+ def limited_store(context: StoreContext) -> BaseStore:
40
+ return LimitedStore(context.name, context.state_dir / "limited.duckdb")
@@ -0,0 +1,58 @@
1
+ """Smoke test of scripts/benchmark.py (TPC-H on DuckLake) at the smallest scale."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from types import ModuleType
10
+
11
+ import pytest
12
+
13
+ SCRIPT = Path(__file__).resolve().parents[3] / "scripts" / "benchmark.py"
14
+
15
+
16
+ def _load_script() -> ModuleType:
17
+ spec = importlib.util.spec_from_file_location("platybus_benchmark_script", SCRIPT)
18
+ assert spec is not None and spec.loader is not None
19
+ module = importlib.util.module_from_spec(spec)
20
+ sys.modules[spec.name] = module # dataclasses resolve annotations through sys.modules
21
+ spec.loader.exec_module(module)
22
+ return module
23
+
24
+
25
+ @pytest.fixture(scope="module")
26
+ def bench() -> ModuleType:
27
+ return _load_script()
28
+
29
+
30
+ def test_benchmark_smoke(
31
+ bench: ModuleType, tmp_path: Path, capsys: pytest.CaptureFixture[str]
32
+ ) -> None:
33
+ out = tmp_path / "result.json"
34
+ code = bench.main(
35
+ ["--scale", "0.01", "--runs", "1", "--workdir", str(tmp_path / "bench"), "--json", str(out)]
36
+ )
37
+ assert code == 0
38
+ data = json.loads(out.read_text(encoding="utf-8"))
39
+ assert data["scale"] == 0.01
40
+ assert data["rows_loaded"] == 86_805
41
+ assert len(data["queries"]) == 22
42
+ assert all(q["rows"] > 0 and len(q["seconds"]) == 1 for q in data["queries"])
43
+ assert data["disk_bytes"] > 0
44
+ assert data["load_seconds"] > 0 and data["query_total_seconds"] > 0
45
+ machine = data["machine"]
46
+ assert machine["cores_logical"] and machine["duckdb"] and machine["platybus"]
47
+ report = capsys.readouterr().out
48
+ assert "TPC-H scale factor 0.01" in report and "| Q22 |" in report
49
+
50
+
51
+ def test_benchmark_rejects_unknown_scale(bench: ModuleType) -> None:
52
+ with pytest.raises(ValueError, match="scale must be one of"):
53
+ bench.run_benchmark(0.5)
54
+
55
+
56
+ def test_peak_rss_is_reported(bench: ModuleType) -> None:
57
+ peak = bench.peak_rss_bytes()
58
+ assert peak is None or peak > 1_000_000
@@ -0,0 +1,112 @@
1
+ """Sample datasets through the hub API and the CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Iterator
7
+ from pathlib import Path
8
+
9
+ import pytest
10
+ from fastapi.testclient import TestClient
11
+ from samples_testkit import SMALLEST
12
+ from typer.testing import CliRunner
13
+
14
+ from platybus.cli import app as cli_app
15
+ from platybus.hub import Hub
16
+ from platybus.server import create_app
17
+
18
+ HOST = "http://127.0.0.1"
19
+
20
+
21
+ @pytest.fixture
22
+ def api(tmp_path: Path) -> Iterator[TestClient]:
23
+ with TestClient(create_app(Hub.init(tmp_path / "hub"), services=[]), base_url=HOST) as client:
24
+ yield client
25
+
26
+
27
+ def test_datasets_are_listed(api: TestClient) -> None:
28
+ datasets = {d["key"]: d for d in api.get("/api/datasets").json()}
29
+ assert {"tpch", "jaffle_shop", "web_events", "taxi_trips"} <= set(datasets)
30
+ tpch = datasets["tpch"]
31
+ assert tpch["default_schema"] == "tpch" and tpch["size"]
32
+ assert {t["name"] for t in tpch["tables"]} == set(SMALLEST["tpch"][1])
33
+ scale = tpch["options_schema"]["properties"]["scale"]
34
+ assert scale["default"] == 0.01 and scale["enum"] == [0.01, 0.1, 1.0]
35
+ web = datasets["web_events"]["options_schema"]["properties"]
36
+ assert web["days"]["maximum"] == 365 and web["users"]["minimum"] == 10
37
+
38
+
39
+ def test_load_tpch_into_a_project(api: TestClient) -> None:
40
+ created = api.post("/api/projects", json={"id": "bench", "transform": "sql"})
41
+ assert created.status_code == 201, created.text
42
+ resp = api.post("/api/projects/bench/datasets/tpch:load", json={"options": {"scale": 0.01}})
43
+ assert resp.status_code == 200, resp.text
44
+ body = resp.json()
45
+ assert body["dataset"] == "tpch" and body["schema"] == "tpch" and body["store"] == "lake"
46
+ assert body["tables"] == SMALLEST["tpch"][1] and body["elapsed_ms"] > 0
47
+ rows = api.post(
48
+ "/api/projects/bench/sql", json={"sql": "select count(*) from tpch.lineitem"}
49
+ ).json()["rows"]
50
+ assert rows == [[60175]]
51
+
52
+
53
+ def test_invalid_options_are_400(api: TestClient) -> None:
54
+ api.post("/api/projects", json={"id": "bench", "transform": "sql"})
55
+ resp = api.post("/api/projects/bench/datasets/tpch:load", json={"options": {"scale": 3}})
56
+ assert resp.status_code == 400
57
+ assert "scale must be one of" in resp.json()["error"]["message"]
58
+ resp = api.post("/api/projects/bench/datasets/nope:load", json={})
59
+ assert resp.status_code == 404
60
+
61
+
62
+ def test_create_project_with_a_dataset(api: TestClient) -> None:
63
+ resp = api.post(
64
+ "/api/projects",
65
+ json={
66
+ "id": "clicks",
67
+ "transform": "sql",
68
+ "dataset": {
69
+ "name": "web_events",
70
+ "schema": "clicks",
71
+ "options": {"days": 1, "users": 10},
72
+ },
73
+ },
74
+ )
75
+ assert resp.status_code == 201, resp.text
76
+ body = resp.json()
77
+ assert body["dataset_error"] is None
78
+ assert body["dataset"]["schema"] == "clicks"
79
+ assert body["dataset"]["tables"] == SMALLEST["web_events"][1]
80
+
81
+
82
+ # ---------------------------------------------------------------------- CLI
83
+ cli = CliRunner()
84
+
85
+
86
+ def test_cli_lists_datasets(project_dir: Path) -> None:
87
+ result = cli.invoke(cli_app, ["datasets", "--json"])
88
+ assert result.exit_code == 0, result.output
89
+ keys = {d["key"] for d in json.loads(result.output)}
90
+ assert {"tpch", "jaffle_shop", "web_events", "taxi_trips"} <= keys
91
+ result = cli.invoke(cli_app, ["datasets"])
92
+ assert result.exit_code == 0 and "taxi_trips" in result.output
93
+
94
+
95
+ def test_cli_loads_a_dataset(project_dir: Path) -> None:
96
+ result = cli.invoke(
97
+ cli_app,
98
+ ["datasets", "load", "taxi_trips", "--set", "rows=100", "--schema", "rides", "--json"],
99
+ )
100
+ assert result.exit_code == 0, result.output
101
+ data = json.loads(result.output)
102
+ assert data["schema"] == "rides" and data["tables"] == SMALLEST["taxi_trips"][1]
103
+ result = cli.invoke(cli_app, ["datasets", "load", "jaffle_shop", "--set", "orders=50"])
104
+ assert result.exit_code == 0, result.output
105
+ assert "Loaded jaffle_shop" in result.output and "payments" in result.output
106
+
107
+
108
+ def test_cli_rejects_bad_options(project_dir: Path) -> None:
109
+ result = cli.invoke(cli_app, ["datasets", "load", "taxi_trips", "--set", "rows"])
110
+ assert result.exit_code != 0 and "key=value" in result.output
111
+ result = cli.invoke(cli_app, ["datasets", "load", "taxi_trips", "--set", "rows=5"])
112
+ assert result.exit_code != 0 and "rows" in result.output
@@ -0,0 +1,128 @@
1
+ """Loading every sample dataset into different store types."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import csv
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+ from samples_testkit import SMALLEST
10
+
11
+ from platybus.config import Project
12
+ from platybus.datasets import dataset_spec, dataset_specs, load_dataset
13
+ from platybus.engine import Engine
14
+ from platybus.errors import InvalidRequestError, PipelineError
15
+ from platybus_samples import jaffle
16
+
17
+ REPO = Path(__file__).resolve().parents[3]
18
+
19
+
20
+ def _counts(engine: Engine, schema: str, tables: list[str]) -> dict[str, int]:
21
+ return {t: int(engine.execute(f"select count(*) from {schema}.{t}").scalar()) for t in tables}
22
+
23
+
24
+ def test_specs_are_registered() -> None:
25
+ keys = {spec.key for spec in dataset_specs()}
26
+ assert {"tpch", "jaffle_shop", "web_events", "taxi_trips"} <= keys
27
+ for key in SMALLEST:
28
+ spec = dataset_spec(key)
29
+ assert spec.options_model is not None and spec.size and spec.default_schema
30
+ assert spec.tables and all(t.description for t in spec.tables)
31
+ assert set(SMALLEST[key][1]) == {t.name for t in spec.tables}
32
+ spec.options_model.model_validate({}) # defaults are valid
33
+
34
+
35
+ @pytest.mark.parametrize("key", list(SMALLEST))
36
+ def test_load_smallest_into_each_store(
37
+ key: str, store_project: Project, store_engine: Engine
38
+ ) -> None:
39
+ options, expected = SMALLEST[key]
40
+ result = load_dataset(store_engine, store_project, key, options=options)
41
+ assert result.store == store_engine.primary.name
42
+ assert result.schema == dataset_spec(key).default_schema
43
+ assert result.tables == expected
44
+ assert _counts(store_engine, result.schema, list(expected)) == expected
45
+ # reloading replaces the tables (no duplicates), into a schema of the caller's choice
46
+ again = load_dataset(store_engine, store_project, key, schema="again", options=options)
47
+ assert again.tables == expected
48
+ load_dataset(store_engine, store_project, key, schema="again", options=options)
49
+ assert _counts(store_engine, "again", list(expected)) == expected
50
+
51
+
52
+ @pytest.mark.parametrize("key", ["jaffle_shop", "web_events", "taxi_trips"])
53
+ def test_loads_are_deterministic(key: str, project: Project, engine: Engine) -> None:
54
+ options, expected = SMALLEST[key]
55
+ digests = []
56
+ for schema in ("one", "two"):
57
+ load_dataset(engine, project, key, schema=schema, options=options)
58
+ digests.append(
59
+ {
60
+ t: engine.execute(
61
+ f"select sum(hash(columns(*))) from (select * from {schema}.{t})"
62
+ ).rows()[0]
63
+ for t in expected
64
+ }
65
+ )
66
+ assert digests[0] == digests[1]
67
+
68
+
69
+ def test_options_are_sized(project: Project, engine: Engine) -> None:
70
+ web = load_dataset(engine, project, "web_events", options={"days": "7", "users": "50"})
71
+ assert web.tables == {"users": 50, "sessions": 89, "events": 365}
72
+ taxi = load_dataset(engine, project, "taxi_trips", options={"rows": 2500})
73
+ assert taxi.tables["trips"] == 2500
74
+ sane = engine.execute(
75
+ "select bool_and(dropoff_at > pickup_at), bool_and(fare_amount > 0), "
76
+ "bool_and(tip_amount = 0 or payment_type in ('card', 'app')), "
77
+ "count(distinct pickup_zone_id) > 10 from taxi.trips"
78
+ ).rows()[0]
79
+ assert sane == (True, True, True, True)
80
+ orphans = engine.execute(
81
+ "select count(*) from web.events e anti join web.sessions s using (session_id)"
82
+ ).scalar()
83
+ assert orphans == 0
84
+
85
+
86
+ @pytest.mark.parametrize(
87
+ ("key", "options", "message"),
88
+ [
89
+ ("tpch", {"scale": 0.5}, "scale must be one of 0.01, 0.1, 1"),
90
+ ("tpch", {"scale": "big"}, "scale"),
91
+ ("tpch", {"sf": 1}, "sf"),
92
+ ("jaffle_shop", {"orders": 0}, "orders"),
93
+ ("web_events", {"days": 400}, "days"),
94
+ ("web_events", {"days": 365, "users": 200_000}, "days x users must be at most"),
95
+ ("taxi_trips", {"rows": 10**9}, "rows"),
96
+ ],
97
+ )
98
+ def test_invalid_options(
99
+ key: str, options: dict[str, object], message: str, project: Project, engine: Engine
100
+ ) -> None:
101
+ with pytest.raises(InvalidRequestError, match=message) as info:
102
+ load_dataset(engine, project, key, options=options)
103
+ assert info.value.status_code == 400
104
+
105
+
106
+ def test_jaffle_default_size_matches_the_example_seeds() -> None:
107
+ rows = jaffle.generate()
108
+ seeds = REPO / "examples" / "jaffle-shop" / "seeds"
109
+ with (seeds / "raw_orders.csv").open(encoding="utf-8") as fh:
110
+ orders = [tuple(r) for r in csv.reader(fh)][1:]
111
+ assert orders == [(str(i), str(u), d.isoformat(), s) for i, u, d, s in rows.orders]
112
+ with (seeds / "raw_payments.csv").open(encoding="utf-8") as fh:
113
+ payments = [tuple(r) for r in csv.reader(fh)][1:]
114
+ assert payments == [tuple(str(v) for v in p) for p in rows.payments]
115
+
116
+
117
+ def test_tpch_without_the_extension(
118
+ project: Project, engine: Engine, monkeypatch: pytest.MonkeyPatch
119
+ ) -> None:
120
+ from platybus.errors import CatalogError
121
+ from platybus_samples import tpch
122
+
123
+ def broken(con: object, name: str) -> None:
124
+ raise CatalogError("cannot install DuckDB extension 'tpch': offline")
125
+
126
+ monkeypatch.setattr(tpch, "load_extension", broken)
127
+ with pytest.raises(PipelineError, match="needs the DuckDB 'tpch' extension"):
128
+ load_dataset(engine, project, "tpch")