PDS-H queries

Results

One table per run of the full benchmark on someone's machine: for each query, the best of the timed runs, in seconds, reading the CSV files included. A dash means the run did not use that engine: older runs timed Nanuq with one engine only, and runs with Nanuq 0.2 have 13 queries, so compare totals only between runs with the same number of queries.

2026-10-31 (claude-sandbox), scale factor 1.0

Intel(R) Xeon(R) Processor @ 2.10GHz, 4 cores, 16.9 GB, Linux 6.18.44-fc-v185. Nanuq 0.2.0, Polars 2.1.0, Nim 2.2.4.

Query Nanuq in-memory Nanuq streaming Python in-memory Python streaming
q1 2.13 s - 0.76 s 0.71 s
q3 1.99 s - 0.76 s 0.74 s
q4 1.98 s - 0.79 s 0.70 s
q5 1.96 s - 0.59 s 0.60 s
q6 1.94 s - 0.53 s 0.53 s
q10 2.01 s - 0.80 s 0.76 s
q11 0.33 s - 0.11 s 0.09 s
q12 2.03 s - 0.74 s 0.79 s
q15 1.94 s - 0.55 s 0.60 s
q17 2.03 s - 0.44 s 0.46 s
q18 2.51 s - 0.73 s 0.94 s
q19 2.04 s - 0.67 s 0.67 s
q21 4.44 s - 1.44 s 1.44 s
total 27.32 s - 8.90 s 9.03 s

2026-10-31 (pietro-mac), scale factor 1.0

Apple M3 Pro, 11 cores, 19.3 GB, macOS 15.7.3. Nanuq 0.2.0, Polars 2.1.0, Nim 2.2.5.

Query Nanuq in-memory Nanuq streaming Python in-memory Python streaming
q1 1.07 s - 0.25 s 0.23 s
q3 1.02 s - 0.23 s 0.25 s
q4 1.02 s - 0.26 s 0.25 s
q5 1.01 s - 0.21 s 0.22 s
q6 1.00 s - 0.21 s 0.21 s
q10 1.02 s - 0.24 s 0.24 s
q11 0.17 s - 0.03 s 0.03 s
q12 1.02 s - 0.27 s 0.27 s
q15 1.00 s - 0.22 s 0.21 s
q17 1.00 s - 0.18 s 0.18 s
q18 1.22 s - 0.26 s 0.30 s
q19 1.02 s - 0.27 s 0.28 s
q21 2.18 s - 0.54 s 0.45 s
total 13.76 s - 3.16 s 3.09 s

2026-11-02 (claude-sandbox), scale factor 1.0

Intel(R) Xeon(R) Processor @ 2.80GHz, 4 cores, 16.9 GB, Linux 6.18.44-fc-v185. Nanuq 0.6.0, Polars 2.1.0, Nim 2.2.4.

Query Nanuq in-memory Nanuq streaming Python in-memory Python streaming
q1 - 1.56 s 1.60 s 1.38 s
q2 - 0.21 s 0.14 s 0.14 s
q3 - 1.56 s 1.41 s 1.39 s
q4 - 1.45 s 1.37 s 1.21 s
q5 - 1.22 s 1.21 s 1.10 s
q6 - 1.43 s 1.15 s 1.17 s
q7 - 1.54 s 1.36 s 1.49 s
q8 - 1.46 s 1.20 s 1.30 s
q9 - 1.68 s 2.13 s 1.66 s
q10 - 1.61 s 1.51 s 1.37 s
q11 - 0.20 s 0.18 s 0.19 s
q12 - 1.83 s 1.64 s 1.51 s
q13 - 0.41 s 0.45 s 0.34 s
q14 - 1.38 s 1.19 s 1.20 s
q15 - 1.31 s 1.20 s 1.08 s
q16 - 0.18 s 0.18 s 0.16 s
q17 - 0.92 s 1.01 s 0.81 s
q18 - 1.80 s 1.43 s 1.74 s
q19 - 1.48 s 0.99 s 1.11 s
q20 - 1.47 s 1.29 s 1.36 s
q21 - 2.66 s 2.47 s 2.46 s
q22 - 0.22 s 0.20 s 0.19 s
total - 27.61 s 25.31 s 24.36 s

2026-11-02 (pietro-mac), scale factor 1.0

Apple M3 Pro, 11 cores, 19.3 GB, macOS 15.7.3. Nanuq 0.6.0, Polars 2.1.0, Nim 2.2.5.

Query Nanuq in-memory Nanuq streaming Python in-memory Python streaming
q1 0.29 s 0.25 s 0.28 s 0.23 s
q2 0.03 s 0.03 s 0.03 s 0.03 s
q3 0.27 s 0.26 s 0.26 s 0.26 s
q4 0.27 s 0.25 s 0.27 s 0.24 s
q5 0.20 s 0.20 s 0.21 s 0.20 s
q6 0.22 s 0.21 s 0.21 s 0.23 s
q7 0.25 s 0.26 s 0.26 s 0.27 s
q8 0.22 s 0.22 s 0.23 s 0.22 s
q9 0.32 s 0.33 s 0.33 s 0.28 s
q10 0.25 s 0.24 s 0.23 s 0.23 s
q11 0.03 s 0.03 s 0.03 s 0.03 s
q12 0.31 s 0.30 s 0.29 s 0.31 s
q13 0.07 s 0.06 s 0.08 s 0.06 s
q14 0.25 s 0.23 s 0.24 s 0.22 s
q15 0.21 s 0.20 s 0.23 s 0.22 s
q16 0.03 s 0.03 s 0.03 s 0.03 s
q17 0.17 s 0.16 s 0.19 s 0.17 s
q18 0.24 s 0.30 s 0.24 s 0.29 s
q19 0.26 s 0.27 s 0.26 s 0.26 s
q20 0.28 s 0.25 s 0.28 s 0.25 s
q21 0.57 s 0.51 s 0.55 s 0.49 s
q22 0.04 s 0.03 s 0.04 s 0.04 s
total 4.78 s 4.61 s 4.76 s 4.55 s

How the tables are made

Each run of the full benchmark leaves a JSON file in results/pdsh/, with the machine, the versions and, for each engine and query, three timings. The tables above are a Polars query over those files, so they come from the same tools as everything else in this book.

The timings are two structs deep: engines, then queries. Two rounds of unnest and unpivot turn each file into a long table with one row per engine and query, and list.min keeps the best of the timed runs:

let index = @["date", "machine", "cpu", "nanuq", "scale"]

proc timings(path: string): DataFrame =
  readJson(path)
    .select(
      col.timestamp.str.slice(0, 10).alias("date"),
      col.label.alias("machine"),
      col.system.struct.field("cpu"),
      col.versions.struct.field("nanuqWrapper").alias("nanuq"),
      col.params.struct.field("scaleFactor").alias("scale"),
      col.timings)
    .unnest("timings")
    .unpivot(index = index, variableName = "engine", valueName = "queries")
    .unnest("queries")
    .unpivot(index = index & "engine", variableName = "query", valueName = "seconds")

let paths = sorted(toSeq(walkFiles("../results/pdsh/*.json")))
let times = concat(paths.mapIt(timings(it)), how = ConcatMethod.Vertical)
  .withColumns(col.seconds.list.min)
nbShow times.head(3)
shape: (3, 8)
datemachinecpunanuqscaleenginequeryseconds
strstrstrstrf64strstrf64
"2026-10-31""claude-sandbox""Intel(R) Xeon(R) Processor @ 2…"0.2.0"1.0"nanuq in-memory""q1"2.126872
"2026-10-31""claude-sandbox""Intel(R) Xeon(R) Processor @ 2…"0.2.0"1.0"python in-memory""q1"0.758044
"2026-10-31""claude-sandbox""Intel(R) Xeon(R) Processor @ 2…"0.2.0"1.0"python streaming""q1"0.707311

Summing per run and engine, and a pivot with one column per engine, gives the total time of each run:

nbShow times
  .groupBy(index & "engine", maintainOrder = true)
  .agg(len().alias("queries"), col.seconds.sum.round(2))
  .pivot(on = "engine", index = index & "queries", values = "seconds", sortColumns = true)
shape: (4, 10)
datemachinecpunanuqscalequeriesnanuq in-memorynanuq streamingpython in-memorypython streaming
strstrstrstrf64u32f64f64f64f64
"2026-10-31""claude-sandbox""Intel(R) Xeon(R) Processor @ 2…"0.2.0"1.01327.32null8.99.03
"2026-10-31""pietro-mac""Apple M3 Pro""0.2.0"1.01313.76null3.163.09
"2026-11-02""claude-sandbox""Intel(R) Xeon(R) Processor @ 2…"0.6.0"1.022null27.6125.3124.36
"2026-11-02""pietro-mac""Apple M3 Pro""0.6.0"1.0224.784.614.764.55

And query by query, on the latest run on an M3 Pro:

let byQuery = times
  .filter(col.machine == "pietro-mac")
  .filter(col.date == col.date.max)
  .withColumns(col.seconds.round(3))
  .pivot(on = "engine", index = "query", values = "seconds", sortColumns = true)
shape: (22, 5)
querynanuq in-memorynanuq streamingpython in-memorypython streaming
strf64f64f64f64
"q1"0.2850.2550.280.234
"q2"0.0280.0270.0280.027
"q3"0.2690.2570.2610.257
"q4"0.2670.250.2730.242
"q5"0.2020.1960.2080.202
"q6"0.2230.2140.2120.231
"q7"0.2460.2560.2580.265
"q8"0.2220.220.2260.215
"q9"0.3240.3270.3330.28
"q10"0.2470.2420.2340.228
"q11"0.0290.0260.0290.026
"q12"0.3050.2980.2860.305
"q13"0.0740.0610.0780.064
"q14"0.2480.2260.2390.224
"q15"0.2140.2010.2280.224
"q16"0.0290.0270.030.028
"q17"0.1730.1620.1890.17
"q18"0.2390.3030.2380.294
"q19"0.2640.2660.2620.264
"q20"0.2780.2540.2760.249
"q21"0.570.5090.5510.486
"q22"0.0430.0340.0430.035

The benchmark

TPC-H is the classic decision-support benchmark: eight tables of a wholesale business (orders, line items, customers, suppliers, parts and the nations and regions they are in) and 22 queries that report on them. Polars publishes how fast it runs them as PDS-H, with its queries in the polars-benchmark repository.

Nanuq 0.3 runs all 22. (Nanuq 0.2 ran 13 of them: the others need string functions or the year of a date, which came with 0.3.)

The queries are in bench/pdsh.nim and bench/pdsh.py. When the book is built, each one runs on both sides on a small dataset (scale factor 0.01, about 10 MB of CSV), and the build checks that the two tables are the same.

Q1

proc q1*(t: Tables): LazyFrame =
  let var1 = date(1998, 9, 2)
  t.lineitem.filter(col.l_shipdate <= var1)
    .groupBy(col.l_returnflag, col.l_linestatus)
    .agg(
      col.l_quantity.sum.alias("sum_qty"),
      col.l_extendedprice.sum.alias("sum_base_price"),
      (col.l_extendedprice * (1.0 - col.l_discount)).sum.alias("sum_disc_price"),
      (col.l_extendedprice * (1.0 - col.l_discount) * (1.0 + col.l_tax))
        .sum.alias("sum_charge"),
      col.l_quantity.mean.alias("avg_qty"),
      col.l_extendedprice.mean.alias("avg_price"),
      col.l_discount.mean.alias("avg_disc"),
      col.l_orderkey.len.alias("count_order"))
    .sort(["l_returnflag", "l_linestatus"])
shape: (4, 10)
l_returnflagl_linestatussum_qtysum_base_pricesum_disc_pricesum_chargeavg_qtyavg_priceavg_disccount_order
strstri64f64f64f64f64f64f64u32
"A""F"3804565.3235e85.0582e85.2617e825.57515535785.7093070.05008114876
"N""F"89711.2385e71.1798e71.2282e725.77873635588.5096840.047759348
"N""O"7428021.0415e99.8974e81.0294e925.45498835691.1292090.04993129181
"R""F"3814495.3459e85.0800e85.2852e825.59716835874.0065330.04982814902

Q2

