Cotton code
166 lines · 6.4 KB · TypeScriptRaw
/** * What Cotton publishes from the sets `scripts/datasets/` builds: each built * SQLite file read as the rows of one published database (src/published.ts). * Pure: a file in, rows out; `publish-datasets.ts` sends them. * *   cotton/places         places (GeoNames cities500), countries (GeoNames countryInfo) *   cotton/holidays       holidays, coverage (python-holidays) *   cotton/airports       airports (OurAirports) *   cotton/english_words  words (SCOWL), looked up by id: the word * * Licence notes travel with the sets: GeoNames is CC BY 4.0, OurAirports is * public domain, python-holidays MIT, SCOWL its own permissive licence * (scripts/datasets/pins.json names each source). */import type { DatabaseSync } from "node:sqlite";export interface PublishedRow {  id: string;  row: Record<string, unknown>;  names?: string[];  lat?: number;  lng?: number;  rank?: number;  group?: string;}export interface Table {  table: string;  rows: () => Iterable<PublishedRow>;}export interface PublishedSet {  /** The published database's name under the publisher `cotton`. */  name: string;  /** The built files it is read from, under the datasets folder. */  files: string[];  tables: (open: (file: string) => DatabaseSync) => Table[];}type Row = Record<string, string | number | null>;function* all(db: DatabaseSync, sql: string): Iterable<Row> {  yield* db.prepare(sql).iterate() as Iterable<Row>;}const text = (v: unknown): string => (v === null || v === undefined ? "" : String(v));export const SETS: PublishedSet[] = [  {    name: "places",    files: ["places.sqlite", "countries.sqlite"],    tables: (open) => {      const countries = open("countries.sqlite");      const names = new Map<string, string>();      for (const c of all(countries, "SELECT id, name FROM countries")) names.set(text(c.id), text(c.name));      return [        {          table: "places",          rows: function* () {            for (const p of all(open("places.sqlite"), "SELECT id, name, alternate_names, country, admin1, lat, lon, population, timezone FROM places ORDER BY id")) {              const country = text(p.country);              yield {                id: `geonames:${p.id}`,                row: { name: text(p.name), admin1: text(p.admin1), country, country_name: names.get(country) ?? "", zone: text(p.timezone), population: Number(p.population) },                names: [text(p.name), ...text(p.alternate_names).split(",")].filter((n) => n.trim()),                lat: Number(p.lat),                lng: Number(p.lon),                rank: Number(p.population),                group: country,              };            }          },        },        {          table: "countries",          rows: function* () {            for (const c of all(countries, "SELECT id, name, dialling_code, currency, flag FROM countries ORDER BY id")) {              yield { id: text(c.id), row: { name: text(c.name), dialling_code: text(c.dialling_code), currency: text(c.currency), flag: text(c.flag) }, names: [text(c.name), text(c.id)] };            }          },        },      ];    },  },  {    name: "holidays",    files: ["holidays.sqlite"],    tables: (open) => {      const db = open("holidays.sqlite");      return [        {          // Found by "<country> <region> <year>" from the front ("IN 2026", "IN TG 2026-08"), earliest first.          table: "holidays",          rows: function* () {            for (const h of all(db, "SELECT id, date, name, country, region FROM holidays ORDER BY id")) {              const date = text(h.date);              yield { id: text(h.id), row: { date, name: text(h.name), country: text(h.country), region: text(h.region) }, names: [[h.country, h.region, date].map(text).filter(Boolean).join(" ")], rank: -Number(date.replaceAll("-", "")), group: text(h.country) };            }          },        },        {          table: "coverage",          rows: function* () {            for (const c of all(db, "SELECT country, region, first_date, last_date FROM holiday_coverage ORDER BY country, region")) {              yield { id: `${text(c.country)}|${text(c.region)}`, row: { country: text(c.country), region: text(c.region), first_date: text(c.first_date), last_date: text(c.last_date) } };            }          },        },      ];    },  },  {    name: "airports",    files: ["airports.sqlite"],    tables: (open) => [      {        table: "airports",        rows: function* () {          for (const a of all(open("airports.sqlite"), "SELECT id, iata, icao, name, city, country, lat, lon, timezone FROM airports ORDER BY id")) {            yield {              // The IATA code is the id a person and a mail know an airport by; OurAirports' own id rides along.              id: text(a.iata),              row: { source_id: text(a.id), iata: text(a.iata), icao: text(a.icao), name: text(a.name), city: text(a.city), country: text(a.country), zone: text(a.timezone) },              names: [a.iata, a.icao, a.name, a.city].map(text).filter(Boolean),              lat: Number(a.lat),              lng: Number(a.lon),              group: text(a.country),            };          }        },      },    ],  },  {    name: "english_words",    files: ["english_words.sqlite"],    tables: (open) => [      {        // Membership by id (the word, lower case): no search keys, so no index beyond the id.        table: "words",        rows: function* () {          for (const w of all(open("english_words.sqlite"), "SELECT term FROM english_words ORDER BY term")) yield { id: text(w.term), row: {} };        },      },    ],  },];/** The version a set publishes under: the build's version and the first bytes of its sources' digests, so a rebuild from new sources is a new version. */export function versionOf(open: (file: string) => DatabaseSync, set: PublishedSet): string {  const parts = set.files.map((file) => open(file).prepare("SELECT version, source_sha256 FROM dataset").get() as { version: string; source_sha256: string });  return `${parts[0]!.version}-${parts.map((p) => p.source_sha256.slice(0, 8)).join("")}`.slice(0, 41);}/** Rows in batches no bigger than a write takes. */export function* batches<T>(rows: Iterable<T>, size: number): Iterable<T[]> {  let batch: T[] = [];  for (const row of rows) {    batch.push(row);    if (batch.length === size) {      yield batch;      batch = [];    }  }  if (batch.length) yield batch;}