platybus-samples 0.1.1__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.
- platybus_samples/__init__.py +26 -0
- platybus_samples/_sql.py +54 -0
- platybus_samples/jaffle.py +157 -0
- platybus_samples/py.typed +0 -0
- platybus_samples/taxi.py +113 -0
- platybus_samples/tpch.py +103 -0
- platybus_samples/web_events.py +158 -0
- platybus_samples-0.1.1.dist-info/METADATA +41 -0
- platybus_samples-0.1.1.dist-info/RECORD +12 -0
- platybus_samples-0.1.1.dist-info/WHEEL +4 -0
- platybus_samples-0.1.1.dist-info/entry_points.txt +2 -0
- platybus_samples-0.1.1.dist-info/licenses/LICENSE +21 -0
|
@@ -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"]
|
platybus_samples/_sql.py
ADDED
|
@@ -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
|
platybus_samples/taxi.py
ADDED
|
@@ -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
|
+
)
|
platybus_samples/tpch.py
ADDED
|
@@ -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,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,12 @@
|
|
|
1
|
+
platybus_samples/__init__.py,sha256=ZCG5vOQItcKaB0zeR3ufe-6OEPkHijXqXP2VoMN0Fi0,930
|
|
2
|
+
platybus_samples/_sql.py,sha256=f7X9qbJ57IbXM8BAb-V1wfNas4nZApTu3Td42BgsrCM,2156
|
|
3
|
+
platybus_samples/jaffle.py,sha256=d9SaBAKRNChIDOEa42xWcHlYekGq6faEg78F36I7NeY,6125
|
|
4
|
+
platybus_samples/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
platybus_samples/taxi.py,sha256=YuHqVN9gczOeKB5xnhqNt0NI_a58ZBUjh-zedfRpeBc,4616
|
|
6
|
+
platybus_samples/tpch.py,sha256=U9kYGc0aiMBpv5-0Fw3e9Ter_RuJpd5mn92Fx3zjvLI,3946
|
|
7
|
+
platybus_samples/web_events.py,sha256=RdQ8vrBYwtYraBvcnGl3c2qs-437TFRSOj6NgGMjOZ8,6848
|
|
8
|
+
platybus_samples-0.1.1.dist-info/METADATA,sha256=qqKb1XboOBDJEQ2SOG7kgdnQImrqBEJ7ElmK1xZXwb4,1684
|
|
9
|
+
platybus_samples-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
10
|
+
platybus_samples-0.1.1.dist-info/entry_points.txt,sha256=Zogeu1bfLETI-MuFkNdvLmjzKpj4h6I-BzyfqeUrLDw,53
|
|
11
|
+
platybus_samples-0.1.1.dist-info/licenses/LICENSE,sha256=1GSdi_XmZ_go3KCNsqt6OJpYJBXDmJCdR4XMnWUWTTY,1072
|
|
12
|
+
platybus_samples-0.1.1.dist-info/RECORD,,
|
|
@@ -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.
|