feat(places): Swiss structure — FSO commune register and Zürich quarters import through real adapters (#215)

* feat(places): Swiss structure — FSO commune register and Zürich quarters import through real adapters

- adapters parse formats and name no country; which levels and schemes rows
  become is each source's options in config, checked by the adapter's schema
- bfs_communes_snapshot (every canton, district, commune on a date),
  bfs_communes_mutations (mergers as succeeds), geojson_tiers (city quarters)
- places:fetch retrieves what an adapter declares; --backfill loads history once
- importer: relation-only batches, ended places filed under their last parent
- Swiss pack: levels, schemes, metrics, income-tax model (no church tax yet)
- licence policy: opendata.swiss terms and Art. 5 URG official acts
- acceptance: Witikon resolves to Switzerland and takes no tax; reruns change nothing

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(changelog): Swiss structure (#215)

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
CatoandCursor authored and GitHub committed 2026-09-29 22:44:16 +02:00
1 parent d5aaa4a2ad
commit b7027f1122
27 files changed
+1608 -27

No files matched your search

+4
View File
@@ -42,6 +42,10 @@ calls it verbatim. Green `verify` locally ⇒ green CI.
<file> [--dry-run]` (`src/lib/places/importer/`) snapshots, parses with the source's
adapter (`src/lib/places/adapters/`), checks against config, applies in one
transaction and runs the invariant engine; every run lands in `place_import_runs`.
`pnpm run places:fetch <source-key> [--backfill] [--dry-run] [--plan]` retrieves
what the adapter declares from the source's URL and imports each in turn;
`--backfill` loads history once, on a source's first load only. Adapters parse a
format; which levels and schemes rows become is the source's `options` in config.
No engine file names a country: Testland (`src/lib/places/__tests__/fixtures/testland/`)
must keep importing and evaluating with changes only to its pack and fixtures.
`pnpm run check:places-literals` (in `verify`) fails on any registry key, ISO
+7
View File
@@ -8,6 +8,13 @@ one to read for the detail. Fixes get the same weight as features.
### Added
- **Switzerland, as the official register has it.** Every canton, district
and commune, with the mergers since 2021 (the old communes stay, marked as
ended, and point to the one they joined), and the City of Zürich's districts
and statistical quarters, each with a page at its place in the chain:
`/places/switzerland/zurich/bezirk-zurich/zurich/kreis-7/witikon`. Everything
comes from the Federal Statistical Office and the city's open data, with the
source kept for every row. Taxes, postcodes and the map come next. (#215)
- **A new kind of body: charter city.** A city with its own charter, founded
by agreement with the state that hosts it — or proposed, before that
agreement. Like a town, it cannot be founded without a place; picking it
@@ -1,7 +1,11 @@
# Places: every jurisdiction on one map, official and founded
_Created 2026-09-29. Status: accepted design; nothing here is built unless it says so._
_Last modified 2026-09-29: the `charter_city` kind built; P0 is built apart
_Last modified 2026-09-29: P1 begun — the Swiss pack's structure is built:
the FSO commune register (all cantons, mergers since 2021) and the City of
Zürich's quarters import through real adapters that `places:fetch` retrieves,
with adapter options in config and Swiss terms of use on the licence policy
(§5.2, §8.1–§8.3, §11). Earlier the same day: the `charter_city` kind built; P0 is built apart
from the Register organization, which needs George's signature (§3, §11).
Earlier the same day: the no-literals and neutral-copy guards built, map
tokens added upstream (§9.1, §12); the minimal place page built; the P0 acceptance
@@ -369,6 +373,15 @@ Nothing in that block is read by name anywhere in `src/`. The engine iterates
`levels`, resolves `parent`, looks up `names` for the reader's locale, and hands
`taxModel` to the evaluator.
**Built (P1)**: `src/lib/config/places/countries/switzerland.ts`. It differs from
the sketch in three ways. The levels stop at what P1 imports (nation, canton,
district, municipality, and the City of Zürich's districts and statistical
quarters as `partial`); parishes and school communities come with P2. The
income-tax model has no church component for the same reason. And the
nation has no identifier source yet, so the commune-register source creates
the root and states its ISO code, set in that source's options; a later
world source matches it by that code.
### 5.3 Config → database projection
Registries that facts FK-reference (`place_country_packs`, `place_levels`,
@@ -522,6 +535,16 @@ the obvious world datasets differ: some are public domain or CC0, some CC BY
the same terms), some non-commercial (excluded). No share-alike source in
P1–P4 (decided, §13).
**Built (P1)**: Swiss public bodies publish under terms of use, not licences,
because raw data is mostly not protected by copyright in Switzerland. The
policy lists them as `LicenseRef-` entries, each the equivalent of a class the
decision admits: `LicenseRef-opendata-swiss-open` (opendata.swiss "Open use",
citing recommended; public-domain-like), `LicenseRef-opendata-swiss-by` ("Open
use. Must provide the source."; CC BY's obligation), and
`LicenseRef-ch-official-act` (official acts, decisions and their figures, such
as tariffs and multipliers, which Art. 5 URG leaves unprotected). The
Register can narrow this by decision like any editorial policy.
### 8.2 Sources, by publisher
Each importer's first task is to **confirm access path, format and licence**
@@ -546,6 +569,22 @@ licence SPDX, attribution key, cadence as a cron expression, adapter module,
packs served). Cadence is config, so the scheduler reads it and no job has a
hardcoded date.
**Built (P1)**, each confirmed on 2026-09-29 and recorded in
`src/lib/config/places/sources.ts`:
| Source key | What | Access | Terms |
|---|---|---|---|
| `bfs-communes-snapshot` | every canton, district and commune valid on a date, with validity and parent | FSO register API, CSV, no key | opendata.swiss open |
| `bfs-communes-mutations` | mergers between two dates | same API | opendata.swiss open |
| `zurich-statistical-quarters` | the City of Zürich's 12 districts and 34 quarters | the city's WFS, GeoJSON | CC0 |
Found for the next steps: the canton's commune multipliers since 2012
(Statistical Office of the Canton of Zürich, CSV, "must provide the source");
federal and cantonal tariffs and the canton's own multiplier (the Federal Tax
Administration's tax-calculator exports, official figures); the city's address
register with postcode, quarter and parishes per address (CC0), which gives
postcode → quarter with shares.
### 8.3 The importer framework
One framework, one adapter per source. The framework owns everything the
@@ -603,10 +642,29 @@ prints the report and exits 1 on a failed run. What the build settled:
chain's current facts, and those facts in the evaluator's terms. Whether a
level takes tax is `taxingLevels` over them, from the model, not a flag.
Not yet: fetching from a URL (P1 hands the file in; the scheduled fetch comes
with the first real adapter), areas and assertions (P4), and CI dry-runs of
real adapters (none exist yet; the fixture adapter is exercised by the
acceptance spec).
**Built (P1)**: fetching. An adapter may declare `retrievals(options, today)`,
what a scheduled run fetches, which must change nothing when rerun on an
unchanged source, and `backfill`, older states loaded once when a source is
first loaded (never by schedule, since an older state imported after a newer
one restates the past). `pnpm run places:fetch <source-key> [--backfill]
[--dry-run] [--plan]` fetches them in order and imports each; the first failed
run stops the rest. What the first real adapters settled:
- **Adapters parse formats and name no country.** Which levels, schemes and
parts of a source its rows become is the source's `options` in config,
checked by the adapter's own schema at run time and by a unit test for every
registered source. The no-literals guard covers the adapters too.
- A source may state relations of places it does not list (a register of
mergers); those relations are diffed like any other the source states.
- An ended place is filed under the last parent it had. When an ended place
and a current one share a name, the one recorded first keeps the plain path,
so a backfill imports today's state first.
- Measured on the full register: the backfill (today, then one snapshot a year
since 2021) takes about 25 seconds on a laptop; a rerun changes nothing.
Not yet: areas and assertions (P4), the scheduled runner on the box, and CI
dry-runs of real adapters against live sources (CI imports cuts of the real
retrievals instead).
### 8.4 Corrections and editorial policy: the Register
@@ -787,6 +845,16 @@ before the build.
takes tax) › Zürich (canton) › Switzerland. City of Zürich vs Küsnacht at CHF
100,000 shows two estimates matching the golden fixtures, and every number
links to its snapshot.
- Built so far: the structure. `src/lib/config/places/countries/switzerland.ts`
(levels, schemes, the income-tax model without church tax, which P2's
parishes bring); the FSO register for **all** cantons rather than Zürich
alone, because its mergers can only be linked when both ends are known
places, with snapshots since 2021 and 79 mergers as `succeeds`; the City of
Zürich's 12 districts and 34 quarters. Witikon resolves up its chain to
Switzerland and its page says it takes no tax
(`swiss-structure.integration.test.ts`, from cuts of the real retrievals).
Next: tariffs and multipliers with golden fixtures, the postcode resolver,
then the screens.
**P2: Switzerland in depth**
- All municipalities, all cantonal models and multipliers, church and school
+7 -4
View File
@@ -4,7 +4,8 @@ _Written 2026-09-25 from George's brief. Companion to
`2026-09-solon-constitution-engine.md` (the governance engine). This file is the
product: who it is for, what they read, how they move through it, in which
language, and the order it gets built in._
_Last modified 2026-09-29: Places P0 marked built in the build order (§9, G).
_Last modified 2026-09-29: Places P1 begun, the Swiss structure imports (§9, G).
Earlier the same day: Places P0 marked built in the build order (§9, G).
Earlier the same day: added Places (every jurisdiction, official and
founded, on one map) to the information architecture and the build order; its
design is `2026-09-places-and-jurisdictions.md`, whose decisions George took the
@@ -63,7 +64,7 @@ footer (decided 2026-09-29).
| **Governance** `/governance` | the art and science (existing lessons) · **ideas** (Solon of Athens, the Landsgemeinde, Ostrom, exit and voice, Condorcet and Arrow, panarchy, network states) · **a new era** (why self-governance is newly possible) |
| **Platform** `/platform` | how Solon, OrangeCat and Loki work together · security · `/technical` (reference) |
| **Decisions** | the public record: organizations, proposals, votes |
| **Places** `/places` (foundations built, no country yet; the map and list come with P1) | every jurisdiction, official and founded, on one map: compare, take part, move · design in `2026-09-places-and-jurisdictions.md` |
| **Places** `/places` (foundations built; Switzerland's communes and the City of Zürich's quarters import; the map and list come later in P1) | every jurisdiction, official and founded, on one map: compare, take part, move · design in `2026-09-places-and-jurisdictions.md` |
| Account | **My Solon** `/me` — my groups, votes waiting for me, my proposals · profile |
Footer and mobile menu render the whole map from `site-config.ts` (existing SSOT,
@@ -158,8 +159,10 @@ Each phase ships on its own, verified live.
P0 (foundations, no country yet) is built: tables, config registries, the
importer, the invariant engine, a minimal place page, the guards and the
`charter_city` kind, proven by a made-up country in CI. Still open in P0:
the Register organization, which George founds and signs. Next: P1, the
Canton of Zürich.
the Register organization, which George founds and signs. P1, the Canton
of Zürich, has begun: the structure (every Swiss canton, district and
commune with mergers since 2021, the City of Zürich's quarters) imports from
the official sources. Next: tariffs, multipliers, postcodes, the screens.
## 10. Open for George
+1
View File
@@ -26,6 +26,7 @@
"check:vendored-drift": "node scripts/check-vendored-drift.mjs",
"places:sync-config": "tsx scripts/places-sync-config.ts",
"places:import": "tsx scripts/places-import.ts",
"places:fetch": "tsx scripts/places-fetch.ts",
"check:places-literals": "tsx scripts/check-places-no-literals.ts"
},
"dependencies": {
+60
View File
@@ -0,0 +1,60 @@
/**
* Fetch a source as its adapter plans it for today, and import each retrieval
* in order (design §8.3). The scheduled runner calls this per the source's
* cadence; run by hand, it is how a source is first loaded.
*
* pnpm run places:fetch <source-key> [--backfill] [--dry-run] [--plan]
*
* --backfill loads the source's history first (once, when a source is first
* loaded; the schedule never passes it). --plan prints the URLs it would fetch
* and stops. Exit 1 on a failed run, so a cron runner alerts.
*/
import { execFileSync } from "node:child_process";
import { placesConfig } from "@/lib/config/places";
import { db } from "@/lib/db/client";
import { fetchAndImport, plannedRetrievals } from "@/lib/places/importer/fetch";
import { defaultSnapshotStore } from "@/lib/places/importer/snapshots";
const args = process.argv.slice(2);
const [sourceKey] = args.filter((a) => !a.startsWith("--"));
const today = new Date().toISOString().slice(0, 10);
const backfill = args.includes("--backfill");
if (!sourceKey) {
console.error("usage: pnpm run places:fetch <source-key> [--backfill] [--dry-run] [--plan]");
process.exit(2);
}
function gitSha(): string | null {
try {
return execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
} catch {
return process.env.GIT_SHA ?? null;
}
}
async function main(): Promise<number> {
if (args.includes("--plan")) {
console.log(plannedRetrievals(placesConfig, sourceKey!, today, { backfill }).join("\n"));
return 0;
}
const reports = await fetchAndImport(db, {
config: placesConfig,
sourceKey: sourceKey!,
today,
snapshots: defaultSnapshotStore(),
dryRun: args.includes("--dry-run"),
backfill,
gitSha: gitSha(),
});
console.log(JSON.stringify(reports, null, 2));
return reports.some((r) => r.status === "failed") ? 1 : 0;
}
main().then(
(code) => process.exit(code),
(error: unknown) => {
console.error(error);
process.exit(2);
},
);
@@ -119,7 +119,7 @@ describe("placesConfigProblems names what is wrong", () => {
it("a source whose licence is not on the policy", () => {
expect(
broken((c) => {
c.sources[0]!.licence = "CC-BY-NC-4.0";
c.sources.find((s) => s.key === "testland-register")!.licence = "CC-BY-NC-4.0";
}),
).toContain('source "testland-register": licence "CC-BY-NC-4.0" is not on the licence policy');
});
@@ -166,7 +166,7 @@ describe("placesConfigProblems names what is wrong", () => {
it("an identifier pattern that does not compile", () => {
expect(
broken((c) => {
c.identifierSchemes[0]!.pattern = "T[0-9";
c.identifierSchemes.find((s) => s.key === "testland_register")!.pattern = "T[0-9";
}),
).toContain('identifier scheme "testland_register": pattern does not compile');
});
+4 -4
View File
@@ -1,9 +1,9 @@
import type { CountryPackInput } from "../schema";
import { switzerland } from "./switzerland";
/**
* Every country pack, one module per country (`<key>.ts` beside this file).
* Empty until the Canton of Zürich lands in P1: the engine is proven first
* against a made-up country that lives only in tests
* (src/lib/places/__tests__/fixtures).
* The engine is proven against a made-up country that lives only in tests
* (src/lib/places/__tests__/fixtures); a real pack is data like it.
*/
export const COUNTRY_PACKS = [] satisfies readonly CountryPackInput[];
export const COUNTRY_PACKS: readonly CountryPackInput[] = [switzerland];
@@ -0,0 +1,112 @@
import type { TaxModel } from "@/lib/tax-model";
import type { CountryPackInput } from "../schema";
/**
* Swiss income tax on taxable income: the federal tariff, plus the canton's
* basic tariff times the sum of the canton's and the commune's multipliers
* (Steuerfüsse). Church tax is not modelled yet: the register publishes its
* multipliers per denomination, and which parish levies it is not imported,
* so a church component waits for the parishes (§6.1). Nor are fixed per-head
* taxes (Zürich's CHF 24 Personalsteuer): schema version 1 has no fixed amount.
*/
export const switzerlandIncomeTax = {
schemaVersion: 1,
base: "taxable_income",
inputs: ["taxable_income"],
variants: ["single", "married"],
components: [
{ key: "federal", tariff: { level: "nation", metric: "tax.income.tariff" } },
{
key: "cantonal_and_communal",
tariff: { level: "canton", metric: "tax.income.tariff.basic" },
multipliers: [
{ level: "canton", metric: "tax.multiplier" },
{ level: "municipality", metric: "tax.multiplier" },
],
},
],
} as const satisfies TaxModel;
export const switzerland: CountryPackInput = {
key: "switzerland",
names: {
de: "Schweiz",
fr: "Suisse",
it: "Svizzera",
rm: "Svizra",
en: "Switzerland",
},
currency: "CHF",
fiscalYear: { startMonthDay: "01-01" },
defaultLocales: ["de", "fr", "it", "rm"],
slug: { strategy: "official-name", transliterate: true },
levels: [
{
key: "nation",
parent: null,
names: {
en: "Confederation",
de: "Bund",
fr: "Confédération",
it: "Confederazione",
rm: "Confederaziun",
},
},
{
key: "canton",
parent: "nation",
names: { en: "Canton", de: "Kanton", fr: "canton", it: "cantone", rm: "chantun" },
},
{
// Cantons without districts appear in the register with one district of
// their own name, so every commune has a district above it.
key: "district",
parent: "canton",
names: { en: "District", de: "Bezirk", fr: "district", it: "distretto", rm: "district" },
},
{
key: "municipality",
parent: "district",
names: {
en: "Municipality",
de: "Gemeinde",
fr: "commune",
it: "comune",
rm: "vischnanca",
},
},
{
key: "city_district",
parent: "municipality",
coverage: "partial",
names: {
en: "City district",
de: "Stadtkreis",
fr: "arrondissement",
it: "circoscrizione",
},
},
{
key: "statistical_quarter",
parent: "city_district",
coverage: "partial",
names: {
en: "Statistical quarter",
de: "Statistisches Quartier",
fr: "quartier statistique",
it: "quartiere statistico",
},
},
],
identifierSchemes: [
"iso_3166_1",
"bfs_canton",
"bfs_district",
"bfs_municipality",
"bfs_municipality_version",
"zurich_city_district",
"zurich_statistical_quarter",
],
sources: ["bfs-communes-snapshot", "bfs-communes-mutations", "zurich-statistical-quarters"],
taxModel: switzerlandIncomeTax,
};
+57 -1
View File
@@ -5,4 +5,60 @@ import type { IdentifierSchemeInput } from "./schema";
* (§4.3). `reserved` schemes can only be carried by a state authority; the
* database refuses them on a founded or proposed place.
*/
export const IDENTIFIER_SCHEMES = [] satisfies readonly IdentifierSchemeInput[];
export const IDENTIFIER_SCHEMES: readonly IdentifierSchemeInput[] = [
{
key: "iso_3166_1",
label: { en: "ISO 3166-1 country code", de: "Ländercode ISO 3166-1" },
pattern: "[A-Z]{2}",
reserved: true,
},
{
key: "bfs_canton",
label: { en: "FSO canton number", de: "BFS-Kantonsnummer", fr: "numéro OFS du canton" },
pattern: "[1-9]|1[0-9]|2[0-6]",
reserved: true,
},
{
key: "bfs_district",
label: { en: "FSO district number", de: "BFS-Bezirksnummer", fr: "numéro OFS du district" },
pattern: "[1-9][0-9]{2,3}",
reserved: true,
},
{
key: "bfs_municipality",
label: {
en: "FSO municipality number",
de: "BFS-Gemeindenummer",
fr: "numéro OFS de la commune",
it: "numero UST del comune",
},
pattern: "[1-9][0-9]{0,3}",
reserved: true,
},
{
// The register's code for one territorial version of a commune; a new one
// with every merger, territory exchange or change of district.
key: "bfs_municipality_version",
label: {
en: "FSO historical municipality code",
de: "BFS-Historisierungsnummer der Gemeinde",
},
pattern: "[1-9][0-9]{0,5}",
reserved: true,
},
{
key: "zurich_city_district",
label: { en: "City of Zürich district (Kreis)", de: "Stadtkreis Zürich" },
pattern: "[1-9]|1[0-2]",
reserved: true,
},
{
key: "zurich_statistical_quarter",
label: {
en: "City of Zürich statistical quarter",
de: "Statistisches Quartier Stadt Zürich",
},
pattern: "[1-9][0-9]{1,2}",
reserved: true,
},
];
+12
View File
@@ -7,9 +7,21 @@ import type { Licence } from "./schema";
* Decided 2026-09-29 (§13): public domain, CC0 and CC BY. No share-alike source
* (ODbL) before a Register decision admits one, which comes before any
* OpenStreetMap-derived data.
*
* Swiss public bodies publish under terms of use rather than licences, because
* raw data is mostly not protected by copyright there. The `LicenseRef-`
* entries are those terms, each the equivalent of a class the decision admits.
*/
export const LICENCES = [
{ spdx: "CC0-1.0", requiresAttribution: false, shareAlike: false },
{ spdx: "PDDL-1.0", requiresAttribution: false, shareAlike: false },
{ spdx: "CC-BY-4.0", requiresAttribution: true, shareAlike: false },
// opendata.swiss "Open use" (terms_open): free use, citing the source recommended.
// https://opendata.swiss/en/terms-of-use
{ spdx: "LicenseRef-opendata-swiss-open", requiresAttribution: false, shareAlike: false },
// opendata.swiss "Open use. Must provide the source." (terms_by): CC BY's obligation.
{ spdx: "LicenseRef-opendata-swiss-by", requiresAttribution: true, shareAlike: false },
// Swiss official acts, decisions and their official figures (tax tariffs, rates set
// by a canton or commune) are not protected: Art. 5 URG, SR 231.1. Public domain.
{ spdx: "LicenseRef-ch-official-act", requiresAttribution: false, shareAlike: false },
] satisfies readonly Licence[];
+35 -1
View File
@@ -4,4 +4,38 @@ import type { MetricInput } from "./schema";
* The metric catalog: what a fact can measure, its value type, unit and
* plausible band (§4.6). Synced to `place_metrics`, which facts reference.
*/
export const METRICS = [] satisfies readonly MetricInput[];
export const METRICS: readonly MetricInput[] = [
{
key: "tax.income.tariff",
label: {
en: "Income tax tariff",
de: "Einkommenssteuertarif",
fr: "barème de l'impôt sur le revenu",
},
valueType: "tariff",
unit: "currency",
},
{
// A tariff whose amount is then multiplied by the multipliers of several levels.
key: "tax.income.tariff.basic",
label: {
en: "Basic income tax tariff",
de: "Grundtarif Einkommenssteuer (einfache Steuer)",
fr: "barème de base de l'impôt sur le revenu",
},
valueType: "tariff",
unit: "currency",
},
{
key: "tax.multiplier",
label: {
en: "Tax multiplier",
de: "Steuerfuss",
fr: "coefficient d'impôt",
it: "moltiplicatore d'imposta",
},
valueType: "number",
unit: "ratio",
plausible: { min: 0, max: 3 },
},
];
+7
View File
@@ -112,6 +112,13 @@ export const sourceSchema = z.object({
cadence: z.string().regex(/^(\S+\s+){4}\S+$/, "a five-field cron expression"),
/** Key of the adapter module in src/lib/places/adapters. */
adapter: registryKey,
/**
* What the adapter needs to know about the world to map this source: which
* levels and identifier schemes its rows become, which part of the source to
* take. Validated by the adapter's own schema, so an adapter parses a format
* and names no country.
*/
options: z.record(z.string(), z.unknown()).default({}),
packs: z.array(registryKey),
});
export type Source = z.infer<typeof sourceSchema>;
+118 -1
View File
@@ -5,4 +5,121 @@ import type { SourceInput } from "./schema";
* the adapter that reads it (§8.2). Each importer's first task is to confirm
* the access path, format and licence, then record them here.
*/
export const SOURCES = [] satisfies readonly SourceInput[];
export const SOURCES: readonly SourceInput[] = [
{
// Confirmed 2026-09-29: CSV from the register's public API, no key;
// opendata.swiss dataset "historisiertes-gemeindeverzeichnis-der-schweiz",
// terms_open. Every unit valid on the date, with its validity and parent.
key: "bfs-communes-snapshot",
publisher: "Federal Statistical Office (FSO)",
dataset: "Official commune register of Switzerland, historicised: snapshot on a date",
homepage: "https://www.agvchapp.bfs.admin.ch/",
licence: "LicenseRef-opendata-swiss-open",
attribution: {
en: "Federal Statistical Office (FSO), official commune register of Switzerland",
de: "Bundesamt für Statistik (BFS), Amtliches Gemeindeverzeichnis der Schweiz",
fr: "Office fédéral de la statistique (OFS), Répertoire officiel des communes de Suisse",
},
cadence: "0 4 2 * *",
adapter: "bfs_communes_snapshot",
options: {
url: "https://www.agvchapp.bfs.admin.ch/api/communes/snapshot?date={date}",
historyFrom: "2021-01-01",
root: { scheme: "iso_3166_1", value: "CH" },
levels: [
{ registerLevel: 1, level: "canton", scheme: "bfs_canton" },
{ registerLevel: 2, level: "district", scheme: "bfs_district" },
{
registerLevel: 3,
level: "municipality",
scheme: "bfs_municipality",
versionScheme: "bfs_municipality_version",
},
],
// Cantons by FSO number, with the languages of their names in the order
// the register lists a multilingual one ("Bern / Berne").
include: {
"1": ["de"],
"2": ["de", "fr"],
"3": ["de"],
"4": ["de"],
"5": ["de"],
"6": ["de"],
"7": ["de"],
"8": ["de"],
"9": ["de"],
"10": ["fr", "de"],
"11": ["de"],
"12": ["de"],
"13": ["de"],
"14": ["de"],
"15": ["de"],
"16": ["de"],
"17": ["de"],
"18": ["de", "it", "rm"],
"19": ["de"],
"20": ["de"],
"21": ["it"],
"22": ["fr"],
"23": ["fr", "de"],
"24": ["fr"],
"25": ["fr"],
"26": ["fr"],
},
},
packs: ["switzerland"],
},
{
// Confirmed 2026-09-29: same API and terms. Imported after the snapshots,
// so both ends of every merger since `historyFrom` are known places.
key: "bfs-communes-mutations",
publisher: "Federal Statistical Office (FSO)",
dataset: "Official commune register of Switzerland, historicised: mutations",
homepage: "https://www.agvchapp.bfs.admin.ch/",
licence: "LicenseRef-opendata-swiss-open",
attribution: {
en: "Federal Statistical Office (FSO), official commune register of Switzerland",
de: "Bundesamt für Statistik (BFS), Amtliches Gemeindeverzeichnis der Schweiz",
fr: "Office fédéral de la statistique (OFS), Répertoire officiel des communes de Suisse",
},
cadence: "30 4 2 * *",
adapter: "bfs_communes_mutations",
options: {
url: "https://www.agvchapp.bfs.admin.ch/api/communes/mutations?includeTerritoryExchange=false&startPeriod={from}&endPeriod={to}",
historyFrom: "2021-01-01",
scheme: "bfs_municipality",
},
packs: ["switzerland"],
},
{
// Confirmed 2026-09-29: GeoJSON from the city's WFS, no key; dataset
// "geo_statistische_quartiere" on data.stadt-zuerich.ch, CC0. 34 quarters
// in 12 districts, each feature carrying its district.
key: "zurich-statistical-quarters",
publisher: "City of Zürich",
dataset: "Statistische Quartiere",
homepage: "https://data.stadt-zuerich.ch/dataset/geo_statistische_quartiere",
licence: "CC0-1.0",
attribution: {
en: "City of Zürich, statistical quarters",
de: "Stadt Zürich, Statistische Quartiere",
},
cadence: "0 4 15 1 *",
adapter: "geojson_tiers",
options: {
url: "https://www.ogd.stadt-zuerich.ch/wfs/geoportal/Statistische_Quartiere?SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=adm_statistische_quartiere_map&OUTPUTFORMAT=GeoJSON&SRSNAME=EPSG:4326",
parent: { scheme: "bfs_municipality", value: "261" },
locale: "de",
tiers: [
{ level: "city_district", scheme: "zurich_city_district", code: "knr", name: "kname" },
{
level: "statistical_quarter",
scheme: "zurich_statistical_quarter",
code: "qnr",
name: "qname",
},
],
},
packs: ["switzerland"],
},
];
+210
View File
@@ -0,0 +1,210 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { placesConfig } from "@/lib/config/places";
import { ADAPTERS } from "../adapters";
import { isoFromDottedDate, parseCsv } from "../adapters/csv";
import { plannedRetrievals } from "../importer/fetch";
import type { BatchJurisdiction, ImportBatch } from "../importer/batch";
const FIXTURES = join(__dirname, "fixtures", "switzerland");
const fixture = (name: string) => new Uint8Array(readFileSync(join(FIXTURES, name)));
/** A retrieval of a registered source, through its adapter as a run would. */
function mapSource(sourceKey: string, bytes: Uint8Array): ImportBatch {
const source = placesConfig.sources.find((s) => s.key === sourceKey)!;
const adapter = ADAPTERS.get(source.adapter)!;
const decoded = adapter.decode
? adapter.decode(bytes)
: (JSON.parse(new TextDecoder().decode(bytes)) as unknown);
return adapter.map(adapter.schema.parse(decoded), {
source,
pack: placesConfig.packs.find((p) => p.key === source.packs[0]),
options: adapter.options?.parse(source.options),
retrieval: { url: null },
});
}
const byRef = (batch: ImportBatch, scheme: string, value: string): BatchJurisdiction => {
const place = batch.jurisdictions.find((j) => j.ref.scheme === scheme && j.ref.value === value);
if (!place) {
throw new Error(`no ${scheme}:${value} in the batch`);
}
return place;
};
const parentOf = (batch: ImportBatch, scheme: string, value: string) =>
batch.relations.find(
(r) => r.relation === "part_of" && r.from.scheme === scheme && r.from.value === value,
)?.to;
describe("parseCsv", () => {
it("reads quoted fields, doubled quotes, line breaks in quotes, CRLF and a BOM", () => {
const text = '\uFEFFa,b,c\r\n1,"two, too","say ""hi"""\r\n"multi\nline",,x\r\n';
expect(parseCsv(text)).toEqual([
{ a: "1", b: "two, too", c: 'say "hi"' },
{ a: "multi\nline", b: "", c: "x" },
]);
});
it("turns a register's dotted date into an ISO date", () => {
expect(isoFromDottedDate("31.12.2022")).toBe("2022-12-31");
expect(isoFromDottedDate("")).toBeNull();
expect(() => isoFromDottedDate("2022-12-31")).toThrow();
});
});
describe("every registered source", () => {
it("has options its adapter accepts", () => {
for (const source of placesConfig.sources) {
const adapter = ADAPTERS.get(source.adapter);
expect(adapter, `adapter for ${source.key}`).toBeDefined();
expect(() => adapter!.options?.parse(source.options), source.key).not.toThrow();
}
});
});
describe("the FSO commune register snapshot", () => {
const y2021 = mapSource("bfs-communes-snapshot", fixture("communes-2021-01-01.csv"));
const y2026 = mapSource("bfs-communes-snapshot", fixture("communes-2026-09-29.csv"));
it("fetches today's snapshot on schedule, and one a year since its start to backfill", () => {
const today = "https://www.agvchapp.bfs.admin.ch/api/communes/snapshot?date=29-09-2026";
expect(plannedRetrievals(placesConfig, "bfs-communes-snapshot", "2026-09-29")).toEqual([today]);
expect(
plannedRetrievals(placesConfig, "bfs-communes-snapshot", "2026-09-29", { backfill: true }),
).toEqual([
today,
...[2021, 2022, 2023, 2024, 2025, 2026].map(
(year) => `https://www.agvchapp.bfs.admin.ch/api/communes/snapshot?date=01-01-${year}`,
),
today,
]);
});
it("puts the country at the root, named as the pack names it", () => {
const root = byRef(y2026, "iso_3166_1", "CH");
expect(root.levelKey).toBe("nation");
expect(root.names.find((n) => n.locale === "de")).toMatchObject({
name: "Schweiz",
nameType: "self",
});
expect(root.names.find((n) => n.locale === "en")?.nameType).toBe("common");
expect(parentOf(y2026, "bfs_canton", "1")).toEqual({ scheme: "iso_3166_1", value: "CH" });
});
it("keys places by their lasting number, at the level the options give", () => {
expect(byRef(y2026, "bfs_canton", "1").levelKey).toBe("canton");
expect(byRef(y2026, "bfs_district", "112").levelKey).toBe("district");
expect(byRef(y2026, "bfs_municipality", "261")).toMatchObject({
levelKey: "municipality",
names: [expect.objectContaining({ name: "Zürich", locale: "de", nameType: "self" })],
});
expect(parentOf(y2026, "bfs_municipality", "261")).toEqual({
scheme: "bfs_district",
value: "112",
});
});
it("looks a parent up within its level: a historical code repeats across levels", () => {
// Bezirk Horgen and Vionnaz (VS) both carry historical code 10078.
expect(parentOf(y2026, "bfs_municipality", "6158")).toEqual({
scheme: "bfs_district",
value: "2308",
});
expect(parentOf(y2026, "bfs_municipality", "141")).toEqual({
scheme: "bfs_district",
value: "106",
});
});
it("splits a multilingual canton name over the canton's locales", () => {
const bern = byRef(y2026, "bfs_canton", "2");
expect(bern.names.map((n) => [n.locale, n.name])).toEqual([
["de", "Bern"],
["fr", "Berne"],
]);
expect(byRef(y2026, "bfs_municipality", "371").names[0]).toMatchObject({
name: "Biel/Bienne",
locale: "de",
});
});
it("keeps the district a canton without districts is registered with", () => {
expect(parentOf(y2026, "bfs_municipality", "1206")).toEqual({
scheme: "bfs_district",
value: "400",
});
expect(byRef(y2026, "bfs_district", "400").names.map((n) => n.name)).toEqual([
"Kanton Uri",
"Kt. Uri",
]);
});
it("ends a commune the register ended, and dates its territorial version", () => {
expect(byRef(y2021, "bfs_municipality", "21")).toMatchObject({
validTo: "2022-12-31",
identifiers: [
{
scheme: "bfs_municipality_version",
value: "11735",
validFrom: "1872-01-01",
validTo: "2022-12-31",
},
],
});
});
it("keeps a commune's number through a territory exchange", () => {
expect(byRef(y2021, "bfs_municipality", "62")).toMatchObject({ validTo: "2023-12-31" });
expect(byRef(y2026, "bfs_municipality", "62")).toMatchObject({
validTo: null,
identifiers: [expect.objectContaining({ value: "16656", validFrom: "2024-01-01" })],
});
});
});
describe("the FSO commune register mutations", () => {
const batch = mapSource("bfs-communes-mutations", fixture("mutations-2021-2026.csv"));
it("records a merger as the new commune succeeding each old one", () => {
expect(batch.jurisdictions).toEqual([]);
expect(batch.relations.map((r) => [r.from.value, r.relation, r.to.value, r.validFrom])).toEqual(
[
["291", "succeeds", "21", "2023-01-01"],
["291", "succeeds", "32", "2023-01-01"],
["291", "succeeds", "30", "2023-01-01"],
],
);
});
it("plans one retrieval from the day after the first snapshot", () => {
expect(plannedRetrievals(placesConfig, "bfs-communes-mutations", "2026-09-29")).toEqual([
"https://www.agvchapp.bfs.admin.ch/api/communes/mutations?includeTerritoryExchange=false&startPeriod=02-01-2021&endPeriod=29-09-2026",
]);
});
});
describe("the City of Zürich's statistical quarters", () => {
const batch = mapSource("zurich-statistical-quarters", fixture("statistical-quarters.json"));
it("maps each tier of a feature to a place part of the tier above", () => {
expect(byRef(batch, "zurich_statistical_quarter", "74")).toMatchObject({
levelKey: "statistical_quarter",
names: [expect.objectContaining({ name: "Witikon", locale: "de" })],
});
expect(parentOf(batch, "zurich_statistical_quarter", "74")).toEqual({
scheme: "zurich_city_district",
value: "7",
});
expect(parentOf(batch, "zurich_city_district", "7")).toEqual({
scheme: "bfs_municipality",
value: "261",
});
});
it("lists a district once, however many quarters it has", () => {
const districts = batch.jurisdictions.filter((j) => j.levelKey === "city_district");
expect(districts.map((d) => d.ref.value).sort()).toEqual(["1", "7"]);
expect(batch.jurisdictions).toHaveLength(7);
});
});
@@ -0,0 +1,23 @@
HistoricalCode,BfsCode,ValidFrom,ValidTo,Level,Parent,Name,ShortName,Inscription,Radiation,Rec_Type_fr,Rec_Type_de
1,1,12.09.1848,,1,,Zürich,ZH,,,,
2,2,12.09.1848,,1,,Bern / Berne,BE,,,,
4,4,12.09.1848,,1,,Uri,UR,,,,
23,23,12.09.1848,,1,,Valais / Wallis,VS,,,,
10082,102,12.09.1848,,2,1,Bezirk Andelfingen,Andelfingen,100,,,
10081,103,12.09.1848,,2,1,Bezirk Bülach,Bülach,100,,,
10078,106,12.09.1848,,2,1,Bezirk Horgen,Horgen,100,,,
10077,107,12.09.1848,,2,1,Bezirk Meilen,Meilen,100,,,
10228,112,01.01.1990,,2,1,Bezirk Zürich,Zürich,124,,,
10284,242,01.01.2010,,2,2,Verwaltungskreis Biel/Bienne,Biel/Bienne,152,,,
10061,400,12.09.1848,,2,4,Kanton Uri,Kt. Uri,100,,Canton qui n’est pas subdivisé en districts,Kanton ohne Bezirksunterteilung
10013,2308,12.09.1848,,2,23,District de Monthey,Monthey,100,,,
11735,21,01.01.1872,31.12.2022,3,10082,Adlikon,Adlikon,3686,3964,,
13214,30,01.01.1970,31.12.2022,3,10082,Andelfingen,Andelfingen,1029,3964,,
12173,32,01.01.1872,31.12.2022,3,10082,Humlikon,Humlikon,3686,3964,,
12673,62,01.01.1927,31.12.2023,3,10081,Kloten,Kloten,3973,3988,,
10691,141,12.09.1848,,3,10078,Thalwil,Thalwil,,,,
12592,154,12.09.1848,,3,10077,Küsnacht (ZH),Küsnacht (ZH),,,,
13688,261,01.01.1990,,3,10228,Zürich,Zürich,1498,,,
15042,371,01.01.2010,,3,10284,Biel/Bienne,Biel/Bienne,2826,,,
12238,1206,12.09.1848,,3,10061,Erstfeld,Erstfeld,,,,
10078,6158,12.09.1848,,3,10013,Vionnaz,Vionnaz,,,,
1 HistoricalCode BfsCode ValidFrom ValidTo Level Parent Name ShortName Inscription Radiation Rec_Type_fr Rec_Type_de
2 1 1 12.09.1848 1 Zürich ZH
3 2 2 12.09.1848 1 Bern / Berne BE
4 4 4 12.09.1848 1 Uri UR
5 23 23 12.09.1848 1 Valais / Wallis VS
6 10082 102 12.09.1848 2 1 Bezirk Andelfingen Andelfingen 100
7 10081 103 12.09.1848 2 1 Bezirk Bülach Bülach 100
8 10078 106 12.09.1848 2 1 Bezirk Horgen Horgen 100
9 10077 107 12.09.1848 2 1 Bezirk Meilen Meilen 100
10 10228 112 01.01.1990 2 1 Bezirk Zürich Zürich 124
11 10284 242 01.01.2010 2 2 Verwaltungskreis Biel/Bienne Biel/Bienne 152
12 10061 400 12.09.1848 2 4 Kanton Uri Kt. Uri 100 Canton qui n’est pas subdivisé en districts Kanton ohne Bezirksunterteilung
13 10013 2308 12.09.1848 2 23 District de Monthey Monthey 100
14 11735 21 01.01.1872 31.12.2022 3 10082 Adlikon Adlikon 3686 3964
15 13214 30 01.01.1970 31.12.2022 3 10082 Andelfingen Andelfingen 1029 3964
16 12173 32 01.01.1872 31.12.2022 3 10082 Humlikon Humlikon 3686 3964
17 12673 62 01.01.1927 31.12.2023 3 10081 Kloten Kloten 3973 3988
18 10691 141 12.09.1848 3 10078 Thalwil Thalwil
19 12592 154 12.09.1848 3 10077 Küsnacht (ZH) Küsnacht (ZH)
20 13688 261 01.01.1990 3 10228 Zürich Zürich 1498
21 15042 371 01.01.2010 3 10284 Biel/Bienne Biel/Bienne 2826
22 12238 1206 12.09.1848 3 10061 Erstfeld Erstfeld
23 10078 6158 12.09.1848 3 10013 Vionnaz Vionnaz
@@ -0,0 +1,21 @@
HistoricalCode,BfsCode,ValidFrom,ValidTo,Level,Parent,Name,ShortName,Inscription,Radiation,Rec_Type_fr,Rec_Type_de
1,1,12.09.1848,,1,,Zürich,ZH,,,,
2,2,12.09.1848,,1,,Bern / Berne,BE,,,,
4,4,12.09.1848,,1,,Uri,UR,,,,
23,23,12.09.1848,,1,,Valais / Wallis,VS,,,,
10082,102,12.09.1848,,2,1,Bezirk Andelfingen,Andelfingen,100,,,
10081,103,12.09.1848,,2,1,Bezirk Bülach,Bülach,100,,,
10078,106,12.09.1848,,2,1,Bezirk Horgen,Horgen,100,,,
10077,107,12.09.1848,,2,1,Bezirk Meilen,Meilen,100,,,
10228,112,01.01.1990,,2,1,Bezirk Zürich,Zürich,124,,,
10284,242,01.01.2010,,2,2,Verwaltungskreis Biel/Bienne,Biel/Bienne,152,,,
10061,400,12.09.1848,,2,4,Kanton Uri,Kt. Uri,100,,Canton qui n’est pas subdivisé en districts,Kanton ohne Bezirksunterteilung
10013,2308,12.09.1848,,2,23,District de Monthey,Monthey,100,,,
16656,62,01.01.2024,,3,10081,Kloten,Kloten,3988,,,
10691,141,12.09.1848,,3,10078,Thalwil,Thalwil,,,,
12592,154,12.09.1848,,3,10077,Küsnacht (ZH),Küsnacht (ZH),,,,
13688,261,01.01.1990,,3,10228,Zürich,Zürich,1498,,,
16621,291,01.01.2023,,3,10082,Andelfingen,Andelfingen,3964,,,
15042,371,01.01.2010,,3,10284,Biel/Bienne,Biel/Bienne,2826,,,
12238,1206,12.09.1848,,3,10061,Erstfeld,Erstfeld,,,,
10078,6158,12.09.1848,,3,10013,Vionnaz,Vionnaz,,,,
1 HistoricalCode BfsCode ValidFrom ValidTo Level Parent Name ShortName Inscription Radiation Rec_Type_fr Rec_Type_de
2 1 1 12.09.1848 1 Zürich ZH
3 2 2 12.09.1848 1 Bern / Berne BE
4 4 4 12.09.1848 1 Uri UR
5 23 23 12.09.1848 1 Valais / Wallis VS
6 10082 102 12.09.1848 2 1 Bezirk Andelfingen Andelfingen 100
7 10081 103 12.09.1848 2 1 Bezirk Bülach Bülach 100
8 10078 106 12.09.1848 2 1 Bezirk Horgen Horgen 100
9 10077 107 12.09.1848 2 1 Bezirk Meilen Meilen 100
10 10228 112 01.01.1990 2 1 Bezirk Zürich Zürich 124
11 10284 242 01.01.2010 2 2 Verwaltungskreis Biel/Bienne Biel/Bienne 152
12 10061 400 12.09.1848 2 4 Kanton Uri Kt. Uri 100 Canton qui n’est pas subdivisé en districts Kanton ohne Bezirksunterteilung
13 10013 2308 12.09.1848 2 23 District de Monthey Monthey 100
14 16656 62 01.01.2024 3 10081 Kloten Kloten 3988
15 10691 141 12.09.1848 3 10078 Thalwil Thalwil
16 12592 154 12.09.1848 3 10077 Küsnacht (ZH) Küsnacht (ZH)
17 13688 261 01.01.1990 3 10228 Zürich Zürich 1498
18 16621 291 01.01.2023 3 10082 Andelfingen Andelfingen 3964
19 15042 371 01.01.2010 3 10284 Biel/Bienne Biel/Bienne 2826
20 12238 1206 12.09.1848 3 10061 Erstfeld Erstfeld
21 10078 6158 12.09.1848 3 10013 Vionnaz Vionnaz
@@ -0,0 +1,4 @@
MutationNumber,MutationDate,InitialHistoricalCode,InitialCode,InitialName,InitialParentHistoricalCode,InitialParentName,InitialStep,TerminalHistoricalCode,TerminalCode,TerminalName,TerminalParentHistoricalCode,TerminalParentName,TerminalStep
3964,01.01.2023,11735,21,Adlikon,10082,Bezirk Andelfingen,29,16621,291,Andelfingen,10082,Bezirk Andelfingen,26
3964,01.01.2023,12173,32,Humlikon,10082,Bezirk Andelfingen,29,16621,291,Andelfingen,10082,Bezirk Andelfingen,26
3964,01.01.2023,13214,30,Andelfingen,10082,Bezirk Andelfingen,26,16621,291,Andelfingen,10082,Bezirk Andelfingen,26
1 MutationNumber MutationDate InitialHistoricalCode InitialCode InitialName InitialParentHistoricalCode InitialParentName InitialStep TerminalHistoricalCode TerminalCode TerminalName TerminalParentHistoricalCode TerminalParentName TerminalStep
2 3964 01.01.2023 11735 21 Adlikon 10082 Bezirk Andelfingen 29 16621 291 Andelfingen 10082 Bezirk Andelfingen 26
3 3964 01.01.2023 12173 32 Humlikon 10082 Bezirk Andelfingen 29 16621 291 Andelfingen 10082 Bezirk Andelfingen 26
4 3964 01.01.2023 13214 30 Andelfingen 10082 Bezirk Andelfingen 26 16621 291 Andelfingen 10082 Bezirk Andelfingen 26
@@ -0,0 +1,60 @@
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": null,
"properties": {
"objectid": 23,
"knr": 1,
"kname": "Kreis 1",
"qnr": 11,
"qname": "Rathaus"
}
},
{
"type": "Feature",
"geometry": null,
"properties": {
"objectid": 24,
"knr": 7,
"kname": "Kreis 7",
"qnr": 71,
"qname": "Fluntern"
}
},
{
"type": "Feature",
"geometry": null,
"properties": {
"objectid": 10,
"knr": 7,
"kname": "Kreis 7",
"qnr": 72,
"qname": "Hottingen"
}
},
{
"type": "Feature",
"geometry": null,
"properties": {
"objectid": 1,
"knr": 7,
"kname": "Kreis 7",
"qnr": 73,
"qname": "Hirslanden"
}
},
{
"type": "Feature",
"geometry": null,
"properties": {
"objectid": 14,
"knr": 7,
"kname": "Kreis 7",
"qnr": 74,
"qname": "Witikon"
}
}
]
}
@@ -0,0 +1,202 @@
/**
* The Swiss structure through the real importer into a real database, from
* cuts of the actual retrievals (fixtures/switzerland): the FSO commune
* register on 1 January 2021 and on 29 September 2026, its mutations in
* between, and the City of Zürich's statistical quarters. The part of the P1
* acceptance (§11) that needs no tax facts: Witikon resolves up its chain to
* Switzerland, and a merger is a succession, not an edit.
*
* Safe to rerun on the same database: the second pass of every import must
* change nothing, which is also what the scheduled runs rely on.
*
* Runs only with INTEGRATION=1 against a migrated database.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { and, eq, isNull } from "drizzle-orm";
import { describe, expect, it } from "vitest";
import { placesConfig } from "@/lib/config/places";
import { db } from "@/lib/db/client";
import {
jurisdictionIdentifiers,
jurisdictionRelations,
jurisdictions,
} from "@/lib/db/places-schema";
import { loadChain } from "../chain";
import { runImport, type ImportReport } from "../importer/run";
import type { SnapshotStore } from "../importer/snapshots";
import { loadPlacePage } from "../place-page";
import { withTestland } from "./fixtures/testland/config";
const RUN = process.env.INTEGRATION === "1";
const ON = "2026-09-29";
const FIXTURES = join(__dirname, "fixtures", "switzerland");
/** CI's database also holds Testland, and sync refuses a config that drops data. */
const config = withTestland(placesConfig);
const snapshots: SnapshotStore = {
async put(sha) {
return `memory/${sha}`;
},
async get() {
throw new Error("not needed here");
},
};
/** In the order `places:fetch --backfill` then the schedule would import them. */
const RETRIEVALS: [sourceKey: string, file: string][] = [
["bfs-communes-snapshot", "communes-2026-09-29.csv"],
["bfs-communes-snapshot", "communes-2021-01-01.csv"],
["bfs-communes-snapshot", "communes-2026-09-29.csv"],
["bfs-communes-mutations", "mutations-2021-2026.csv"],
["zurich-statistical-quarters", "statistical-quarters.json"],
];
const importFixture = (sourceKey: string, file: string): Promise<ImportReport> =>
runImport(db, {
config,
sourceKey,
retrieval: {
bytes: new Uint8Array(readFileSync(join(FIXTURES, file))),
url: `fixture:${file}`,
retrievedAt: new Date(),
},
snapshots,
});
async function placeId(scheme: string, value: string): Promise<string> {
const [row] = await db
.select({ id: jurisdictionIdentifiers.jurisdictionId })
.from(jurisdictionIdentifiers)
.where(
and(
eq(jurisdictionIdentifiers.scheme, scheme),
eq(jurisdictionIdentifiers.value, value),
isNull(jurisdictionIdentifiers.supersededAt),
),
);
expect(row, `${scheme}:${value}`).toBeDefined();
return row!.id;
}
describe.skipIf(!RUN)("the Swiss structure, imported (P1)", () => {
it("imports the register's snapshots, its mergers and the city's quarters", async () => {
for (const [sourceKey, file] of RETRIEVALS) {
const report = await importFixture(sourceKey, file);
expect(report.problems, file).toEqual([]);
expect(report.status, file).toBe("applied");
}
});
it("changes nothing when a scheduled run brings the same state again", async () => {
// The first two are backfill: a schedule never refetches the past.
for (const [sourceKey, file] of RETRIEVALS.slice(2)) {
const report = await importFixture(sourceKey, file);
expect(report.status, file).toBe("applied");
expect(
Object.entries(report.counts).filter(([, n]) => n > 0),
file,
).toEqual([]);
}
});
it("resolves Witikon up its chain to Switzerland", async () => {
const chain = await loadChain(db, await placeId("zurich_statistical_quarter", "74"), ON);
const ladder = chain
.filter((p) => p.depth !== null)
.sort((a, b) => a.depth! - b.depth!)
.map((p) => [
p.levelKey,
p.names.find((n) => n.nameType === "self" && n.locale === "de")?.name,
]);
expect(ladder).toEqual([
["statistical_quarter", "Witikon"],
["city_district", "Kreis 7"],
["municipality", "Zürich"],
["district", "Bezirk Zürich"],
["canton", "Zürich"],
["nation", "Schweiz"],
]);
});
it("gives Witikon a page at its path, taking no tax", async () => {
const view = await loadPlacePage(
db,
config,
"switzerland/zurich/bezirk-zurich/zurich/kreis-7/witikon",
ON,
"de",
);
expect(view).toMatchObject({
name: "Witikon",
levelName: "Statistisches Quartier",
takesTax: false,
});
expect(view!.partOf.map((p) => p.name)).toEqual([
"Schweiz",
"Zürich",
"Bezirk Zürich",
"Zürich",
"Kreis 7",
]);
});
it("ends the merged communes and links the new one to each", async () => {
const andelfingen = await placeId("bfs_municipality", "291");
const successions = await db
.select({ to: jurisdictionRelations.toId, validFrom: jurisdictionRelations.validFrom })
.from(jurisdictionRelations)
.where(
and(
eq(jurisdictionRelations.fromId, andelfingen),
eq(jurisdictionRelations.relation, "succeeds"),
isNull(jurisdictionRelations.supersededAt),
),
);
const predecessors = await Promise.all(
["21", "32", "30"].map((value) => placeId("bfs_municipality", value)),
);
expect(successions.map((s) => s.to).sort()).toEqual([...predecessors].sort());
expect(new Set(successions.map((s) => s.validFrom))).toEqual(new Set(["2023-01-01"]));
const ended = await db
.select({ validTo: jurisdictions.validTo })
.from(jurisdictions)
.where(eq(jurisdictions.id, predecessors[0]!));
expect(ended[0]!.validTo).toBe("2022-12-31");
});
it("keeps the plain path for the commune that exists now", async () => {
const paths = await db
.select({ slugPath: jurisdictions.slugPath, validTo: jurisdictions.validTo })
.from(jurisdictions)
.where(eq(jurisdictions.id, await placeId("bfs_municipality", "291")));
expect(paths[0]!.slugPath).toBe("switzerland/zurich/bezirk-andelfingen/andelfingen");
const [old] = await db
.select({ slugPath: jurisdictions.slugPath })
.from(jurisdictions)
.where(eq(jurisdictions.id, await placeId("bfs_municipality", "30")));
expect(old!.slugPath).toBe("switzerland/zurich/bezirk-andelfingen/andelfingen-30");
});
it("keeps Kloten current through its territory exchange, under its new version", async () => {
const kloten = await placeId("bfs_municipality", "62");
const [row] = await db
.select({ validTo: jurisdictions.validTo })
.from(jurisdictions)
.where(eq(jurisdictions.id, kloten));
expect(row!.validTo).toBeNull();
const versions = await db
.select({ value: jurisdictionIdentifiers.value })
.from(jurisdictionIdentifiers)
.where(
and(
eq(jurisdictionIdentifiers.jurisdictionId, kloten),
eq(jurisdictionIdentifiers.scheme, "bfs_municipality_version"),
isNull(jurisdictionIdentifiers.supersededAt),
),
);
expect(versions.map((v) => v.value)).toEqual(["16656"]);
});
});
+250
View File
@@ -0,0 +1,250 @@
/**
* The Swiss Federal Statistical Office's historicised commune register, as its
* API serves it: a snapshot of every unit valid on a date (cantons, districts,
* communes), and the list of mutations between two dates. Format only: which
* levels, schemes and cantons the rows become is the source's `options`.
*
* Two traits of the format shape the mapping. A unit's `HistoricalCode` names
* one territorial version and is unique only within its level; `Parent` is the
* code of the version one level up. `BfsCode` is the unit's lasting number,
* kept through renamings and territory exchanges, so it is the key; a merger
* creates a new number, recorded as `succeeds`.
*/
import { z } from "zod";
import type { BatchJurisdiction, BatchName, BatchRelation, ExternalRef } from "../importer/batch";
import { isoFromDottedDate, parseCsv } from "./csv";
import type { Adapter } from "./types";
const dotted = z.string().regex(/^(\d{2}\.\d{2}\.\d{4})?$/, "a DD.MM.YYYY date or empty");
const code = z.string().regex(/^\d+$/, "a number");
const decodeCsv = (bytes: Uint8Array): unknown => parseCsv(new TextDecoder().decode(bytes));
const refSchema = z.object({ scheme: z.string().min(1), value: z.string().min(1) });
const isoDate = z.iso.date();
/** `{date}`-style placeholders as the register's `DD-MM-YYYY`. */
const registerDate = (iso: string): string => iso.split("-").reverse().join("-");
const dayAfter = (iso: string): string =>
new Date(Date.parse(`${iso}T00:00:00Z`) + 86_400_000).toISOString().slice(0, 10);
/** Every anniversary of `from` before `today`. */
function anniversariesBefore(from: string, today: string): string[] {
const [year, monthDay] = [Number(from.slice(0, 4)), from.slice(5)];
const dates: string[] = [];
for (let y = year; `${y}-${monthDay}` < today; y++) {
dates.push(`${y}-${monthDay}`);
}
return dates;
}
const snapshotRow = z.object({
HistoricalCode: code,
BfsCode: code,
ValidFrom: dotted,
ValidTo: dotted,
Level: code,
Parent: z.string().regex(/^\d*$/),
Name: z.string().min(1),
ShortName: z.string(),
});
type SnapshotRow = z.infer<typeof snapshotRow>;
const snapshotOptions = z.object({
/** The register's snapshot endpoint, with `{date}` for the snapshot date. */
url: z.string().includes("{date}"),
/** The first snapshot a backfill loads; one more per year after it. */
historyFrom: isoDate,
/** The country the register covers. Its names are the pack's. */
root: refSchema,
/** Register level → pack level and identifier scheme. The lowest number is the top. */
levels: z
.array(
z.object({
registerLevel: z.number().int().positive(),
level: z.string().min(1),
scheme: z.string().min(1),
/** Keeps each territorial version's `HistoricalCode` under this scheme. */
versionScheme: z.string().min(1).optional(),
}),
)
.min(1),
/**
* Which top-level units to take, by register number, each with the locales
* its names are published in, in the order a multilingual name lists them
* ("Bern / Berne").
*/
include: z.record(code, z.array(z.string().min(2)).min(1)),
});
type SnapshotOptions = z.infer<typeof snapshotOptions>;
export const bfsCommunesSnapshotAdapter: Adapter<SnapshotRow[], SnapshotOptions> = {
key: "bfs_communes_snapshot",
version: "1",
decode: decodeCsv,
schema: z.array(snapshotRow).min(1),
options: snapshotOptions,
// Today's snapshot already carries an end the register has recorded ahead
// (a merger on 1 January is in December's snapshot as ValidTo 31.12).
retrievals: (options, today) => [{ url: options.url.replace("{date}", registerDate(today)) }],
// Communes that ended before today are in no current snapshot: one a year.
// Today's comes first so the places that exist now are the first recorded
// and keep their plain paths; an ended namesake gets its number appended.
// The schedule's own run of today's snapshot then restates the present.
backfill: (options, today) =>
[today, ...anniversariesBefore(options.historyFrom, today)].map((date) => ({
url: options.url.replace("{date}", registerDate(date)),
})),
map: (rows, { pack, options }) => {
if (!pack) {
throw new Error("the commune register maps into a pack; the source names none");
}
const rootLevel = pack.levels.find((l) => l.parent === null && !l.overlaps)!;
const levels = new Map(options.levels.map((l) => [l.registerLevel, l]));
const top = Math.min(...levels.keys());
const at = (level: number, historical: string) => `${level}:${historical}`;
const index = new Map(rows.map((r) => [at(Number(r.Level), r.HistoricalCode), r]));
const parentOf = (row: SnapshotRow) => index.get(at(Number(row.Level) - 1, row.Parent));
const topOf = (row: SnapshotRow): SnapshotRow | undefined => {
let cursor: SnapshotRow | undefined = row;
while (cursor && Number(cursor.Level) > top) {
cursor = parentOf(cursor);
}
return cursor;
};
const refOf = (row: SnapshotRow): ExternalRef => ({
scheme: levels.get(Number(row.Level))!.scheme,
value: row.BfsCode,
});
const jurisdictions: BatchJurisdiction[] = [
{
ref: options.root,
levelKey: rootLevel.key,
identifiers: [],
names: Object.entries(pack.names).map(([locale, name]) => ({
...plainName(name, locale),
nameType: pack.defaultLocales.includes(locale) ? "self" : "common",
})),
validFrom: null,
validTo: null,
},
];
const relations: BatchRelation[] = [];
for (const row of rows) {
const level = levels.get(Number(row.Level));
const locales = options.include[topOf(row)?.BfsCode ?? ""];
if (!level || !locales) {
continue;
}
const isTop = Number(row.Level) === top;
const validTo = isoFromDottedDate(row.ValidTo);
const parts = row.Name.split(" / ");
const names: BatchName[] =
isTop && parts.length === locales.length
? parts.map((part, i) => plainName(part, locales[i]!))
: [plainName(row.Name, locales[0]!)];
if (!isTop && row.ShortName !== "" && row.ShortName !== row.Name) {
names.push({ ...plainName(row.ShortName, locales[0]!), nameType: "common" });
}
jurisdictions.push({
ref: refOf(row),
levelKey: level.level,
identifiers: level.versionScheme
? [
{
scheme: level.versionScheme,
value: row.HistoricalCode,
validFrom: isoFromDottedDate(row.ValidFrom),
validTo,
},
]
: [],
names,
validFrom: null,
validTo,
});
const parent = isTop ? undefined : parentOf(row);
if (!isTop && !parent) {
throw new Error(`${row.Name} (${row.BfsCode}): no parent ${row.Parent} in the snapshot`);
}
relations.push({
from: refOf(row),
to: parent ? refOf(parent) : options.root,
relation: "part_of",
validFrom: null,
validTo,
});
}
return { pack: pack.key, jurisdictions, relations, facts: [] };
},
};
function plainName(name: string, locale: string): BatchName {
return {
locale,
script: null,
name,
nameType: "self",
usedBy: null,
validFrom: null,
validTo: null,
};
}
const mutationRow = z.object({
MutationNumber: code,
MutationDate: dotted.refine((d) => d !== "", "a mutation has a date"),
InitialCode: code,
TerminalCode: code,
});
type MutationRow = z.infer<typeof mutationRow>;
const mutationOptions = z.object({
/** The register's mutations endpoint, with `{from}` and `{to}` for the period. */
url: z.string().includes("{from}").includes("{to}"),
/** The commune snapshots' `historyFrom`: mutations after it link places they hold. */
historyFrom: isoDate,
/** The scheme the register's commune numbers are recorded under. */
scheme: z.string().min(1),
});
type MutationOptions = z.infer<typeof mutationOptions>;
export const bfsCommunesMutationsAdapter: Adapter<MutationRow[], MutationOptions> = {
key: "bfs_communes_mutations",
version: "1",
decode: decodeCsv,
schema: z.array(mutationRow),
options: mutationOptions,
// A merger dated on the first snapshot's day ended its communes the day
// before, so neither end of it is a place the backfill knows.
retrievals: (options, today) => [
{
url: options.url
.replace("{from}", registerDate(dayAfter(options.historyFrom)))
.replace("{to}", registerDate(today)),
},
],
map: (rows, { pack, options }) => {
if (!pack) {
throw new Error("the mutation register maps into a pack; the source names none");
}
const seen = new Set<string>();
const relations: BatchRelation[] = [];
for (const row of rows) {
const key = `${row.TerminalCode}>${row.InitialCode}`;
// A commune that keeps its number (renamed, territory exchanged) succeeds nobody.
if (row.InitialCode === row.TerminalCode || seen.has(key)) {
continue;
}
seen.add(key);
relations.push({
from: { scheme: options.scheme, value: row.TerminalCode },
to: { scheme: options.scheme, value: row.InitialCode },
relation: "succeeds",
validFrom: isoFromDottedDate(row.MutationDate),
validTo: null,
});
}
return { pack: pack.key, jurisdictions: [], relations, facts: [] };
},
};
+67
View File
@@ -0,0 +1,67 @@
/**
* RFC 4180 CSV to records keyed by the header row: quoted fields, doubled
* quotes, commas and line breaks inside quotes, CRLF or LF, a leading BOM.
* Official registers publish CSV; nothing here knows which.
*/
export function parseCsv(text: string): Record<string, string>[] {
const rows = csvRows(text.replace(/^\uFEFF/, ""));
const header = rows.shift();
if (!header) {
return [];
}
return rows
.filter((row) => !(row.length === 1 && row[0] === ""))
.map((row) => Object.fromEntries(header.map((name, i) => [name, row[i] ?? ""])));
}
function csvRows(text: string): string[][] {
const rows: string[][] = [];
let row: string[] = [];
let field = "";
let quoted = false;
for (let i = 0; i < text.length; i++) {
const char = text[i]!;
if (quoted) {
if (char === '"' && text[i + 1] === '"') {
field += '"';
i++;
} else if (char === '"') {
quoted = false;
} else {
field += char;
}
} else if (char === '"') {
quoted = true;
} else if (char === ",") {
row.push(field);
field = "";
} else if (char === "\n" || char === "\r") {
if (char === "\r" && text[i + 1] === "\n") {
i++;
}
row.push(field);
rows.push(row);
row = [];
field = "";
} else {
field += char;
}
}
if (field !== "" || row.length > 0) {
row.push(field);
rows.push(row);
}
return rows;
}
/** A register's `DD.MM.YYYY` as an ISO date; empty stays null. */
export function isoFromDottedDate(value: string): string | null {
if (value === "") {
return null;
}
const match = /^(\d{2})\.(\d{2})\.(\d{4})$/.exec(value);
if (!match) {
throw new Error(`"${value}" is not a DD.MM.YYYY date`);
}
return `${match[3]}-${match[2]}-${match[1]}`;
}
+108
View File
@@ -0,0 +1,108 @@
/**
* Subdivisions published as GeoJSON features, one feature per smallest unit,
* each carrying the codes and names of every tier above it (a city's quarters
* with their district on each quarter). Format only: which properties hold
* which tier, and the place the top tier belongs to, are the source's
* `options`. Geometry is not read yet; areas come with the map.
*/
import { z } from "zod";
import type { BatchJurisdiction, BatchRelation, ExternalRef } from "../importer/batch";
import type { Adapter } from "./types";
const property = z.union([z.string(), z.number()]).nullable();
const featureCollection = z.object({
type: z.literal("FeatureCollection"),
features: z
.array(z.object({ type: z.literal("Feature"), properties: z.record(z.string(), property) }))
.min(1),
});
type FeatureCollection = z.infer<typeof featureCollection>;
const tiersOptions = z.object({
/** Where to fetch the collection; absent when it is handed in as a file. */
url: z.url().optional(),
/** The place the top tier is part of. */
parent: z.object({ scheme: z.string().min(1), value: z.string().min(1) }),
/** The locale the names are published in. */
locale: z.string().min(2),
/** From the top tier down: the level it becomes, its scheme, and the properties holding code and name. */
tiers: z
.array(
z.object({
level: z.string().min(1),
scheme: z.string().min(1),
code: z.string().min(1),
name: z.string().min(1),
}),
)
.min(1),
});
type TiersOptions = z.infer<typeof tiersOptions>;
export const geojsonTiersAdapter: Adapter<FeatureCollection, TiersOptions> = {
key: "geojson_tiers",
version: "1",
schema: featureCollection,
options: tiersOptions,
retrievals: (options) => (options.url ? [{ url: options.url }] : []),
map: (collection, { pack, options }) => {
if (!pack) {
throw new Error("subdivisions map into a pack; the source names none");
}
const places = new Map<string, BatchJurisdiction>();
const relations = new Map<string, BatchRelation>();
for (const [i, feature] of collection.features.entries()) {
let above: ExternalRef = options.parent;
for (const tier of options.tiers) {
const code = feature.properties[tier.code];
const name = feature.properties[tier.name];
if (code === null || code === undefined || typeof name !== "string" || name === "") {
throw new Error(`feature ${i}: no ${tier.code} / ${tier.name} for ${tier.level}`);
}
const ref = { scheme: tier.scheme, value: String(code) };
const key = `${ref.scheme}:${ref.value}`;
if (!places.has(key)) {
places.set(key, {
ref,
levelKey: tier.level,
identifiers: [],
names: [
{
locale: options.locale,
script: null,
name,
nameType: "self",
usedBy: null,
validFrom: null,
validTo: null,
},
],
validFrom: null,
validTo: null,
});
}
const relation = relations.get(key);
if (
relation &&
`${relation.to.scheme}:${relation.to.value}` !== `${above.scheme}:${above.value}`
) {
throw new Error(`${key} is listed under two different parents`);
}
relations.set(key, {
from: ref,
to: above,
relation: "part_of",
validFrom: null,
validTo: null,
});
above = ref;
}
}
return {
pack: pack.key,
jurisdictions: [...places.values()],
relations: [...relations.values()],
facts: [],
};
},
};
+9 -2
View File
@@ -1,9 +1,16 @@
import { bfsCommunesMutationsAdapter, bfsCommunesSnapshotAdapter } from "./bfs-communes";
import { fixtureAdapter } from "./fixture";
import { geojsonTiersAdapter } from "./geojson-tiers";
import type { Adapter } from "./types";
/** Every adapter, by the key sources name in the registry. */
export const ADAPTERS: ReadonlyMap<string, Adapter> = new Map(
[fixtureAdapter as Adapter].map((adapter) => [adapter.key, adapter]),
[
fixtureAdapter,
bfsCommunesSnapshotAdapter,
bfsCommunesMutationsAdapter,
geojsonTiersAdapter,
].map((adapter) => [adapter.key, adapter as Adapter]),
);
export type { Adapter } from "./types";
export type { Adapter, RetrievalRequest } from "./types";
+36 -4
View File
@@ -2,12 +2,30 @@ import type { z } from "zod";
import type { CountryPack, Source } from "@/lib/config/places/schema";
import type { ImportBatch } from "../importer/batch";
/** One request the framework makes to fetch a source (design §8.3, step 1). */
export interface RetrievalRequest {
url: string;
}
export interface MapContext<Options> {
source: Source;
pack: CountryPack | undefined;
/** `source.options`, parsed with the adapter's `options` schema. */
options: Options;
/** Where these bytes came from, when known. */
retrieval: { url: string | null };
}
/**
* One adapter per source format (design §8.3). An adapter only parses and
* maps; the framework owns snapshots, diffing, applying and invariants, so no
* adapter reimplements them.
* maps; the framework owns fetching, snapshots, diffing, applying and
* invariants, so no adapter reimplements them.
*
* An adapter knows its format (column names, codes) and nothing about the
* world: which levels, schemes and places its rows become is the source's
* `options`, in config.
*/
export interface Adapter<Parsed = unknown> {
export interface Adapter<Parsed = unknown, Options = unknown> {
/** The `adapter` key sources name in the registry. */
key: string;
/** Recorded on every `sources` row it produces. Bump when the mapping changes. */
@@ -16,5 +34,19 @@ export interface Adapter<Parsed = unknown> {
decode?: (bytes: Uint8Array) => unknown;
/** A format change fails here, loudly. */
schema: z.ZodType<Parsed>;
map: (parsed: Parsed, context: { source: Source; pack: CountryPack | undefined }) => ImportBatch;
/** Checks `source.options`; absent when the adapter takes none. */
options?: z.ZodType<Options>;
/**
* What to fetch, in the order to import it, for a scheduled run on `today`
* (ISO date). Absent: the source is handed in as a file. Rerunning it must
* change nothing when the source has not changed.
*/
retrievals?: (options: Options, today: string) => RetrievalRequest[];
/**
* The history to load once, before the first scheduled run: older states of
* the source, oldest first. Not refetched by schedule, since importing an
* older state after a newer one would restate the past as current.
*/
backfill?: (options: Options, today: string) => RetrievalRequest[];
map: (parsed: Parsed, context: MapContext<Options>) => ImportBatch;
}
+90
View File
@@ -0,0 +1,90 @@
/**
* Step 1 of the framework for a scheduled run (design §8.3): ask the source's
* adapter what to retrieve for today, fetch each in turn and import it. The
* retrievals are imported in the adapter's order and the first failure stops
* the run, because later retrievals may build on earlier ones (a register's
* yearly snapshots, then its mergers).
*/
import type { PlacesConfig } from "@/lib/config/places/schema";
import type { Database } from "@/lib/db/client";
import { ADAPTERS, type Adapter } from "../adapters";
import { runImport, type ImportReport } from "./run";
import type { SnapshotStore } from "./snapshots";
export interface FetchOptions {
config: PlacesConfig;
sourceKey: string;
/** ISO date the retrievals are planned for. */
today: string;
snapshots: SnapshotStore;
dryRun?: boolean;
gitSha?: string | null;
/** Load the source's history first (adapter `backfill`), then today's state. */
backfill?: boolean;
adapters?: ReadonlyMap<string, Adapter>;
fetchImpl?: typeof fetch;
}
const FETCH_TIMEOUT_MS = 120_000;
/** The URLs a run of the source fetches, in import order. */
export function plannedRetrievals(
config: PlacesConfig,
sourceKey: string,
today: string,
{
backfill = false,
adapters = ADAPTERS,
}: { backfill?: boolean; adapters?: ReadonlyMap<string, Adapter> } = {},
): string[] {
const source = config.sources.find((s) => s.key === sourceKey);
if (!source) {
throw new Error(`source "${sourceKey}" is not in the source registry`);
}
const adapter = adapters.get(source.adapter);
if (!adapter) {
throw new Error(`no adapter "${source.adapter}" for source "${sourceKey}"`);
}
if (!adapter.retrievals) {
throw new Error(`adapter "${adapter.key}" is handed files; it does not fetch`);
}
const options = adapter.options ? adapter.options.parse(source.options) : undefined;
return [
...(backfill ? (adapter.backfill?.(options, today) ?? []) : []),
...adapter.retrievals(options, today),
].map((r) => r.url);
}
export async function fetchAndImport(db: Database, options: FetchOptions): Promise<ImportReport[]> {
const adapters = options.adapters ?? ADAPTERS;
const fetchImpl = options.fetchImpl ?? fetch;
const reports: ImportReport[] = [];
const urls = plannedRetrievals(options.config, options.sourceKey, options.today, {
backfill: options.backfill,
adapters,
});
for (const url of urls) {
const response = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (!response.ok) {
throw new Error(`${url}: HTTP ${response.status}`);
}
const report = await runImport(db, {
config: options.config,
sourceKey: options.sourceKey,
retrieval: {
bytes: new Uint8Array(await response.arrayBuffer()),
url,
retrievedAt: new Date(),
},
snapshots: options.snapshots,
dryRun: options.dryRun,
gitSha: options.gitSha,
adapters,
});
reports.push(report);
if (report.status === "failed") {
break;
}
}
return reports;
}
+29 -3
View File
@@ -168,8 +168,25 @@ export async function runImport(db: Database, options: ImportOptions): Promise<I
.map((issue) => `format: ${issue.path.join(".") || "(root)"}: ${issue.message}`),
);
}
const adapterOptions = adapter.options
? adapter.options.safeParse(source.options)
: { success: true as const, data: undefined };
if (!adapterOptions.success) {
throw new RunFailed(
adapterOptions.error.issues.map(
(issue) => `source options: ${issue.path.join(".") || "(root)"}: ${issue.message}`,
),
);
}
const pack = config.packs.find((p) => p.key === source.packs[0]);
const batch = importBatchSchema.parse(adapter.map(parsed.data, { source, pack }));
const batch = importBatchSchema.parse(
adapter.map(parsed.data, {
source,
pack,
options: adapterOptions.data,
retrieval: { url: retrieval.url },
}),
);
const check = checkBatch(batch, config, sourceKey);
report.quarantined = check.quarantined.map(({ fact, reason }) => ({
fact: `${refKey(fact.jurisdiction)} ${fact.metricKey} ${fact.validFrom}`,
@@ -316,9 +333,11 @@ async function applyBatch(
};
// --- Places: new ones get a row, a path and their identifier. ---
// The current parent, or for a place that has ended, the last one it had.
const currentParent = new Map(
batch.relations
.filter((r) => r.relation === "part_of" && r.validTo === null)
.filter((r) => r.relation === "part_of")
.sort((a, b) => (a.validTo ?? "9999").localeCompare(b.validTo ?? "9999"))
.map((r) => [refKey(r.from), r.to]),
);
const byRef = new Map(batch.jurisdictions.map((j) => [refKey(j.ref), j]));
@@ -550,6 +569,13 @@ async function applyBatch(
}
// --- Relations: end or supersede first, so "one current parent" holds throughout. ---
// A source may state relations of places it does not list (a register of mergers).
const relationScope = [
...new Set([
...placeIds,
...batch.relations.map((r) => idOf(r.from, `relation ${r.relation}`)),
]),
];
const currentRelations = await tx
.select({
id: jurisdictionRelations.id,
@@ -563,7 +589,7 @@ async function applyBatch(
.innerJoin(sources, eq(sources.id, jurisdictionRelations.sourceId))
.where(
and(
inArray(jurisdictionRelations.fromId, placeIds),
inArray(jurisdictionRelations.fromId, relationScope),
eq(sources.sourceKey, source.key),
isNull(jurisdictionRelations.supersededAt),
),