proc q2*(t: Tables): LazyFrame =
  let var1 = 15
  let var2 = "BRASS"
  let var3 = "EUROPE"
  let q1 = t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .join(t.region, leftOn = ["n_regionkey"], rightOn = ["r_regionkey"])
    .filter(col.p_size == var1)
    .filter(col.p_type.str.endsWith(var2))
    .filter(col.r_name == var3)
  q1.groupBy(col.p_partkey)
    .agg(col.ps_supplycost.min)
    .join(q1, on = ["p_partkey", "ps_supplycost"])
    .select(col.s_acctbal, col.s_name, col.n_name, col.p_partkey, col.p_mfgr,
            col.s_address, col.s_phone, col.s_comment)
    .sort(["s_acctbal", "n_name", "s_name", "p_partkey"],
          descending = [true, false, false, false])
    .head(100)
shape: (4, 8)
s_acctbals_namen_namep_partkeyp_mfgrs_addresss_phones_comment
f64strstri64strstrstrstr
4186.95"Supplier#000000077""GERMANY"249"Manufacturer#4""wVtcr0uH3CyrSiWMLsqnB09Syo,UuZ…"17-281-345-4863""the slyly final asymptotes. bl…
1883.37"Supplier#000000086""ROMANIA"1015"Manufacturer#4""J1fgg5QaqnN""29-903-665-7065""cajole furiously special, fina…
1687.81"Supplier#000000017""ROMANIA"1634"Manufacturer#2""c2d,ESHRSkK3WYnxpgw6aOqN0q""29-601-884-9219""eep against the furiously bold…
287.16"Supplier#000000052""ROMANIA"323"Manufacturer#4""WCk XCHYzBA1dvJDSol4ZJQQcQN,""29-974-934-4713""dolites are slyly against the …

Q3

proc q3*(t: Tables): LazyFrame =
  let var1 = "BUILDING"
  let var2 = date(1995, 3, 15)
  t.customer.filter(col.c_mktsegment == var1)
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .filter(col.o_orderdate < var2)
    .filter(col.l_shipdate > var2)
    .withColumns((col.l_extendedprice * (1 - col.l_discount)).alias("revenue"))
    .groupBy(col.o_orderkey, col.o_orderdate, col.o_shippriority)
    .agg(col.revenue.sum)
    .select(col.o_orderkey.alias("l_orderkey"), col.revenue, col.o_orderdate,
            col.o_shippriority)
    .sort(["revenue", "o_orderdate"], descending = [true, false])
    .head(10)
shape: (10, 4)
l_orderkeyrevenueo_orderdateo_shippriority
i64f64datei64
47714267010.58941995-03-110
22276266351.55621995-01-290
32965263768.34141995-02-250
21956254541.12851995-02-020
1637243512.79811995-02-080
10916241320.08141995-03-110
30497208566.69691995-02-070
450205447.42321995-03-050
47204204478.52131995-03-130
9696201502.21881995-02-200

Q4

proc q4*(t: Tables): LazyFrame =
  let var1 = date(1993, 7, 1)
  let var2 = date(1993, 10, 1)
  # SQL exists translates to semi join in Polars API
  t.orders.join(t.lineitem.filter(col.l_commitdate < col.l_receiptdate),
                leftOn = ["o_orderkey"], rightOn = ["l_orderkey"], how = Semi)
    .filter(col.o_orderdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.o_orderpriority)
    .agg(col.o_orderkey.len.alias("order_count"))
    .sort("o_orderpriority")
shape: (5, 2)
o_orderpriorityorder_count
stru32
"1-URGENT"93
"2-HIGH"103
"3-MEDIUM"109
"4-NOT SPECIFIED"102
"5-LOW"128

Q5

proc q5*(t: Tables): LazyFrame =
  let var1 = "ASIA"
  let var2 = date(1994, 1, 1)
  let var3 = date(1995, 1, 1)
  t.region.join(t.nation, leftOn = ["r_regionkey"], rightOn = ["n_regionkey"])
    .join(t.customer, leftOn = ["n_nationkey"], rightOn = ["c_nationkey"])
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.supplier, leftOn = ["l_suppkey", "n_nationkey"],
          rightOn = ["s_suppkey", "s_nationkey"])
    .filter(col.r_name == var1)
    .filter(col.o_orderdate.isBetween(var2, var3, closed = Left))
    .withColumns((col.l_extendedprice * (1 - col.l_discount)).alias("revenue"))
    .groupBy(col.n_name)
    .agg(col.revenue.sum)
    .sort("revenue", descending = true)
shape: (5, 2)
n_namerevenue
strf64
"VIETNAM"1.0009e6
"CHINA"740210.757
"JAPAN"660651.2425
"INDONESIA"566379.5276
"INDIA"422874.6844

Q6

proc q6*(t: Tables): LazyFrame =
  let var1 = date(1994, 1, 1)
  let var2 = date(1995, 1, 1)
  let var3 = 0.05
  let var4 = 0.07
  let var5 = 24
  t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .filter(col.l_discount.isBetween(var3, var4))
    .filter(col.l_quantity < var5)
    .withColumns((col.l_extendedprice * col.l_discount).alias("revenue"))
    .select(col.revenue.sum)
shape: (1, 1)
revenue
f64
1.1931e6

Q7

