#!/usr/bin/env python3 """The served file: every view in dbt's serving schema, copied into one SQLite. Nothing is decided here. What ships, and every number in it, is dbt's: the views in dbt/models/serving/ are the list, and the marts under them are where anything is computed and tested. This is post-processing only -- layout SQLite's physical design: which tables are WITHOUT ROWID and on what key, and their secondary indexes. Reads are point lookups and short range scans, so the key order is the whole design. search FTS5 over the search terms, the one index SQLite has to build itself. types what SQLite cannot hold as DuckDB does: lists and structs become JSON text, 128-bit integers become 64-bit, decimals doubles. It replaced scripts/build_tiers.py, which had grown to decide which taxa ship, clean interaction records, count support, climb clade rollups and pack blobs, across seven files a reader stitched back into one. None of that could be tested where it happened, and the warehouse and the served file came to disagree about the same numbers. uv run python scripts/export.py TAXONOMY_SQLITE=/tmp/t.sqlite uv run python scripts/export.py """ import os import sqlite3 import time import duckdb SOURCE = os.environ.get("TAXONOMY_DB", "data/taxonomy.duckdb") OUT = os.environ.get("TAXONOMY_SQLITE", "data/taxonomy.sqlite") # dbt-duckdb names a custom schema _. SERVING = "main_serving" # Every serving view, with (primary key, secondary indexes). A key makes the # table WITHOUT ROWID -- the b-tree is the table, filled in key order, so a # read by key prefix is one seek and a sequential scan. Tables of large rows # (JSON, geometry) stay rowid tables: WITHOUT ROWID keeps only about 1,000 # bytes of a row on its page and spills the rest to an overflow page each. LAYOUT = { # The last covers bloom's partner and candidate filters -- kingdom, US # nativity, rank -- so a taxon row is never read just to be filtered out. # Cold, that row is a random page read per candidate. "taxon": (None, ["unique (inat_taxon_id)", "(parent_inat_taxon_id)", "(class, observations_count desc)", "(inat_taxon_id, kingdom, us_establishment_means, taxon_rank)"]), "taxon_aux": (None, ["unique (inat_taxon_id)"]), "taxon_media": (None, ["unique (inat_taxon_id)"]), "taxon_place": (("inat_taxon_id", "inat_place_id"), []), "clade_place": (("inat_taxon_id", "inat_place_id"), []), "taxon_range": (None, ["unique (inat_taxon_id)"]), "place": (None, ["unique (inat_place_id)"]), # Covers home's layer checks: field = 'plant_type', confidence <> # 'contested', token IN (...). "plant_traits": (None, ["(inat_taxon_id, field, confidence, token)"]), "plant_conditions": (None, ["(inat_taxon_id)"]), "county_shape": (None, ["unique (fips)", "(state_place)"]), "interaction_type": (None, ["unique (type_id)", "unique (interaction_slug)"]), # n_records inside the key, so a partner list reads in the order it is # shown and a LIMIT stops the scan instead of sorting. The partner index # carries larval so an animal's "Supported by" list, which ranks larval # hosts first, never reads the table; being WITHOUT ROWID, the index holds # the key's columns already. "taxon_interaction": (("inat_taxon_id", "type_id", "n_records desc", "partner_inat_taxon_id"), ["(partner_inat_taxon_id, larval, tier)"]), "taxon_interaction_type": (("inat_taxon_id", "n_records desc", "type_id"), []), # A row's citations, read as its key range: the datasets and seed rows # behind it, and the references its records cite. The citations themselves # are written once and joined to by id. "interaction_source": (("source_id",), []), "taxon_interaction_source": (("inat_taxon_id", "type_id", "partner_inat_taxon_id", "source_id"), []), "interaction_reference": (("reference_id",), []), "taxon_interaction_reference": (("inat_taxon_id", "type_id", "partner_inat_taxon_id", "reference_id"), []), # The last is clade_support_us's order: native plants by the kind of # support they give, caterpillar hosts first. "taxon_support": (None, ["unique (inat_taxon_id)", "(n_supported desc)", "(n_animals desc)", "(n_native_animals desc)", "(n_caterpillars desc)", "(n_native_caterpillar_hosts desc, n_native_hosts desc," " n_native_food desc, n_native_flowers desc," " n_native_shelter desc)"]), "taxon_supported_by": (None, ["unique (inat_taxon_id)"]), "caterpillar_breadth": (None, ["unique (inat_taxon_id)"]), # A plant's animals or an animal's plants in the order they are shown: a # list is one key range, read until the reader's scope has enough. "support_partner": (("inat_taxon_id", "pos"), []), "taxon_group": (None, ["unique (inat_taxon_id)"]), "interaction_group": (None, ["unique (grp)"]), "cell_index": (("idx",), []), # Read both ways: one taxon's map, and everything in the reader's cell. "taxon_cell": (("inat_taxon_id", "cell_idx"), ["(cell_idx, inat_taxon_id, grade)"]), "clade_cell": (("inat_taxon_id", "cell_idx"), []), "clade_place_grade": (("inat_place_id", "inat_taxon_id"), []), "taxon_place_grade": (("inat_place_id", "inat_taxon_id"), []), # A taxon's nativity trace, read as its key ranges: how each place's # grade was reached, and the hand-set rows and effort ratios a cell's # steps point at. A cell's own steps are columns of taxon_cell. "taxon_place_trace": (("inat_taxon_id", "inat_place_id"), []), "checklist_statement": (("inat_taxon_id", "state"), []), "nativity_override": (("inat_taxon_id", "state"), []), "taxon_state_effort": (("inat_taxon_id", "state"), []), # A cell's county evidence: its counties and their land, how well USDA # recorded each, and where USDA records the plant. "cell_county": (("cell_idx", "fips"), []), "county_usda": (("fips",), []), "taxon_usda": (("inat_taxon_id",), []), "taxon_usda_state": (("inat_taxon_id", "state_fips"), []), "taxon_usda_county": (("inat_taxon_id", "fips"), []), "trace_link": (("kind",), []), "cell_support": (("cell_idx", "inat_taxon_id"), []), "cell_supported_by": (("cell_idx", "inat_taxon_id"), []), "clade_support_us": (("inat_taxon_id", "pos"), []), "clade_support_cell": (("inat_taxon_id", "cell_idx", "pos"), []), "clade_observed_us": (("inat_taxon_id", "pos"), []), "clade_observed_cell": (("inat_taxon_id", "cell_idx", "pos"), []), # A layer's list in rank order, one key range: home reads the head of # each, a layer page pages on. The cell's leads, so one site is one range. "layer_plant_us": (("layer", "pos"), []), "layer_plant_cell": (("cell_idx", "layer", "pos"), []), # A layer's keystones by rank; a keystone's plants are its rows in layer_plant_*. "layer_keystone_us": (("layer", "pos"), []), "layer_keystone_cell": (("cell_idx", "layer", "pos"), []), # Not shipped as itself: becomes fts_row and the fts index, below. "search_term": (None, []), } def columns(con, catalog, view): """A select list SQLite can hold, in the view's own column order.""" parts = [] for name, ty in con.execute( "select column_name, data_type from duckdb_columns() where database_name = ?" " and schema_name = ? and table_name = ? order by column_index", [catalog, SERVING, view]).fetchall(): if "[]" in ty or "STRUCT" in ty or ty.startswith("MAP") or ty == "JSON": # DuckDB's sqlite writer prints a LIST in its own display format, # which json.loads rejects -- `[BE, BG]`, unquoted. parts.append(f'to_json("{name}") as "{name}"') elif ty in ("HUGEINT", "UHUGEINT"): # The writer stores a HUGEINT as text, silently. parts.append(f'cast("{name}" as bigint) as "{name}"') elif ty.startswith("DECIMAL"): parts.append(f'cast("{name}" as double) as "{name}"') else: parts.append(f'"{name}"') return ", ".join(parts) def main(): started = time.time() building = f"{OUT}.building" if os.path.exists(building): os.remove(building) # In memory with the warehouse attached read-only, because a read-only # connection cannot create the SQLite file it attaches. Attached under its # file's own name: that is the catalog dbt built the views in, and what # they name their marts by. con = duckdb.connect() for ext in ("spatial", "sqlite"): con.execute(f"install {ext}") con.execute(f"load {ext}") catalog = os.path.splitext(os.path.basename(SOURCE))[0] con.execute(f"attach '{os.path.abspath(SOURCE)}' as \"{catalog}\" (read_only)") con.execute(f'use "{catalog}"') views = {r[0] for r in con.execute( "select view_name from duckdb_views() where database_name = ? and schema_name = ?", [catalog, SERVING]).fetchall()} # A view with no layout would ship as an unindexed heap, slow without # saying so; refuse it. A layout with no view is a table dbt did not build # this time -- the interaction ones, with var('globi') off -- and is left # out rather than faked. if views - set(LAYOUT): raise SystemExit(f"no LAYOUT for serving views {sorted(views - set(LAYOUT))}") if set(LAYOUT) - views: print(f" not built, not shipped: {', '.join(sorted(set(LAYOUT) - views))}") con.execute(f"attach '{os.path.abspath(building)}' as o (type sqlite)") counts = {} for view in sorted(views): con.execute(f'create table o."{view}" as select {columns(con, catalog, view)}' f' from {SERVING}."{view}"') counts[view] = con.execute(f'select count(*) from o."{view}"').fetchone()[0] print(f" {view:<24} {counts[view]:>12,} rows {time.time() - started:5.0f}s", flush=True) con.execute("detach o") con.close() db = sqlite3.connect(building, isolation_level=None) db.execute("pragma journal_mode = off") db.execute("pragma synchronous = off") # Two passes over the keyed tables because DuckDB's sqlite writer insists # on a ROWID: inserting into a pre-made WITHOUT ROWID table fails with # `SELECT ROWID FROM "t": no such column`. for table, (key, indexes) in LAYOUT.items(): if table not in views: continue if key: cols = ", ".join(f'"{n}" {t}'.strip() for _, n, t, *_ in db.execute(f'pragma table_info("{table}")')) order = ", ".join(key) db.execute(f'create table "{table}__k" ({cols}, primary key ({order}))' " without rowid") db.execute(f'insert into "{table}__k" select * from "{table}" order by {order}') db.execute(f'drop table "{table}"') db.execute(f'alter table "{table}__k" rename to "{table}"') for n, spec in enumerate(indexes): unique = "unique " if spec.startswith("unique") else "" db.execute(f'create {unique}index "{table}_{n}" on "{table}"' f' {spec.removeprefix("unique").strip()}') # Contentless FTS5, so the term text is matchable but not stored twice; # fts_row carries what search ranks by, on the same rowid. columnsize=0 # drops the length table FTS5 keeps for ranking nothing here uses. db.execute("create table fts_row (rowid integer primary key," " inat_taxon_id integer, score real, n_tokens integer)") db.execute("insert into fts_row (rowid, inat_taxon_id, score, n_tokens)" " select rowid, inat_taxon_id, score, n_tokens from search_term") db.execute("create virtual table fts using fts5(term, content='', columnsize=0)") db.execute("insert into fts (rowid, term) select rowid, term from search_term") db.execute("insert into fts (fts) values ('optimize')") # The vocabulary, for correcting a typo against terms that exist. db.execute("create virtual table fts_vocab using fts5vocab('fts', 'row')") db.execute("drop table search_term") counts["fts_row"] = counts.pop("search_term") db.execute("create table meta (key text primary key, value text)") db.executemany("insert into meta values (?, ?)", [ ("built_at", time.strftime("%Y-%m-%dT%H:%M:%S")), ("source", os.path.abspath(SOURCE))]) # The one check that belongs here rather than in dbt: that the copy is a # copy. Everything about the rows themselves is tested where they are made. short = {t: (n, db.execute(f'select count(*) from "{t}"').fetchone()[0]) for t, n in counts.items()} short = {t: v for t, v in short.items() if v[0] != v[1]} if short: raise SystemExit(f"row counts changed in the copy: {short}") db.execute("vacuum") db.execute("analyze") db.close() os.replace(building, OUT) print(f"{OUT}: {len(counts)} tables, {os.path.getsize(OUT) / 1e9:.2f} GB," f" {(time.time() - started) / 60:.1f} min") if __name__ == "__main__": main()