// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * Build the UN/locode lookup DB from the unece code list CSV * (datasets/un-locode `code-list.csv`: columns Change, Country, Location, Name, * NameWoDiacritics, Subdivision, Status, Function, Date, iata, Coordinates, Remarks). * * One row per assigned location. coordinates parsed where present. */ import { DatabaseClient } from "@mailwoman/sqlite/client" import { CSVSpliterator } from "spliterator" import { foldName, parseUNLocodeCoords } from "#index" import type { UNLocodeDatabase } from "#schema" interface CSVRow { Country: string Location: string Name: string NameWoDiacritics: string Coordinates: string } /** * Read the code-list CSV at `csvPath` and write the lookup DB to `dbPath`. */ export async function buildUNLocodeDB(csvPath: string, dbPath: string): Promise<{ rows: number; withCoords: number }> { // `normalizeKeys: false` keeps the unece header casing the row shape above is // written against (`NameWoDiacritics`, not `name_wo_diacritics`). const records = CSVSpliterator.fromAsync(csvPath, { normalizeKeys: false, }) using db = new DatabaseClient(dbPath) db.exec("DROP TABLE IF EXISTS un_locode") db.exec( "CREATE TABLE un_locode (country TEXT NOT NULL, location TEXT NOT NULL, name TEXT, nameNorm TEXT, lat REAL, lon REAL)" ) const insert = db.prepare("INSERT INTO un_locode (country, location, name, nameNorm, lat, lon) VALUES (?,?,?,?,?,?)") let withCoords = 0 let rows = 0 db.exec("BEGIN") for await (const r of records) { rows++ if (!r.Country || !r.Location) continue // header/country rows have no Location const coords = r.Coordinates ? parseUNLocodeCoords(r.Coordinates) : null if (coords) { withCoords++ } const name = r.NameWoDiacritics || r.Name || "" insert.run(r.Country, r.Location, r.Name || name, foldName(name), coords?.lat ?? null, coords?.lon ?? null) } db.exec("COMMIT") db.exec("CREATE INDEX idx_locode_name ON un_locode (country, nameNorm)") db.exec("CREATE INDEX idx_locode_bbox ON un_locode (lat, lon)") return { rows, withCoords } }