proc q7*(t: Tables): LazyFrame =
  let var1 = "FRANCE"
  let var2 = "GERMANY"
  let var3 = date(1995, 1, 1)
  let var4 = date(1996, 12, 31)
  let nations = t.nation.filter(col.n_name.isIn([var1, var2]))
  t.customer.join(nations, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .rename({"n_name": "cust_nation"})
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(nations, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .rename({"n_name": "supp_nation"})
    .filter(
      (col.cust_nation == var1 and col.supp_nation == var2) or
      (col.cust_nation == var2 and col.supp_nation == var1))
    .filter(col.l_shipdate.isBetween(var3, var4))
    .withColumns(
      (col.l_extendedprice * (1 - col.l_discount)).alias("volume"),
      col.l_shipdate.dt.year.alias("l_year"))
    .groupBy(col.supp_nation, col.cust_nation, col.l_year)
    .agg(col.volume.sum.alias("revenue"))
    .sort(["supp_nation", "cust_nation", "l_year"])
shape: (4, 4)
supp_nationcust_nationl_yearrevenue
strstri32f64
"FRANCE""GERMANY"1995268068.5774
"FRANCE""GERMANY"1996303862.298
"GERMANY""FRANCE"1995621159.4882
"GERMANY""FRANCE"1996379095.8854

Q8

proc q8*(t: Tables): LazyFrame =
  let var1 = "BRAZIL"
  let var2 = "AMERICA"
  let var3 = "ECONOMY ANODIZED STEEL"
  let var4 = date(1995, 1, 1)
  let var5 = date(1996, 12, 31)
  let n1 = t.nation.select(col.n_nationkey, col.n_regionkey)
  let n2 = t.nation.select(col.n_nationkey, col.n_name)
  t.part.join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(t.orders, leftOn = ["l_orderkey"], rightOn = ["o_orderkey"])
    .join(t.customer, leftOn = ["o_custkey"], rightOn = ["c_custkey"])
    .join(n1, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .join(t.region, leftOn = ["n_regionkey"], rightOn = ["r_regionkey"])
    .filter(col.r_name == var2)
    .join(n2, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.o_orderdate.isBetween(var4, var5))
    .filter(col.p_type == var3)
    .select(
      col.o_orderdate.dt.year.alias("o_year"),
      (col.l_extendedprice * (1 - col.l_discount)).alias("volume"),
      col.n_name.alias("nation"))
    .withColumns(
      choose(if col.nation == var1: col.volume else: 0).alias("_tmp"))
    .groupBy(col.o_year)
    .agg((col("_tmp").sum / col.volume.sum).round(2).alias("mkt_share"))
    .sort("o_year")
shape: (2, 2)
o_yearmkt_share
i32f64
19950.0
19960.0

Q9

proc q9*(t: Tables): LazyFrame =
  t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.lineitem, leftOn = ["p_partkey", "ps_suppkey"],
          rightOn = ["l_partkey", "l_suppkey"])
    .join(t.orders, leftOn = ["l_orderkey"], rightOn = ["o_orderkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.p_name.str.contains("green"))
    .select(
      col.n_name.alias("nation"),
      col.o_orderdate.dt.year.alias("o_year"),
      (col.l_extendedprice * (1 - col.l_discount) -
        col.ps_supplycost * col.l_quantity).alias("amount"))
    .groupBy(col.nation, col.o_year)
    .agg(col.amount.sum.round(2).alias("sum_profit"))
    .sort(["nation", "o_year"], descending = [false, true])
shape: (173, 3)
nationo_yearsum_profit
stri32f64
"ALGERIA"199897864.57
"ALGERIA"1997368231.67
"ALGERIA"1996196525.8
"ALGERIA"1995341438.69
"ALGERIA"1994677444.02
………
"VIETNAM"1996439390.08
"VIETNAM"1995418626.63
"VIETNAM"1994422644.82
"VIETNAM"1993309063.4
"VIETNAM"1992716126.54

Q10

proc q10*(t: Tables): LazyFrame =
  let var1 = date(1993, 10, 1)
  let var2 = date(1994, 1, 1)
  t.customer.join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.nation, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.o_orderdate.isBetween(var1, var2, closed = Left))
    .filter(col.l_returnflag == "R")
    .groupBy(col.c_custkey, col.c_name, col.c_acctbal, col.c_phone,
             col.n_name, col.c_address, col.c_comment)
    .agg((col.l_extendedprice * (1 - col.l_discount)).sum.round(2).alias("revenue"))
    .select(col.c_custkey, col.c_name, col.revenue, col.c_acctbal,
            col.n_name, col.c_address, col.c_phone, col.c_comment)
    .sort("revenue", descending = true)
    .head(20)
shape: (20, 8)
c_custkeyc_namerevenuec_acctbaln_namec_addressc_phonec_comment
i64strf64f64strstrstrstr
679"Customer#000000679"378211.331394.44"IRAN""IJf1FlZL9I9m,rvofcoKy5pRUOjUQV""20-146-696-9508""ely pending frays boost carefu…
1201"Customer#000001201"374331.535165.39"IRAN""LfCSVKWozyWOGDW02g9UX,XgH5YU2o…"20-825-400-1187""lyly pending packages. special…
422"Customer#000000422"366451.01-272.14"INDONESIA""AyNzZBvmIDo42JtjP9xzaK3pnvkh Q…"19-299-247-2444""eposits; furiously ironic pack…
334"Customer#000000334"360370.76-405.91"EGYPT""OPN1N7t4aQ23TnCpc""14-947-291-5002""fully busily special ideas. ca…
805"Customer#000000805"359448.9511.69"IRAN""wCKx5zcHvwpSffyc9qfi9dvqcm9LT,…"20-732-989-5653""busy sentiments. pending packa…
……………………
211"Customer#000000211"287905.644198.72"JORDAN""URhlVPzz4FqXem""23-965-335-9471""furiously regular foxes boost …
197"Customer#000000197"283190.489860.22"ARGENTINA""UeVqssepNuXmtZ38D""11-107-312-6585""ickly final accounts cajole. f…
1030"Customer#000001030"282557.366359.27"INDIA""Xpt1BiB5h9o""18-759-877-1870""ding to the slyly unusual acco…
1049"Customer#000001049"281134.118747.99"INDONESIA""bZ1OcFhHaIZ5gMiH""19-499-258-2851""uriously according to the furi…
1094"Customer#000001094"274877.442544.49"BRAZIL""OFz0eedTmPmXk2 3XM9v9Mcp13NVC0…"12-234-721-9871""tes serve blithely quickly pen…

Q11

proc q11*(t: Tables, scaleFactor: float): LazyFrame =
  let var1 = "GERMANY"
  let var2 = 0.0001 / scaleFactor
  let q1 = t.partsupp.join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.n_name == var1)
  let q2 = q1.select(
    (col.ps_supplycost * col.ps_availqty).sum.round(2).alias("tmp") * var2)
  q1.groupBy(col.ps_partkey)
    .agg((col.ps_supplycost * col.ps_availqty).sum.round(2).alias("value"))
    .join(q2, on = newSeq[string](), how = Cross)
    .filter(col.value > col.tmp)
    .select(col.ps_partkey, col.value)
    .sort("value", descending = true)
shape: (1, 2)
ps_partkeyvalue
i64f64
13761.3271e7

Q12

proc q12*(t: Tables): LazyFrame =
  let var1 = "MAIL"
  let var2 = "SHIP"
  let var3 = date(1994, 1, 1)
  let var4 = date(1995, 1, 1)
  t.orders.join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .filter(col.l_shipmode.isIn([var1, var2]))
    .filter(col.l_commitdate < col.l_receiptdate)
    .filter(col.l_shipdate < col.l_commitdate)
    .filter(col.l_receiptdate.isBetween(var3, var4, closed = Left))
    .withColumns(col.o_orderpriority.isIn(["1-URGENT", "2-HIGH"]).alias("line_count"))
    .groupBy(col.l_shipmode)
    .agg(
      col.line_count.sum.alias("high_line_count"),
      (not col.line_count).sum.alias("low_line_count"))
    .sort("l_shipmode")
shape: (2, 3)
l_shipmodehigh_line_countlow_line_count
stru32u32
"MAIL"6486
"SHIP"6196

Q13

proc q13*(t: Tables): LazyFrame =
  let var1 = "special"
  let var2 = "requests"
  let orders = t.orders.filter(not col.o_comment.str.contains(var1 & ".*" & var2))
  t.customer.join(orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"], how = Left)
    .groupBy(col.c_custkey)
    .agg(col.o_orderkey.count.alias("c_count"))
    .groupBy(col.c_count)
    .agg(col.c_count.len.alias("len"))
    .select(col.c_count, col.len.alias("custdist"))
    .sort(["custdist", "c_count"], descending = [true, true])
shape: (33, 2)
c_countcustdist
u32u32
0500
1168
1064
1262
962
……
302
32
311
21
11

Q14

proc q14*(t: Tables): LazyFrame =
  let var1 = date(1995, 9, 1)
  let var2 = date(1995, 10, 1)
  t.lineitem.join(t.part, leftOn = ["l_partkey"], rightOn = ["p_partkey"])
    .filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .select(
      (100.00 *
        choose(if col.p_type.str.startsWith("PROMO"):
                 col.l_extendedprice * (1 - col.l_discount)
               else: 0).sum /
        (col.l_extendedprice * (1 - col.l_discount)).sum)
      .round(2)
      .alias("promo_revenue"))
shape: (1, 1)
promo_revenue
f64
15.49

Q15

proc q15*(t: Tables): LazyFrame =
  let var1 = date(1996, 1, 1)
  let var2 = date(1996, 4, 1)
  let revenue = t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.l_suppkey)
    .agg((col.l_extendedprice * (1 - col.l_discount)).sum.alias("total_revenue"))
    .select(col.l_suppkey.alias("supplier_no"), col.total_revenue)
  t.supplier.join(revenue, leftOn = ["s_suppkey"], rightOn = ["supplier_no"])
    .filter(col.total_revenue == col.total_revenue.max)
    .withColumns(col.total_revenue.round(2))
    .select(col.s_suppkey, col.s_name, col.s_address, col.s_phone,
            col.total_revenue)
    .sort("s_suppkey")
shape: (1, 5)
s_suppkeys_names_addresss_phonetotal_revenue
i64strstrstrf64
21"Supplier#000000021""81CavellcrJ0PQ3CPBID0Z0JwyJm0k…"12-253-590-5816"1.1611e6

Q16

proc q16*(t: Tables): LazyFrame =
  let var1 = "Brand#45"
  let supplier = t.supplier
    .filter(col.s_comment.str.contains(".*Customer.*Complaints.*"))
    .select(col.s_suppkey, col.s_suppkey.alias("ps_suppkey"))
  t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .filter(col.p_brand != var1)
    .filter(not col.p_type.str.contains("MEDIUM POLISHED*"))
    .filter(col.p_size.isIn([49, 14, 23, 45, 19, 3, 36, 9]))
    .join(supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"], how = Anti)
    .groupBy(col.p_brand, col.p_type, col.p_size)
    .agg(col.ps_suppkey.nUnique.alias("supplier_cnt"))
    .sort(["supplier_cnt", "p_brand", "p_type", "p_size"],
          descending = [true, false, false, false])
shape: (296, 4)
p_brandp_typep_sizesupplier_cnt
strstri64u32
"Brand#14""PROMO BRUSHED STEEL"98
"Brand#35""SMALL POLISHED COPPER"148
"Brand#22""LARGE BURNISHED TIN"366
"Brand#11""ECONOMY BURNISHED NICKEL"494
"Brand#11""LARGE PLATED TIN"234
…………
"Brand#55""PROMO BURNISHED STEEL"144
"Brand#55""SMALL PLATED COPPER"454
"Brand#55""STANDARD ANODIZED BRASS"364
"Brand#55""STANDARD BRUSHED COPPER"34
"Brand#55""STANDARD BRUSHED STEEL"194

Q17

proc q17*(t: Tables): LazyFrame =
  let var1 = "Brand#23"
  let var2 = "MED BOX"
  let q1 = t.part.filter(col.p_brand == var1)
    .filter(col.p_container == var2)
    .join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
  q1.groupBy(col.p_partkey)
    .agg((0.2 * col.l_quantity.mean).alias("avg_quantity"))
    .select(col.p_partkey.alias("key"), col.avg_quantity)
    .join(q1, leftOn = ["key"], rightOn = ["p_partkey"])
    .filter(col.l_quantity < col.avg_quantity)
    .select((col.l_extendedprice.sum / 7.0).round(2).alias("avg_yearly"))
shape: (1, 1)
avg_yearly
f64
0.0

Q18

proc q18*(t: Tables): LazyFrame =
  let var1 = 300
  let q1 = t.lineitem.groupBy(col.l_orderkey)
    .agg(col.l_quantity.sum.alias("sum_quantity"))
    .filter(col.sum_quantity > var1)
  t.orders.join(q1, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"], how = Semi)
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.customer, leftOn = ["o_custkey"], rightOn = ["c_custkey"])
    .groupBy(col.c_name, col.o_custkey, col.o_orderkey, col.o_orderdate,
             col.o_totalprice)
    .agg(col.l_quantity.sum.alias("col6"))
    .select(col.c_name, col.o_custkey.alias("c_custkey"), col.o_orderkey,
            col.o_orderdate.alias("o_orderdat"), col.o_totalprice, col.col6)
    .sort(["o_totalprice", "o_orderdat"], descending = [true, false])
    .head(100)
shape: (2, 6)
c_namec_custkeyo_orderkeyo_orderdato_totalpricecol6
stri64i64datef64i64
"Customer#000000667"667291581995-10-21439687.23305
"Customer#000000178"17868821997-04-09422359.65303

Q19

proc q19*(t: Tables): LazyFrame =
  t.part.join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
    .filter(col.l_shipmode.isIn(["AIR", "AIR REG"]))
    .filter(col.l_shipinstruct == "DELIVER IN PERSON")
    .filter(
      (
        (col.p_brand == "Brand#12") and
        col.p_container.isIn(["SM CASE", "SM BOX", "SM PACK", "SM PKG"]) and
        col.l_quantity.isBetween(1, 11) and
        col.p_size.isBetween(1, 5)
      ) or (
        (col.p_brand == "Brand#23") and
        col.p_container.isIn(["MED BAG", "MED BOX", "MED PKG", "MED PACK"]) and
        col.l_quantity.isBetween(10, 20) and
        col.p_size.isBetween(1, 10)
      ) or (
        (col.p_brand == "Brand#34") and
        col.p_container.isIn(["LG CASE", "LG BOX", "LG PACK", "LG PKG"]) and
        col.l_quantity.isBetween(20, 30) and
        col.p_size.isBetween(1, 15)
      ))
    .select((col.l_extendedprice * (1 - col.l_discount)).sum.round(2).alias("revenue"))
shape: (1, 1)
revenue
f64
22923.03

Q20

proc q20*(t: Tables): LazyFrame =
  let var1 = date(1994, 1, 1)
  let var2 = date(1995, 1, 1)
  let var3 = "CANADA"
  let var4 = "forest"
  let q1 = t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.l_partkey, col.l_suppkey)
    .agg((col.l_quantity.sum * 0.5).alias("sum_quantity"))
  let q2 = t.nation.filter(col.n_name == var3)
  let q3 = t.supplier.join(q2, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
  # Nanuq has no Expr.unique yet: the frame's unique does the same here
  t.part.filter(col.p_name.str.startsWith(var4))
    .select(col.p_partkey).unique()
    .join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(q1, leftOn = ["ps_suppkey", "p_partkey"], rightOn = ["l_suppkey", "l_partkey"])
    .filter(col.ps_availqty > col.sum_quantity)
    .select(col.ps_suppkey).unique()
    .join(q3, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .select(col.s_name, col.s_address)
    .sort("s_name")
shape: (1, 2)
s_names_address
strstr
"Supplier#000000013""HK71HQyWoqRWOX8GI FpgAifW,2PoH"

Q21

proc q21*(t: Tables): LazyFrame =
  let var1 = "SAUDI ARABIA"
  let isLate = col.l_receiptdate > col.l_commitdate
  let l1 = t.lineitem.filter(isLate)
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation.filter(col.n_name == var1),
          leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .join(t.orders.filter(col.o_orderstatus == "F"),
          leftOn = ["l_orderkey"], rightOn = ["o_orderkey"], how = Semi)
  let perOrder = t.lineitem.join(l1, on = ["l_orderkey"], how = Semi)
    .groupBy(col.l_orderkey)
    .agg(
      col.l_suppkey.nUnique.alias("n_supp"),
      col.l_suppkey.filter(isLate).nUnique.alias("n_late_supp"))
  l1.join(perOrder, on = ["l_orderkey"])
    .filter(col.n_supp > 1 and col.n_late_supp == 1)
    .groupBy(col.s_name)
    .agg(col.s_name.len.alias("numwait"))
    .sort(["numwait", "s_name"], descending = [true, false])
    .head(100)
shape: (1, 2)
s_namenumwait
stru32
"Supplier#000000074"9

Q22

proc q22*(t: Tables): LazyFrame =
  let q1 = t.customer.withColumns(col.c_phone.str.slice(0, 2).alias("cntrycode"))
    .filter(col.cntrycode.str.contains("13|31|23|29|30|18|17"))
    .select(col.c_acctbal, col.c_custkey, col.cntrycode)
  let q2 = q1.filter(col.c_acctbal > 0.0)
    .select(col.c_acctbal.mean.alias("avg_acctbal"))
  q1.join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"], how = Anti)
    .join(q2, how = Cross)
    .filter(col.c_acctbal > col.avg_acctbal)
    .groupBy(col.cntrycode)
    .agg(
      col.c_acctbal.count.alias("numcust"),
      col.c_acctbal.sum.round(2).alias("totacctbal"))
    .sort("cntrycode")
shape: (7, 3)
cntrycodenumcusttotacctbal
stru32f64
"13"1075359.29
"17"862288.98
"18"14111072.45
"23"540458.86
"29"1188722.85
"30"17122189.33
"31"866313.16

Running it on your machine

From the root of a clone of the book, with Nim, nimble, uv and git (the script installs the book's dependencies first; the data goes to bench-data/, which git ignores; scale factor 1 is about 1 GB of CSV):

scripts/bench pdsh                          # scale factor 1, 3 timed runs per query
scripts/bench pdsh -d:benchScale=10         # scale factor 10
scripts/bench pdsh -d:benchLabel=my-laptop  # a name for your machine

It writes the timings and the machine's specs to a timestamped file in results/pdsh/ and commits it; a pull request with that file adds a run to the tables at the top.

Source files

Every source file this page mentions, folded: tap one to read it. A file's name in the text leads here.

bench/pdsh.nim 388 lines
## PDS-H (derived from TPC-H) queries in Nanuq: all 22.
##
## Ported from the Polars queries of polars-benchmark (Apache-2.0).
import std/os
import nanuq

type Tables* = object
  customer*, lineitem*, nation*, orders*, part*, partsupp*, region*, supplier*: LazyFrame

proc scanTables*(dir: string): Tables =
  ## The eight tables, as CSV files with a header (`tpchgen-cli csv`), dates parsed.
  template scan(name: string): LazyFrame = scanCsv(dir / name & ".csv", tryParseDates = true)
  Tables(customer: scan("customer"), lineitem: scan("lineitem"), nation: scan("nation"),
         orders: scan("orders"), part: scan("part"), partsupp: scan("partsupp"),
         region: scan("region"), supplier: scan("supplier"))

proc q1*(t: Tables): LazyFrame =
  let var1 = date(1998, 9, 2)
  t.lineitem.filter(col.l_shipdate <= var1)
    .groupBy(col.l_returnflag, col.l_linestatus)
    .agg(
      col.l_quantity.sum.alias("sum_qty"),
      col.l_extendedprice.sum.alias("sum_base_price"),
      (col.l_extendedprice * (1.0 - col.l_discount)).sum.alias("sum_disc_price"),
      (col.l_extendedprice * (1.0 - col.l_discount) * (1.0 + col.l_tax))
        .sum.alias("sum_charge"),
      col.l_quantity.mean.alias("avg_qty"),
      col.l_extendedprice.mean.alias("avg_price"),
      col.l_discount.mean.alias("avg_disc"),
      col.l_orderkey.len.alias("count_order"))
    .sort(["l_returnflag", "l_linestatus"])

proc q2*(t: Tables): LazyFrame =
  let var1 = 15
  let var2 = "BRASS"
  let var3 = "EUROPE"
  let q1 = t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .join(t.region, leftOn = ["n_regionkey"], rightOn = ["r_regionkey"])
    .filter(col.p_size == var1)
    .filter(col.p_type.str.endsWith(var2))
    .filter(col.r_name == var3)
  q1.groupBy(col.p_partkey)
    .agg(col.ps_supplycost.min)
    .join(q1, on = ["p_partkey", "ps_supplycost"])
    .select(col.s_acctbal, col.s_name, col.n_name, col.p_partkey, col.p_mfgr,
            col.s_address, col.s_phone, col.s_comment)
    .sort(["s_acctbal", "n_name", "s_name", "p_partkey"],
          descending = [true, false, false, false])
    .head(100)

proc q3*(t: Tables): LazyFrame =
  let var1 = "BUILDING"
  let var2 = date(1995, 3, 15)
  t.customer.filter(col.c_mktsegment == var1)
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .filter(col.o_orderdate < var2)
    .filter(col.l_shipdate > var2)
    .withColumns((col.l_extendedprice * (1 - col.l_discount)).alias("revenue"))
    .groupBy(col.o_orderkey, col.o_orderdate, col.o_shippriority)
    .agg(col.revenue.sum)
    .select(col.o_orderkey.alias("l_orderkey"), col.revenue, col.o_orderdate,
            col.o_shippriority)
    .sort(["revenue", "o_orderdate"], descending = [true, false])
    .head(10)

proc q4*(t: Tables): LazyFrame =
  let var1 = date(1993, 7, 1)
  let var2 = date(1993, 10, 1)
  # SQL exists translates to semi join in Polars API
  t.orders.join(t.lineitem.filter(col.l_commitdate < col.l_receiptdate),
                leftOn = ["o_orderkey"], rightOn = ["l_orderkey"], how = Semi)
    .filter(col.o_orderdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.o_orderpriority)
    .agg(col.o_orderkey.len.alias("order_count"))
    .sort("o_orderpriority")

proc q5*(t: Tables): LazyFrame =
  let var1 = "ASIA"
  let var2 = date(1994, 1, 1)
  let var3 = date(1995, 1, 1)
  t.region.join(t.nation, leftOn = ["r_regionkey"], rightOn = ["n_regionkey"])
    .join(t.customer, leftOn = ["n_nationkey"], rightOn = ["c_nationkey"])
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.supplier, leftOn = ["l_suppkey", "n_nationkey"],
          rightOn = ["s_suppkey", "s_nationkey"])
    .filter(col.r_name == var1)
    .filter(col.o_orderdate.isBetween(var2, var3, closed = Left))
    .withColumns((col.l_extendedprice * (1 - col.l_discount)).alias("revenue"))
    .groupBy(col.n_name)
    .agg(col.revenue.sum)
    .sort("revenue", descending = true)

proc q6*(t: Tables): LazyFrame =
  let var1 = date(1994, 1, 1)
  let var2 = date(1995, 1, 1)
  let var3 = 0.05
  let var4 = 0.07
  let var5 = 24
  t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .filter(col.l_discount.isBetween(var3, var4))
    .filter(col.l_quantity < var5)
    .withColumns((col.l_extendedprice * col.l_discount).alias("revenue"))
    .select(col.revenue.sum)

proc q7*(t: Tables): LazyFrame =
  let var1 = "FRANCE"
  let var2 = "GERMANY"
  let var3 = date(1995, 1, 1)
  let var4 = date(1996, 12, 31)
  let nations = t.nation.filter(col.n_name.isIn([var1, var2]))
  t.customer.join(nations, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .rename({"n_name": "cust_nation"})
    .join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(nations, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .rename({"n_name": "supp_nation"})
    .filter(
      (col.cust_nation == var1 and col.supp_nation == var2) or
      (col.cust_nation == var2 and col.supp_nation == var1))
    .filter(col.l_shipdate.isBetween(var3, var4))
    .withColumns(
      (col.l_extendedprice * (1 - col.l_discount)).alias("volume"),
      col.l_shipdate.dt.year.alias("l_year"))
    .groupBy(col.supp_nation, col.cust_nation, col.l_year)
    .agg(col.volume.sum.alias("revenue"))
    .sort(["supp_nation", "cust_nation", "l_year"])

proc q8*(t: Tables): LazyFrame =
  let var1 = "BRAZIL"
  let var2 = "AMERICA"
  let var3 = "ECONOMY ANODIZED STEEL"
  let var4 = date(1995, 1, 1)
  let var5 = date(1996, 12, 31)
  let n1 = t.nation.select(col.n_nationkey, col.n_regionkey)
  let n2 = t.nation.select(col.n_nationkey, col.n_name)
  t.part.join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(t.orders, leftOn = ["l_orderkey"], rightOn = ["o_orderkey"])
    .join(t.customer, leftOn = ["o_custkey"], rightOn = ["c_custkey"])
    .join(n1, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .join(t.region, leftOn = ["n_regionkey"], rightOn = ["r_regionkey"])
    .filter(col.r_name == var2)
    .join(n2, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.o_orderdate.isBetween(var4, var5))
    .filter(col.p_type == var3)
    .select(
      col.o_orderdate.dt.year.alias("o_year"),
      (col.l_extendedprice * (1 - col.l_discount)).alias("volume"),
      col.n_name.alias("nation"))
    .withColumns(
      choose(if col.nation == var1: col.volume else: 0).alias("_tmp"))
    .groupBy(col.o_year)
    .agg((col("_tmp").sum / col.volume.sum).round(2).alias("mkt_share"))
    .sort("o_year")

proc q9*(t: Tables): LazyFrame =
  t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.lineitem, leftOn = ["p_partkey", "ps_suppkey"],
          rightOn = ["l_partkey", "l_suppkey"])
    .join(t.orders, leftOn = ["l_orderkey"], rightOn = ["o_orderkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.p_name.str.contains("green"))
    .select(
      col.n_name.alias("nation"),
      col.o_orderdate.dt.year.alias("o_year"),
      (col.l_extendedprice * (1 - col.l_discount) -
        col.ps_supplycost * col.l_quantity).alias("amount"))
    .groupBy(col.nation, col.o_year)
    .agg(col.amount.sum.round(2).alias("sum_profit"))
    .sort(["nation", "o_year"], descending = [false, true])

proc q10*(t: Tables): LazyFrame =
  let var1 = date(1993, 10, 1)
  let var2 = date(1994, 1, 1)
  t.customer.join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"])
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.nation, leftOn = ["c_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.o_orderdate.isBetween(var1, var2, closed = Left))
    .filter(col.l_returnflag == "R")
    .groupBy(col.c_custkey, col.c_name, col.c_acctbal, col.c_phone,
             col.n_name, col.c_address, col.c_comment)
    .agg((col.l_extendedprice * (1 - col.l_discount)).sum.round(2).alias("revenue"))
    .select(col.c_custkey, col.c_name, col.revenue, col.c_acctbal,
            col.n_name, col.c_address, col.c_phone, col.c_comment)
    .sort("revenue", descending = true)
    .head(20)

proc q11*(t: Tables, scaleFactor: float): LazyFrame =
  let var1 = "GERMANY"
  let var2 = 0.0001 / scaleFactor
  let q1 = t.partsupp.join(t.supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .filter(col.n_name == var1)
  let q2 = q1.select(
    (col.ps_supplycost * col.ps_availqty).sum.round(2).alias("tmp") * var2)
  q1.groupBy(col.ps_partkey)
    .agg((col.ps_supplycost * col.ps_availqty).sum.round(2).alias("value"))
    .join(q2, on = newSeq[string](), how = Cross)
    .filter(col.value > col.tmp)
    .select(col.ps_partkey, col.value)
    .sort("value", descending = true)

proc q12*(t: Tables): LazyFrame =
  let var1 = "MAIL"
  let var2 = "SHIP"
  let var3 = date(1994, 1, 1)
  let var4 = date(1995, 1, 1)
  t.orders.join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .filter(col.l_shipmode.isIn([var1, var2]))
    .filter(col.l_commitdate < col.l_receiptdate)
    .filter(col.l_shipdate < col.l_commitdate)
    .filter(col.l_receiptdate.isBetween(var3, var4, closed = Left))
    .withColumns(col.o_orderpriority.isIn(["1-URGENT", "2-HIGH"]).alias("line_count"))
    .groupBy(col.l_shipmode)
    .agg(
      col.line_count.sum.alias("high_line_count"),
      (not col.line_count).sum.alias("low_line_count"))
    .sort("l_shipmode")

proc q13*(t: Tables): LazyFrame =
  let var1 = "special"
  let var2 = "requests"
  let orders = t.orders.filter(not col.o_comment.str.contains(var1 & ".*" & var2))
  t.customer.join(orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"], how = Left)
    .groupBy(col.c_custkey)
    .agg(col.o_orderkey.count.alias("c_count"))
    .groupBy(col.c_count)
    .agg(col.c_count.len.alias("len"))
    .select(col.c_count, col.len.alias("custdist"))
    .sort(["custdist", "c_count"], descending = [true, true])

proc q14*(t: Tables): LazyFrame =
  let var1 = date(1995, 9, 1)
  let var2 = date(1995, 10, 1)
  t.lineitem.join(t.part, leftOn = ["l_partkey"], rightOn = ["p_partkey"])
    .filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .select(
      (100.00 *
        choose(if col.p_type.str.startsWith("PROMO"):
                 col.l_extendedprice * (1 - col.l_discount)
               else: 0).sum /
        (col.l_extendedprice * (1 - col.l_discount)).sum)
      .round(2)
      .alias("promo_revenue"))

proc q15*(t: Tables): LazyFrame =
  let var1 = date(1996, 1, 1)
  let var2 = date(1996, 4, 1)
  let revenue = t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.l_suppkey)
    .agg((col.l_extendedprice * (1 - col.l_discount)).sum.alias("total_revenue"))
    .select(col.l_suppkey.alias("supplier_no"), col.total_revenue)
  t.supplier.join(revenue, leftOn = ["s_suppkey"], rightOn = ["supplier_no"])
    .filter(col.total_revenue == col.total_revenue.max)
    .withColumns(col.total_revenue.round(2))
    .select(col.s_suppkey, col.s_name, col.s_address, col.s_phone,
            col.total_revenue)
    .sort("s_suppkey")

proc q16*(t: Tables): LazyFrame =
  let var1 = "Brand#45"
  let supplier = t.supplier
    .filter(col.s_comment.str.contains(".*Customer.*Complaints.*"))
    .select(col.s_suppkey, col.s_suppkey.alias("ps_suppkey"))
  t.part.join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .filter(col.p_brand != var1)
    .filter(not col.p_type.str.contains("MEDIUM POLISHED*"))
    .filter(col.p_size.isIn([49, 14, 23, 45, 19, 3, 36, 9]))
    .join(supplier, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"], how = Anti)
    .groupBy(col.p_brand, col.p_type, col.p_size)
    .agg(col.ps_suppkey.nUnique.alias("supplier_cnt"))
    .sort(["supplier_cnt", "p_brand", "p_type", "p_size"],
          descending = [true, false, false, false])

proc q17*(t: Tables): LazyFrame =
  let var1 = "Brand#23"
  let var2 = "MED BOX"
  let q1 = t.part.filter(col.p_brand == var1)
    .filter(col.p_container == var2)
    .join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
  q1.groupBy(col.p_partkey)
    .agg((0.2 * col.l_quantity.mean).alias("avg_quantity"))
    .select(col.p_partkey.alias("key"), col.avg_quantity)
    .join(q1, leftOn = ["key"], rightOn = ["p_partkey"])
    .filter(col.l_quantity < col.avg_quantity)
    .select((col.l_extendedprice.sum / 7.0).round(2).alias("avg_yearly"))

proc q18*(t: Tables): LazyFrame =
  let var1 = 300
  let q1 = t.lineitem.groupBy(col.l_orderkey)
    .agg(col.l_quantity.sum.alias("sum_quantity"))
    .filter(col.sum_quantity > var1)
  t.orders.join(q1, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"], how = Semi)
    .join(t.lineitem, leftOn = ["o_orderkey"], rightOn = ["l_orderkey"])
    .join(t.customer, leftOn = ["o_custkey"], rightOn = ["c_custkey"])
    .groupBy(col.c_name, col.o_custkey, col.o_orderkey, col.o_orderdate,
             col.o_totalprice)
    .agg(col.l_quantity.sum.alias("col6"))
    .select(col.c_name, col.o_custkey.alias("c_custkey"), col.o_orderkey,
            col.o_orderdate.alias("o_orderdat"), col.o_totalprice, col.col6)
    .sort(["o_totalprice", "o_orderdat"], descending = [true, false])
    .head(100)

proc q19*(t: Tables): LazyFrame =
  t.part.join(t.lineitem, leftOn = ["p_partkey"], rightOn = ["l_partkey"])
    .filter(col.l_shipmode.isIn(["AIR", "AIR REG"]))
    .filter(col.l_shipinstruct == "DELIVER IN PERSON")
    .filter(
      (
        (col.p_brand == "Brand#12") and
        col.p_container.isIn(["SM CASE", "SM BOX", "SM PACK", "SM PKG"]) and
        col.l_quantity.isBetween(1, 11) and
        col.p_size.isBetween(1, 5)
      ) or (
        (col.p_brand == "Brand#23") and
        col.p_container.isIn(["MED BAG", "MED BOX", "MED PKG", "MED PACK"]) and
        col.l_quantity.isBetween(10, 20) and
        col.p_size.isBetween(1, 10)
      ) or (
        (col.p_brand == "Brand#34") and
        col.p_container.isIn(["LG CASE", "LG BOX", "LG PACK", "LG PKG"]) and
        col.l_quantity.isBetween(20, 30) and
        col.p_size.isBetween(1, 15)
      ))
    .select((col.l_extendedprice * (1 - col.l_discount)).sum.round(2).alias("revenue"))

proc q20*(t: Tables): LazyFrame =
  let var1 = date(1994, 1, 1)
  let var2 = date(1995, 1, 1)
  let var3 = "CANADA"
  let var4 = "forest"
  let q1 = t.lineitem.filter(col.l_shipdate.isBetween(var1, var2, closed = Left))
    .groupBy(col.l_partkey, col.l_suppkey)
    .agg((col.l_quantity.sum * 0.5).alias("sum_quantity"))
  let q2 = t.nation.filter(col.n_name == var3)
  let q3 = t.supplier.join(q2, leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
  # Nanuq has no Expr.unique yet: the frame's unique does the same here
  t.part.filter(col.p_name.str.startsWith(var4))
    .select(col.p_partkey).unique()
    .join(t.partsupp, leftOn = ["p_partkey"], rightOn = ["ps_partkey"])
    .join(q1, leftOn = ["ps_suppkey", "p_partkey"], rightOn = ["l_suppkey", "l_partkey"])
    .filter(col.ps_availqty > col.sum_quantity)
    .select(col.ps_suppkey).unique()
    .join(q3, leftOn = ["ps_suppkey"], rightOn = ["s_suppkey"])
    .select(col.s_name, col.s_address)
    .sort("s_name")

proc q21*(t: Tables): LazyFrame =
  let var1 = "SAUDI ARABIA"
  let isLate = col.l_receiptdate > col.l_commitdate
  let l1 = t.lineitem.filter(isLate)
    .join(t.supplier, leftOn = ["l_suppkey"], rightOn = ["s_suppkey"])
    .join(t.nation.filter(col.n_name == var1),
          leftOn = ["s_nationkey"], rightOn = ["n_nationkey"])
    .join(t.orders.filter(col.o_orderstatus == "F"),
          leftOn = ["l_orderkey"], rightOn = ["o_orderkey"], how = Semi)
  let perOrder = t.lineitem.join(l1, on = ["l_orderkey"], how = Semi)
    .groupBy(col.l_orderkey)
    .agg(
      col.l_suppkey.nUnique.alias("n_supp"),
      col.l_suppkey.filter(isLate).nUnique.alias("n_late_supp"))
  l1.join(perOrder, on = ["l_orderkey"])
    .filter(col.n_supp > 1 and col.n_late_supp == 1)
    .groupBy(col.s_name)
    .agg(col.s_name.len.alias("numwait"))
    .sort(["numwait", "s_name"], descending = [true, false])
    .head(100)

proc q22*(t: Tables): LazyFrame =
  let q1 = t.customer.withColumns(col.c_phone.str.slice(0, 2).alias("cntrycode"))
    .filter(col.cntrycode.str.contains("13|31|23|29|30|18|17"))
    .select(col.c_acctbal, col.c_custkey, col.cntrycode)
  let q2 = q1.filter(col.c_acctbal > 0.0)
    .select(col.c_acctbal.mean.alias("avg_acctbal"))
  q1.join(t.orders, leftOn = ["c_custkey"], rightOn = ["o_custkey"], how = Anti)
    .join(q2, how = Cross)
    .filter(col.c_acctbal > col.avg_acctbal)
    .groupBy(col.cntrycode)
    .agg(
      col.c_acctbal.count.alias("numcust"),
      col.c_acctbal.sum.round(2).alias("totacctbal"))
    .sort("cntrycode")

bench/pdsh.nim

bench/pdsh.py 629 lines
"""PDS-H (derived from TPC-H) queries in Python Polars.

The Polars queries of polars-benchmark (Apache-2.0), as they are there: only the
dataset loading is left out (the tables are passed in) and q11 takes the scale factor
as an argument.
"""
from datetime import date
from pathlib import Path

import polars as pl

TABLES = ["customer", "lineitem", "nation", "orders", "part", "partsupp", "region", "supplier"]


def scan_tables(folder):
    # The eight tables, as CSV files with a header (`tpchgen-cli csv`), dates parsed.
    return {
        name: pl.scan_csv(Path(folder) / f"{name}.csv", try_parse_dates=True)
        for name in TABLES
    }


def q1(lineitem, **kwargs):
    var1 = date(1998, 9, 2)

    return (
        lineitem.filter(pl.col("l_shipdate") <= var1)
        .group_by("l_returnflag", "l_linestatus")
        .agg(
            pl.sum("l_quantity").alias("sum_qty"),
            pl.sum("l_extendedprice").alias("sum_base_price"),
            (pl.col("l_extendedprice") * (1.0 - pl.col("l_discount")))
            .sum()
            .alias("sum_disc_price"),
            (
                pl.col("l_extendedprice")
                * (1.0 - pl.col("l_discount"))
                * (1.0 + pl.col("l_tax"))
            )
            .sum()
            .alias("sum_charge"),
            pl.mean("l_quantity").alias("avg_qty"),
            pl.mean("l_extendedprice").alias("avg_price"),
            pl.mean("l_discount").alias("avg_disc"),
            pl.len().alias("count_order"),
        )
        .sort("l_returnflag", "l_linestatus")
    )


def q2(nation, partsupp, supplier, region, part, **kwargs):
    var1 = 15
    var2 = "BRASS"
    var3 = "EUROPE"

    q1 = (
        part.join(partsupp, left_on="p_partkey", right_on="ps_partkey")
        .join(supplier, left_on="ps_suppkey", right_on="s_suppkey")
        .join(nation, left_on="s_nationkey", right_on="n_nationkey")
        .join(region, left_on="n_regionkey", right_on="r_regionkey")
        .filter(pl.col("p_size") == var1)
        .filter(pl.col("p_type").str.ends_with(var2))
        .filter(pl.col("r_name") == var3)
    )

    return (
        q1.group_by("p_partkey")
        .agg(pl.min("ps_supplycost"))
        .join(q1, on=["p_partkey", "ps_supplycost"])
        .select(
            "s_acctbal",
            "s_name",
            "n_name",
            "p_partkey",
            "p_mfgr",
            "s_address",
            "s_phone",
            "s_comment",
        )
        .sort(
            by=["s_acctbal", "n_name", "s_name", "p_partkey"],
            descending=[True, False, False, False],
        )
        .head(100)
    )


def q3(customer, lineitem, orders, **kwargs):
    var1 = "BUILDING"
    var2 = date(1995, 3, 15)

    return (
        customer.filter(pl.col("c_mktsegment") == var1)
        .join(orders, left_on="c_custkey", right_on="o_custkey")
        .join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .filter(pl.col("o_orderdate") < var2)
        .filter(pl.col("l_shipdate") > var2)
        .with_columns(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).alias("revenue")
        )
        .group_by("o_orderkey", "o_orderdate", "o_shippriority")
        .agg(pl.sum("revenue"))
        .select(
            pl.col("o_orderkey").alias("l_orderkey"),
            "revenue",
            "o_orderdate",
            "o_shippriority",
        )
        .sort(by=["revenue", "o_orderdate"], descending=[True, False])
        .head(10)
    )


def q4(lineitem, orders, **kwargs):
    var1 = date(1993, 7, 1)
    var2 = date(1993, 10, 1)

    return (
        # SQL exists translates to semi join in Polars API
        orders.join(
            (lineitem.filter(pl.col("l_commitdate") < pl.col("l_receiptdate"))),
            left_on="o_orderkey",
            right_on="l_orderkey",
            how="semi",
        )
        .filter(pl.col("o_orderdate").is_between(var1, var2, closed="left"))
        .group_by("o_orderpriority")
        .agg(pl.len().alias("order_count"))
        .sort("o_orderpriority")
    )


def q5(customer, lineitem, nation, orders, supplier, region, **kwargs):
    var1 = "ASIA"
    var2 = date(1994, 1, 1)
    var3 = date(1995, 1, 1)

    return (
        region.join(nation, left_on="r_regionkey", right_on="n_regionkey")
        .join(customer, left_on="n_nationkey", right_on="c_nationkey")
        .join(orders, left_on="c_custkey", right_on="o_custkey")
        .join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .join(
            supplier,
            left_on=["l_suppkey", "n_nationkey"],
            right_on=["s_suppkey", "s_nationkey"],
        )
        .filter(pl.col("r_name") == var1)
        .filter(pl.col("o_orderdate").is_between(var2, var3, closed="left"))
        .with_columns(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).alias("revenue")
        )
        .group_by("n_name")
        .agg(pl.sum("revenue"))
        .sort(by="revenue", descending=True)
    )


def q6(lineitem, **kwargs):
    var1 = date(1994, 1, 1)
    var2 = date(1995, 1, 1)
    var3 = 0.05
    var4 = 0.07
    var5 = 24

    return (
        lineitem.filter(pl.col("l_shipdate").is_between(var1, var2, closed="left"))
        .filter(pl.col("l_discount").is_between(var3, var4))
        .filter(pl.col("l_quantity") < var5)
        .with_columns(
            (pl.col("l_extendedprice") * pl.col("l_discount")).alias("revenue")
        )
        .select(pl.sum("revenue"))
    )


def q7(customer, lineitem, nation, orders, supplier, **kwargs):
    var1 = "FRANCE"
    var2 = "GERMANY"
    var3 = date(1995, 1, 1)
    var4 = date(1996, 12, 31)

    nations = nation.filter(pl.col("n_name").is_in([var1, var2]))

    return (
        customer.join(nations, left_on="c_nationkey", right_on="n_nationkey")
        .rename({"n_name": "cust_nation"})
        .join(orders, left_on="c_custkey", right_on="o_custkey")
        .join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .join(supplier, left_on="l_suppkey", right_on="s_suppkey")
        .join(nations, left_on="s_nationkey", right_on="n_nationkey")
        .rename({"n_name": "supp_nation"})
        .filter(
            ((pl.col("cust_nation") == var1) & (pl.col("supp_nation") == var2))
            | ((pl.col("cust_nation") == var2) & (pl.col("supp_nation") == var1))
        )
        .filter(pl.col("l_shipdate").is_between(var3, var4))
        .with_columns(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).alias("volume"),
            pl.col("l_shipdate").dt.year().alias("l_year"),
        )
        .group_by("supp_nation", "cust_nation", "l_year")
        .agg(pl.sum("volume").alias("revenue"))
        .sort(by=["supp_nation", "cust_nation", "l_year"])
    )


def q8(customer, lineitem, nation, orders, supplier, region, part, **kwargs):
    var1 = "BRAZIL"
    var2 = "AMERICA"
    var3 = "ECONOMY ANODIZED STEEL"
    var4 = date(1995, 1, 1)
    var5 = date(1996, 12, 31)

    n1 = nation.select("n_nationkey", "n_regionkey")
    n2 = nation.select("n_nationkey", "n_name")

    return (
        part.join(lineitem, left_on="p_partkey", right_on="l_partkey")
        .join(supplier, left_on="l_suppkey", right_on="s_suppkey")
        .join(orders, left_on="l_orderkey", right_on="o_orderkey")
        .join(customer, left_on="o_custkey", right_on="c_custkey")
        .join(n1, left_on="c_nationkey", right_on="n_nationkey")
        .join(region, left_on="n_regionkey", right_on="r_regionkey")
        .filter(pl.col("r_name") == var2)
        .join(n2, left_on="s_nationkey", right_on="n_nationkey")
        .filter(pl.col("o_orderdate").is_between(var4, var5))
        .filter(pl.col("p_type") == var3)
        .select(
            pl.col("o_orderdate").dt.year().alias("o_year"),
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).alias("volume"),
            pl.col("n_name").alias("nation"),
        )
        .with_columns(
            pl.when(pl.col("nation") == var1)
            .then(pl.col("volume"))
            .otherwise(0)
            .alias("_tmp")
        )
        .group_by("o_year")
        .agg((pl.sum("_tmp") / pl.sum("volume")).round(2).alias("mkt_share"))
        .sort("o_year")
    )


def q9(lineitem, nation, orders, partsupp, supplier, part, **kwargs):
    return (
        part.join(partsupp, left_on="p_partkey", right_on="ps_partkey")
        .join(supplier, left_on="ps_suppkey", right_on="s_suppkey")
        .join(
            lineitem,
            left_on=["p_partkey", "ps_suppkey"],
            right_on=["l_partkey", "l_suppkey"],
        )
        .join(orders, left_on="l_orderkey", right_on="o_orderkey")
        .join(nation, left_on="s_nationkey", right_on="n_nationkey")
        .filter(pl.col("p_name").str.contains("green"))
        .select(
            pl.col("n_name").alias("nation"),
            pl.col("o_orderdate").dt.year().alias("o_year"),
            (
                pl.col("l_extendedprice") * (1 - pl.col("l_discount"))
                - pl.col("ps_supplycost") * pl.col("l_quantity")
            ).alias("amount"),
        )
        .group_by("nation", "o_year")
        .agg(pl.sum("amount").round(2).alias("sum_profit"))
        .sort(by=["nation", "o_year"], descending=[False, True])
    )


def q10(customer, lineitem, nation, orders, **kwargs):
    var1 = date(1993, 10, 1)
    var2 = date(1994, 1, 1)

    return (
        customer.join(orders, left_on="c_custkey", right_on="o_custkey")
        .join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .join(nation, left_on="c_nationkey", right_on="n_nationkey")
        .filter(pl.col("o_orderdate").is_between(var1, var2, closed="left"))
        .filter(pl.col("l_returnflag") == "R")
        .group_by(
            "c_custkey",
            "c_name",
            "c_acctbal",
            "c_phone",
            "n_name",
            "c_address",
            "c_comment",
        )
        .agg(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount")))
            .sum()
            .round(2)
            .alias("revenue")
        )
        .select(
            "c_custkey",
            "c_name",
            "revenue",
            "c_acctbal",
            "n_name",
            "c_address",
            "c_phone",
            "c_comment",
        )
        .sort(by="revenue", descending=True)
        .head(20)
    )


def q11(nation, partsupp, supplier, scale_factor=1.0, **kwargs):
    var1 = "GERMANY"
    var2 = 0.0001 / scale_factor

    q1 = (
        partsupp.join(supplier, left_on="ps_suppkey", right_on="s_suppkey")
        .join(nation, left_on="s_nationkey", right_on="n_nationkey")
        .filter(pl.col("n_name") == var1)
    )
    q2 = q1.select(
        (pl.col("ps_supplycost") * pl.col("ps_availqty")).sum().round(2).alias("tmp")
        * var2
    )

    return (
        q1.group_by("ps_partkey")
        .agg(
            (pl.col("ps_supplycost") * pl.col("ps_availqty"))
            .sum()
            .round(2)
            .alias("value")
        )
        .join(q2, how="cross")
        .filter(pl.col("value") > pl.col("tmp"))
        .select("ps_partkey", "value")
        .sort("value", descending=True)
    )


def q12(lineitem, orders, **kwargs):
    var1 = "MAIL"
    var2 = "SHIP"
    var3 = date(1994, 1, 1)
    var4 = date(1995, 1, 1)

    return (
        orders.join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .filter(pl.col("l_shipmode").is_in([var1, var2]))
        .filter(pl.col("l_commitdate") < pl.col("l_receiptdate"))
        .filter(pl.col("l_shipdate") < pl.col("l_commitdate"))
        .filter(pl.col("l_receiptdate").is_between(var3, var4, closed="left"))
        .with_columns(
            line_count=pl.col("o_orderpriority").is_in(["1-URGENT", "2-HIGH"])
        )
        .group_by("l_shipmode")
        .agg(
            high_line_count=pl.col.line_count.sum(),
            low_line_count=pl.col.line_count.not_().sum(),
        )
        .sort("l_shipmode")
    )


def q13(customer, orders, **kwargs):
    var1 = "special"
    var2 = "requests"

    orders = orders.filter(pl.col("o_comment").str.contains(f"{var1}.*{var2}").not_())
    return (
        customer.join(orders, left_on="c_custkey", right_on="o_custkey", how="left")
        .group_by("c_custkey")
        .agg(pl.col("o_orderkey").count().alias("c_count"))
        .group_by("c_count")
        .len()
        .select(pl.col("c_count"), pl.col("len").alias("custdist"))
        .sort(by=["custdist", "c_count"], descending=[True, True])
    )


def q14(lineitem, part, **kwargs):
    var1 = date(1995, 9, 1)
    var2 = date(1995, 10, 1)

    return (
        lineitem.join(part, left_on="l_partkey", right_on="p_partkey")
        .filter(pl.col("l_shipdate").is_between(var1, var2, closed="left"))
        .select(
            (
                100.00
                * pl.when(pl.col("p_type").str.starts_with("PROMO"))
                .then(pl.col("l_extendedprice") * (1 - pl.col("l_discount")))
                .otherwise(0)
                .sum()
                / (pl.col("l_extendedprice") * (1 - pl.col("l_discount"))).sum()
            )
            .round(2)
            .alias("promo_revenue")
        )
    )


def q15(lineitem, supplier, **kwargs):
    var1 = date(1996, 1, 1)
    var2 = date(1996, 4, 1)

    revenue = (
        lineitem.filter(pl.col("l_shipdate").is_between(var1, var2, closed="left"))
        .group_by("l_suppkey")
        .agg(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount")))
            .sum()
            .alias("total_revenue")
        )
        .select(pl.col("l_suppkey").alias("supplier_no"), pl.col("total_revenue"))
    )

    return (
        supplier.join(revenue, left_on="s_suppkey", right_on="supplier_no")
        .filter(pl.col("total_revenue") == pl.col("total_revenue").max())
        .with_columns(pl.col("total_revenue").round(2))
        .select("s_suppkey", "s_name", "s_address", "s_phone", "total_revenue")
        .sort("s_suppkey")
    )


def q16(partsupp, supplier, part, **kwargs):
    var1 = "Brand#45"

    supplier = supplier.filter(
        pl.col("s_comment").str.contains(".*Customer.*Complaints.*")
    ).select(pl.col("s_suppkey"), pl.col("s_suppkey").alias("ps_suppkey"))

    return (
        part.join(partsupp, left_on="p_partkey", right_on="ps_partkey")
        .filter(pl.col("p_brand") != var1)
        .filter(pl.col("p_type").str.contains("MEDIUM POLISHED*").not_())
        .filter(pl.col("p_size").is_in([49, 14, 23, 45, 19, 3, 36, 9]))
        .join(supplier, left_on="ps_suppkey", right_on="s_suppkey", how="anti")
        .group_by("p_brand", "p_type", "p_size")
        .agg(pl.col("ps_suppkey").n_unique().alias("supplier_cnt"))
        .sort(
            by=["supplier_cnt", "p_brand", "p_type", "p_size"],
            descending=[True, False, False, False],
        )
    )


def q17(lineitem, part, **kwargs):
    var1 = "Brand#23"
    var2 = "MED BOX"

    q1 = (
        part.filter(pl.col("p_brand") == var1)
        .filter(pl.col("p_container") == var2)
        .join(lineitem, how="inner", left_on="p_partkey", right_on="l_partkey")
    )

    return (
        q1.group_by("p_partkey")
        .agg((0.2 * pl.col("l_quantity").mean()).alias("avg_quantity"))
        .select(pl.col("p_partkey").alias("key"), pl.col("avg_quantity"))
        .join(q1, left_on="key", right_on="p_partkey")
        .filter(pl.col("l_quantity") < pl.col("avg_quantity"))
        .select((pl.col("l_extendedprice").sum() / 7.0).round(2).alias("avg_yearly"))
    )


def q18(customer, lineitem, orders, **kwargs):
    var1 = 300

    q1 = (
        lineitem.group_by("l_orderkey")
        .agg(pl.col("l_quantity").sum().alias("sum_quantity"))
        .filter(pl.col("sum_quantity") > var1)
    )

    return (
        orders.join(q1, left_on="o_orderkey", right_on="l_orderkey", how="semi")
        .join(lineitem, left_on="o_orderkey", right_on="l_orderkey")
        .join(customer, left_on="o_custkey", right_on="c_custkey")
        .group_by("c_name", "o_custkey", "o_orderkey", "o_orderdate", "o_totalprice")
        .agg(pl.col("l_quantity").sum().alias("col6"))
        .select(
            pl.col("c_name"),
            pl.col("o_custkey").alias("c_custkey"),
            pl.col("o_orderkey"),
            pl.col("o_orderdate").alias("o_orderdat"),
            pl.col("o_totalprice"),
            pl.col("col6"),
        )
        .sort(by=["o_totalprice", "o_orderdat"], descending=[True, False])
        .head(100)
    )


def q19(lineitem, part, **kwargs):
    return (
        part.join(lineitem, left_on="p_partkey", right_on="l_partkey")
        .filter(pl.col("l_shipmode").is_in(["AIR", "AIR REG"]))
        .filter(pl.col("l_shipinstruct") == "DELIVER IN PERSON")
        .filter(
            (
                (pl.col("p_brand") == "Brand#12")
                & pl.col("p_container").is_in(
                    ["SM CASE", "SM BOX", "SM PACK", "SM PKG"]
                )
                & (pl.col("l_quantity").is_between(1, 11))
                & (pl.col("p_size").is_between(1, 5))
            )
            | (
                (pl.col("p_brand") == "Brand#23")
                & pl.col("p_container").is_in(
                    ["MED BAG", "MED BOX", "MED PKG", "MED PACK"]
                )
                & (pl.col("l_quantity").is_between(10, 20))
                & (pl.col("p_size").is_between(1, 10))
            )
            | (
                (pl.col("p_brand") == "Brand#34")
                & pl.col("p_container").is_in(
                    ["LG CASE", "LG BOX", "LG PACK", "LG PKG"]
                )
                & (pl.col("l_quantity").is_between(20, 30))
                & (pl.col("p_size").is_between(1, 15))
            )
        )
        .select(
            (pl.col("l_extendedprice") * (1 - pl.col("l_discount")))
            .sum()
            .round(2)
            .alias("revenue")
        )
    )


def q20(lineitem, nation, partsupp, supplier, part, **kwargs):
    var1 = date(1994, 1, 1)
    var2 = date(1995, 1, 1)
    var3 = "CANADA"
    var4 = "forest"

    q1 = (
        lineitem.filter(pl.col("l_shipdate").is_between(var1, var2, closed="left"))
        .group_by("l_partkey", "l_suppkey")
        .agg((pl.col("l_quantity").sum() * 0.5).alias("sum_quantity"))
    )
    q2 = nation.filter(pl.col("n_name") == var3)
    q3 = supplier.join(q2, left_on="s_nationkey", right_on="n_nationkey")

    return (
        part.filter(pl.col("p_name").str.starts_with(var4))
        .select(pl.col("p_partkey").unique())
        .join(partsupp, left_on="p_partkey", right_on="ps_partkey")
        .join(
            q1,
            left_on=["ps_suppkey", "p_partkey"],
            right_on=["l_suppkey", "l_partkey"],
        )
        .filter(pl.col("ps_availqty") > pl.col("sum_quantity"))
        .select(pl.col("ps_suppkey").unique())
        .join(q3, left_on="ps_suppkey", right_on="s_suppkey")
        .select("s_name", "s_address")
        .sort("s_name")
    )


def q21(lineitem, nation, orders, supplier, **kwargs):
    var1 = "SAUDI ARABIA"

    is_late = pl.col("l_receiptdate") > pl.col("l_commitdate")

    l1 = (
        lineitem.filter(is_late)
        .join(supplier, left_on="l_suppkey", right_on="s_suppkey")
        .join(
            nation.filter(pl.col("n_name") == var1),
            left_on="s_nationkey",
            right_on="n_nationkey",
        )
        .join(
            orders.filter(pl.col("o_orderstatus") == "F"),
            left_on="l_orderkey",
            right_on="o_orderkey",
            how="semi",
        )
    )

    per_order = (
        lineitem.join(l1, on="l_orderkey", how="semi")
        .group_by("l_orderkey")
        .agg(
            n_supp=pl.col("l_suppkey").n_unique(),
            n_late_supp=pl.col("l_suppkey").filter(is_late).n_unique(),
        )
    )

    return (
        l1.join(per_order, on="l_orderkey")
        .filter(pl.col("n_supp") > 1, pl.col("n_late_supp") == 1)
        .group_by("s_name")
        .agg(pl.len().alias("numwait"))
        .sort(by=["numwait", "s_name"], descending=[True, False])
        .head(100)
    )


def q22(customer, orders, **kwargs):
    q1 = (
        customer.with_columns(pl.col("c_phone").str.slice(0, 2).alias("cntrycode"))
        .filter(pl.col("cntrycode").str.contains("13|31|23|29|30|18|17"))
        .select("c_acctbal", "c_custkey", "cntrycode")
    )

    q2 = q1.filter(pl.col("c_acctbal") > 0.0).select(
        pl.col("c_acctbal").mean().alias("avg_acctbal")
    )

    return (
        q1.join(orders, left_on="c_custkey", right_on="o_custkey", how="anti")
        .join(q2, how="cross")
        .filter(pl.col("c_acctbal") > pl.col("avg_acctbal"))
        .group_by("cntrycode")
        .agg(
            pl.col("c_acctbal").count().alias("numcust"),
            pl.col("c_acctbal").sum().round(2).alias("totacctbal"),
        )
        .sort("cntrycode")
    )

bench/pdsh.py

book/benchkit.nim: timing, results and tables of the benchmark chapters 138 lines
## Helpers for the benchmark chapters.
##
## A benchmark chapter builds in two ways:
## - normally (`nimble genbook`, CI): it runs its queries on a small sample, to check
##   that Nim and Python agree, and shows every result file in `results/<bench>/`,
##   as a Nanuq query over those files;
## - with `-d:bench` (`scripts/bench <bench>`, on your machine): it first runs the
##   benchmark at full size, times the Nim and the Python queries, writes a timestamped
##   JSON file with the timings and the machine's specs to `results/<bench>/`, and
##   commits it.
import std/[json, options, os, osproc, strutils, times, monotimes, sequtils, math, xmltree]
import nanuq
import nanuqbook

const
  benchRuns* {.intdefine.} = 3        ## timed runs of each query (the best one counts)
  benchLabel* {.strdefine.} = ""      ## a name for the machine, such as "pietro-mac"

proc resultsDir*(bench: string): string =
  ## results/<bench>, seen from the chapter's working directory (docs/).
  ".." / "results" / bench

proc cmd(c: string): string =
  try:
    let (o, code) = execCmdEx(c)
    if code == 0: o.strip else: ""
  except OSError: ""

proc systemInfo*(): JsonNode =
  ## The machine the benchmark runs on.
  var cpu, memBytes: string
  when defined(macosx):
    cpu = cmd("sysctl -n machdep.cpu.brand_string")
    memBytes = cmd("sysctl -n hw.memsize")
  else:
    for line in cmd("cat /proc/cpuinfo").splitLines:
      if line.startsWith("model name"):
        cpu = line.split(':', 1)[1].strip
        break
    for line in cmd("cat /proc/meminfo").splitLines:
      if line.startsWith("MemTotal:"):
        memBytes = $(parseInt(line.splitWhitespace[1]) * 1024)
  let memGb = if memBytes.len > 0: round(parseFloat(memBytes) / 1e9, 1) else: 0.0
  var osName = cmd("uname -sr")
  when defined(macosx):
    osName = "macOS " & cmd("sw_vers -productVersion")
  %*{"os": osName, "arch": hostCPU, "cpu": cpu, "cores": countProcessors(),
     "memoryGB": memGb}

proc timeIt*(runs: int, body: proc ()): seq[float] =
  ## Seconds taken by each of `runs` runs of `body`.
  for _ in 1 .. runs:
    let start = getMonoTime()
    body()
    result.add (getMonoTime() - start).inNanoseconds.float / 1e9

proc timePython*(runs: int, call: string): seq[float] =
  ## Seconds taken by each of `runs` runs of the Python expression `call`, in the
  ## chapter's Python session.
  let (printed, _) = runPython("""
import time as _time
_times = []
for _ in range(""" & $runs & """):
    _start = _time.perf_counter()
    """ & call & """

    _times.append(_time.perf_counter() - _start)
print(" ".join(repr(t) for t in _times))
""")
  printed.splitWhitespace.mapIt(parseFloat(it))

proc pythonVersions*(): JsonNode =
  let (printed, _) = runPython("""
import platform as _platform, polars as _pl
print(_platform.python_version(), _pl.__version__)
""")
  let v = printed.splitWhitespace
  %*{"python": v[0], "pythonPolars": v[1]}

proc saveResult*(bench: string, params, timings: JsonNode): string =
  ## Writes results/<bench>/<timestamp>[-<label>].json and commits it. Returns its path.
  let now = now().utc
  var versions = %*{"nim": NimVersion, "nanuqWrapper": polarsWrapperVersion()}
  for k, v in pythonVersions(): versions[k] = v
  let data = %*{"benchmark": bench, "timestamp": now.format("yyyy-MM-dd'T'HH:mm:ss'Z'"),
                "label": benchLabel, "params": params, "system": systemInfo(),
                "versions": versions, "timings": timings}
  createDir resultsDir(bench)
  var name = now.format("yyyyMMdd'T'HHmmss'Z'")
  if benchLabel.len > 0: name.add "-" & benchLabel
  result = resultsDir(bench) / name & ".json"
  writeFile result, data.pretty & "\n"
  echo "[bench] wrote ", result
  let (o, code) = execCmdEx("git add " & quoteShell(result) & " && git commit -q -m " &
    quoteShell("Benchmark result: " & bench & " " & name) & " -- " & quoteShell(result))
  if code == 0: echo "[bench] committed ", result
  else: echo "[bench] could not commit ", result, ":\n", o

proc markdownTable*(df: DataFrame, boldLast = false): string =
  ## `df` as a Markdown table, as readers want it: capitalised headers, seconds with two
  ## decimals, rows with separators, "-" for nulls. `boldLast` is for a row of totals.
  let names = df.columns
  result = "| " & names.mapIt(it.capitalizeAscii).join(" | ") & " |\n| " &
    names.mapIt(if df.dtype(it) == String: "---" else: "--:").join(" | ") & " |\n"
  for i in 0 ..< df.height:
    var cells: seq[string]
    for name in names:
      let dtype = df.dtype(name)
      var cell = "-"
      if dtype == Float64:
        let x = df[name, i, Option[float]]
        if x.isSome: cell = formatFloat(x.get, ffDecimal, 2) & " s"
      elif dtype == Int64:
        cell = insertSep($df[name, i, int], ',')
      else:
        cell = df[name, i, string]
      cells.add (if boldLast and i == df.height - 1 and cell != "-": "**" & cell & "**" else: cell)
    result.add "| " & cells.join(" | ") & " |\n"

proc queryTabs*(nimSrc, pySrc: string, nimFrame: DataFrame, pyCall: string): string =
  ## A query's Nim and Python source in tabs, each with the table it gives (the Python
  ## one from running `pyCall`); fails the build if the two tables differ.
  let nimSide = "<pre><code class=\"nim-file nohighlight nim hljs\">" &
    highlightNim(nimSrc.strip) & "</code></pre>" & nimFrame.toHtml
  let (_, pyShown) = runPython(pyCall)
  checkSameFrame(nimSide, pyShown, pyCall)
  tabsHtml(nimSide, "<pre><code class=\"language-python py-file hljs\">" &
    xmltree.escape(pySrc.strip) & "</code></pre>" & pyShown)

proc sourcePart*(source, start: string, stops: openArray[string]): string =
  ## The part of `source` from the line starting with `start` to the next `stops`.
  let i = source.find(start)
  doAssert i >= 0, "not found: " & start
  var j = source.len
  for s in stops:
    let k = source.find(s, i + start.len)
    if k >= 0 and k < j: j = k
  source[i ..< j].strip

book/benchkit.nim

scripts/bench: a full run on your machine 23 lines
#!/bin/sh
# Runs a benchmark chapter of the book at full size, on this machine:
#
#   scripts/bench 1brc|pdsh|dbbench [nim options]
#
# e.g. `scripts/bench 1brc -d:benchRows=100000000 -d:benchLabel=my-laptop` or
# `scripts/bench pdsh -d:benchScale=10`.
# The chapter times the Nim and the Python queries, writes the timings and the
# machine's specs to results/<benchmark>/<timestamp>[-label].json, commits that
# file, and rebuilds its page. Needs Nim (with nimble), uv and git; run it from the
# repository root. It installs the book's Nim and Python dependencies first.
set -e
cd "$(dirname "$0")/.."
case "$1" in
  1brc) chapter=book/benchmarks/one_billion_rows.nim ;;
  pdsh) chapter=book/benchmarks/pds_h.nim ;;
  dbbench) chapter=book/benchmarks/db_benchmark.nim ;;
  *) echo "usage: scripts/bench 1brc|pdsh|dbbench [nim options]" >&2; exit 2 ;;
esac
shift
nimble install -y --depsOnly
uv sync --locked --quiet
exec uv run nim r -d:release -d:bench --hints:off "$@" "$chapter"

scripts/bench

import nanuq, nanuqbook, benchkit, pdsh
import ../foldcode
import std/[algorithm, os, json, strutils, osproc, sequtils]
bookInit()

const benchScale {.strdefine.} = "1"  ## scale factor of a full run (`-d:benchScale=10`)

nbText: "# PDS-H queries"

nanuq """
**About this chapter.** The queries are ported from the Polars queries of
[polars-benchmark](https://github.com/pola-rs/polars-benchmark), by the Polars
contributors, licensed under the
[Apache License 2.0](https://github.com/pietroppeter/nanuq-book/blob/main/licenses/polars-benchmark-Apache-2.0.txt).
The data comes from [tpchgen-cli](https://github.com/datafusion-contrib/tpchgen-rs), which
generates the TPC-H tables; it is made on the fly and never stored in the repository.
PDS-H is derived from TPC-H, but these results are not comparable to published TPC-H
results. The text is the book's own.

The code of the benchmark is folded under [Source files](#source-files), at the end.
"""

proc tpchData(scale: string): string =
  ## The tables at this scale factor, generated with tpchgen-cli the first time.
  result = ".." / "bench-data" / "tpch-" & scale
  if not fileExists(result / "lineitem.csv"):
    createDir result
    let (o, code) = execCmdEx("tpchgen-cli csv -s " & scale & " --output-dir=" & quoteShell(result))
    doAssert code == 0, "tpchgen-cli failed (run the book with `uv run`):\n" & o

type Query = tuple[n: int, run: proc (t: Tables): LazyFrame]

proc queries(scale: float): seq[Query] =
  @[(1, q1), (2, q2), (3, q3), (4, q4), (5, q5), (6, q6), (7, q7), (8, q8), (9, q9),
    (10, q10), (11, proc (t: Tables): LazyFrame = q11(t, scale)),
    (12, q12), (13, q13), (14, q14), (15, q15), (16, q16), (17, q17), (18, q18),
    (19, q19), (20, q20), (21, q21), (22, q22)]

proc pyCall(n: int, scale: float, engine = "in-memory"): string =
  "q" & $n & "(**_tables" & (if n == 11: ", scale_factor=" & $scale else: "") &
    ").collect(engine=" & escapeJson(engine) & ")"

proc loadPython(dir: string) =
  discard runPython("import sys\nsys.path.insert(0, '../bench')\nfrom pdsh import *\n" &
                    "_tables = scan_tables(" & escapeJson(dir) & ")")

# --- A full run: only with -d:bench -------------------------------------------------
when defined(bench):
  let scale = parseFloat(benchScale)
  let dir = tpchData(benchScale)
  let tables = scanTables(dir)
  loadPython(dir)
  var nimMemory, nimStreaming, pyMemory, pyStreaming = newJObject()
  for (n, run) in queries(scale):
    let q = "q" & $n
    echo "[bench] ", q
    nimMemory[q] = %timeIt(benchRuns, proc () = discard run(tables).collect(Engine.InMemory))
    nimStreaming[q] = %timeIt(benchRuns, proc () = discard run(tables).collect(Engine.Streaming))
    pyMemory[q] = %timePython(benchRuns, pyCall(n, scale))
    pyStreaming[q] = %timePython(benchRuns, pyCall(n, scale, "streaming"))
  discard saveResult("pdsh", %*{"scaleFactor": scale, "runs": benchRuns},
    %*{"nanuq in-memory": nimMemory, "nanuq streaming": nimStreaming,
       "python in-memory": pyMemory, "python streaming": pyStreaming})

# --- Results ----------------------------------------------------------------------
nbText: """
## Results

One table per run of the full benchmark on someone's machine: for each query, the best of
the timed runs, in seconds, reading the CSV files included. A dash means the run did not
use that engine: older runs timed Nanuq with one engine only, and runs with Nanuq 0.2 have
13 queries, so compare totals only between runs with the same number of queries.
"""

nbText: ""  # the tables, filled in below from the Polars query
let summary = nb.blk.NbText

nbText: """
## How the tables are made

Each run of the full benchmark leaves a JSON file in
[`results/pdsh/`](https://github.com/pietroppeter/nanuq-book/tree/main/results/pdsh), with
the machine, the versions and, for each engine and query, three timings. The tables above
are a Polars query over those files, so they come from the same tools as everything else
in this book.

The timings are two structs deep: engines, then queries. Two rounds of `unnest` and
`unpivot` turn each file into a long table with one row per engine and query, and
`list.min` keeps the best of the timed runs:
"""

tabs """
import glob
import polars as pl

index = ["date", "machine", "cpu", "nanuq", "scale"]


def timings(path):
    return (
        pl.read_json(path)
        .select(
            pl.col("timestamp").str.slice(0, 10).alias("date"),
            pl.col("label").alias("machine"),
            pl.col("system").struct.field("cpu"),
            pl.col("versions").struct.field("nanuqWrapper").alias("nanuq"),
            pl.col("params").struct.field("scaleFactor").alias("scale"),
            "timings",
        )
        .unnest("timings")
        .unpivot(index=index, variable_name="engine", value_name="queries")
        .unnest("queries")
        .unpivot(index=[*index, "engine"], variable_name="query", value_name="seconds")
    )


times = pl.concat(
    [timings(path) for path in sorted(glob.glob("../results/pdsh/*.json"))]
).with_columns(pl.col("seconds").list.min())
times.head(3)
""":
  nbCode:
    let index = @["date", "machine", "cpu", "nanuq", "scale"]

    proc timings(path: string): DataFrame =
      readJson(path)
        .select(
          col.timestamp.str.slice(0, 10).alias("date"),
          col.label.alias("machine"),
          col.system.struct.field("cpu"),
          col.versions.struct.field("nanuqWrapper").alias("nanuq"),
          col.params.struct.field("scaleFactor").alias("scale"),
          col.timings)
        .unnest("timings")
        .unpivot(index = index, variableName = "engine", valueName = "queries")
        .unnest("queries")
        .unpivot(index = index & "engine", variableName = "query", valueName = "seconds")

    let paths = sorted(toSeq(walkFiles("../results/pdsh/*.json")))
    let times = concat(paths.mapIt(timings(it)), how = ConcatMethod.Vertical)
      .withColumns(col.seconds.list.min)
    nbShow times.head(3)

nbText: """
Summing per run and engine, and a `pivot` with one column per engine, gives the total time
of each run:
"""

tabs """
(
    times.group_by([*index, "engine"], maintain_order=True)
    .agg(pl.len().alias("queries"), pl.col("seconds").sum().round(2))
    .pivot(on="engine", index=[*index, "queries"], values="seconds", sort_columns=True)
)
""":
  nbCode:
    nbShow times
      .groupBy(index & "engine", maintainOrder = true)
      .agg(len().alias("queries"), col.seconds.sum.round(2))
      .pivot(on = "engine", index = index & "queries", values = "seconds", sortColumns = true)

nbText: """
And query by query, on the latest run on an M3 Pro:
"""

tabs """
pl.Config.set_tbl_rows(22)  # the default shows 10 rows

(
    times.filter(pl.col("machine") == "pietro-mac")
    .filter(pl.col("date") == pl.col("date").max())
    .with_columns(pl.col("seconds").round(3))
    .pivot(on="engine", index="query", values="seconds", sort_columns=True)
)
""":
  nbCode:
    let byQuery = times
      .filter(col.machine == "pietro-mac")
      .filter(col.date == col.date.max)
      .withColumns(col.seconds.round(3))
      .pivot(on = "engine", index = "query", values = "seconds", sortColumns = true)
  nbRawHtml: byQuery.toHtml(maxRows = 22)  # the default shows 10 rows

discard runPython("pl.Config.set_tbl_rows(10)")

const engines = ["nanuq in-memory", "nanuq streaming", "python in-memory", "python streaming"]

proc runTable(date, machine: string): string =
  ## The table of one run: every engine, a row per query and a row of totals.
  let cells = engines.mapIt(col.seconds.filter(col.engine == it).first.alias(it))
  let run = times.filter(col.date == date and col.machine == machine)
    .groupBy("query", maintainOrder = true).agg(cells)
  # mean * count, not sum, which gives 0 for an engine the run did not use
  let totals = run.select(@[lit("total").alias("query")] &
    engines.mapIt((col(it).mean * col(it).count).alias(it)))
  markdownTable(concat([run, totals]), boldLast = true)

for path in paths:
  let run = readJson(path).select(
    col.timestamp.str.slice(0, 10).alias("date"),
    col.label.alias("machine"),
    col.params.struct.field("scaleFactor").alias("scale"),
    format("{}, {} cores, {} GB, {}. Nanuq {}, Polars {}, Nim {}.",
           col.system.struct.field("cpu"), col.system.struct.field("cores"),
           col.system.struct.field("memoryGB"), col.system.struct.field("os"),
           col.versions.struct.field("nanuqWrapper"),
           col.versions.struct.field("pythonPolars"),
           col.versions.struct.field("nim")).alias("about"))
  let (date, machine) = (run["date", 0, string], run["machine", 0, string])
  summary.text.add "### " & date & " (" & machine & "), scale factor " &
    $run["scale", 0, float] & "\n\n" & run["about", 0, string] & "\n\n" &
    runTable(date, machine) & "\n"

nbText: """
## The benchmark

[TPC-H](https://www.tpc.org/tpch/) is the classic decision-support benchmark: eight
tables of a wholesale business (orders, line items, customers, suppliers, parts and the
nations and regions they are in) and 22 queries that report on them. Polars publishes
how fast it runs them as [PDS-H](https://pola.rs/posts/benchmarks/), with its queries in
the polars-benchmark repository.

Nanuq 0.3 runs all 22. (Nanuq 0.2 ran 13 of them: the others need string functions or
the year of a date, which came with 0.3.)
"""

nanuq """
The Python queries are the originals, unchanged; both sides read the CSV files with
`tryParseDates`, so the date columns are dates. In Nim, Python's `date(1995, 3, 15)` is
Nanuq's `date(1995, 3, 15)`, column names that Python passes as strings are `col(...)`,
keys are lists, `pl.len()` is the length of a column and `when/then/otherwise` is
`choose`. One query takes a detour for an expression Nanuq does not have yet: q20 takes the
unique keys with the frame's `unique` (no `Expr.unique`).
"""

nbText: """
The queries are in [`bench/pdsh.nim`](#src-bench-pdsh-nim)
and [`bench/pdsh.py`](#src-bench-pdsh-py).
When the book is built, each one runs on both sides on a small dataset (scale factor
0.01, about 10 MB of CSV), and the build checks that the two tables are the same.
"""

let nimSource = readFile(".." / "bench" / "pdsh.nim")
let pySource = readFile(".." / "bench" / "pdsh.py")

block:
  let dir = tpchData("0.01")
  let tables = scanTables(dir)
  loadPython(dir)
  for (n, run) in queries(0.01):
    nbText: "## Q" & $n
    let nimSrc = sourcePart(nimSource, "proc q" & $n & "*", ["\nproc "])
    let pySrc = sourcePart(pySource, "def q" & $n & "(", ["\n\n\ndef "])
    nbRawHtml: queryTabs(nimSrc, pySrc, run(tables).collect, pyCall(n, 0.01))

nbText: """
## Running it on your machine

From the root of a clone of the book, with Nim, nimble, uv and git (the script
installs the book's dependencies first; the data goes to
`bench-data/`, which git ignores; scale factor 1 is about 1 GB of CSV):

```sh
scripts/bench pdsh                          # scale factor 1, 3 timed runs per query
scripts/bench pdsh -d:benchScale=10         # scale factor 10
scripts/bench pdsh -d:benchLabel=my-laptop  # a name for your machine
```

It writes the timings and the machine's specs to a timestamped file in `results/pdsh/`
and commits it; a pull request with that file adds a run to the tables at the top.
"""

nbSourceFiles:
  nbFoldCode "bench/pdsh.nim"
  nbFoldCode "bench/pdsh.py"
  nbFoldCode "book/benchkit.nim", title = "`book/benchkit.nim`: timing, results and tables of the benchmark chapters"
  nbFoldCode "scripts/bench", title = "`scripts/bench`: a full run on your machine"

bookSave()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.