@mailwoman/resolver-wof-sqlite 12.0.0 → 12.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/lib/address/keys/build.ts +35 -0
  2. package/lib/address/keys/lookup.ts +204 -6
  3. package/lib/address/keys/point-lookup.ts +4 -0
  4. package/lib/address/keys/schema.ts +37 -0
  5. package/lib/address/number-forms.ts +32 -13
  6. package/lib/address/point/interpolation.ts +23 -6
  7. package/lib/address/point/schema.ts +120 -2
  8. package/lib/address/point/scope-search.ts +179 -0
  9. package/lib/address/point.ts +225 -28
  10. package/lib/build/candidate.ts +36 -9
  11. package/lib/candidate/ancestors/sidecar.ts +73 -4
  12. package/lib/candidate/del1.ts +218 -0
  13. package/lib/candidate/lookup.ts +159 -100
  14. package/lib/candidate/schema.ts +14 -2
  15. package/lib/fst/binary-matcher.ts +9 -1
  16. package/lib/fst/builder.ts +7 -0
  17. package/lib/fst/del1-sidecar.ts +782 -0
  18. package/lib/fst/deserialize-web.ts +14 -2
  19. package/lib/fst/matcher.ts +7 -1
  20. package/lib/fst/types.ts +8 -0
  21. package/lib/fst.ts +1 -0
  22. package/lib/index.ts +22 -2
  23. package/lib/labels/street/canonical.ts +333 -0
  24. package/lib/labels/street/centroid/schema.ts +23 -1
  25. package/lib/labels/street/interpolation.ts +32 -6
  26. package/lib/labels/street/morphology/fst/builder.ts +13 -0
  27. package/lib/labels/street/morphology/fst/loader.ts +32 -2
  28. package/lib/labels/street/normalize.ts +32 -3
  29. package/lib/labels/street.ts +1 -0
  30. package/lib/lookup/types.ts +0 -6
  31. package/lib/poi/lookup.ts +4 -0
  32. package/lib/schema/overture-match.ts +2 -1
  33. package/out/address/keys/build.d.ts.map +1 -1
  34. package/out/address/keys/build.js +28 -1
  35. package/out/address/keys/build.js.map +1 -1
  36. package/out/address/keys/lookup.d.ts +17 -0
  37. package/out/address/keys/lookup.d.ts.map +1 -1
  38. package/out/address/keys/lookup.js +119 -6
  39. package/out/address/keys/lookup.js.map +1 -1
  40. package/out/address/keys/point-lookup.d.ts.map +1 -1
  41. package/out/address/keys/point-lookup.js +4 -0
  42. package/out/address/keys/point-lookup.js.map +1 -1
  43. package/out/address/keys/schema.d.ts +21 -0
  44. package/out/address/keys/schema.d.ts.map +1 -1
  45. package/out/address/keys/schema.js +18 -0
  46. package/out/address/keys/schema.js.map +1 -1
  47. package/out/address/number-forms.d.ts +10 -1
  48. package/out/address/number-forms.d.ts.map +1 -1
  49. package/out/address/number-forms.js +20 -11
  50. package/out/address/number-forms.js.map +1 -1
  51. package/out/address/point/interpolation.d.ts.map +1 -1
  52. package/out/address/point/interpolation.js +15 -5
  53. package/out/address/point/interpolation.js.map +1 -1
  54. package/out/address/point/schema.d.ts +43 -2
  55. package/out/address/point/schema.d.ts.map +1 -1
  56. package/out/address/point/schema.js +73 -0
  57. package/out/address/point/schema.js.map +1 -1
  58. package/out/address/point/scope-search.d.ts +77 -0
  59. package/out/address/point/scope-search.d.ts.map +1 -0
  60. package/out/address/point/scope-search.js +107 -0
  61. package/out/address/point/scope-search.js.map +1 -0
  62. package/out/address/point.d.ts +12 -0
  63. package/out/address/point.d.ts.map +1 -1
  64. package/out/address/point.js +143 -26
  65. package/out/address/point.js.map +1 -1
  66. package/out/build/candidate.d.ts +8 -0
  67. package/out/build/candidate.d.ts.map +1 -1
  68. package/out/build/candidate.js +17 -7
  69. package/out/build/candidate.js.map +1 -1
  70. package/out/candidate/ancestors/sidecar.d.ts +7 -3
  71. package/out/candidate/ancestors/sidecar.d.ts.map +1 -1
  72. package/out/candidate/ancestors/sidecar.js +56 -4
  73. package/out/candidate/ancestors/sidecar.js.map +1 -1
  74. package/out/candidate/del1.d.ts +61 -0
  75. package/out/candidate/del1.d.ts.map +1 -0
  76. package/out/candidate/del1.js +158 -0
  77. package/out/candidate/del1.js.map +1 -0
  78. package/out/candidate/lookup.d.ts +2 -14
  79. package/out/candidate/lookup.d.ts.map +1 -1
  80. package/out/candidate/lookup.js +122 -84
  81. package/out/candidate/lookup.js.map +1 -1
  82. package/out/candidate/schema.d.ts +8 -2
  83. package/out/candidate/schema.d.ts.map +1 -1
  84. package/out/candidate/schema.js +8 -2
  85. package/out/candidate/schema.js.map +1 -1
  86. package/out/fst/binary-matcher.d.ts +7 -1
  87. package/out/fst/binary-matcher.d.ts.map +1 -1
  88. package/out/fst/binary-matcher.js +7 -1
  89. package/out/fst/binary-matcher.js.map +1 -1
  90. package/out/fst/builder.d.ts +2 -0
  91. package/out/fst/builder.d.ts.map +1 -1
  92. package/out/fst/builder.js +5 -0
  93. package/out/fst/builder.js.map +1 -1
  94. package/out/fst/del1-sidecar.d.ts +158 -0
  95. package/out/fst/del1-sidecar.d.ts.map +1 -0
  96. package/out/fst/del1-sidecar.js +581 -0
  97. package/out/fst/del1-sidecar.js.map +1 -0
  98. package/out/fst/deserialize-web.d.ts +3 -1
  99. package/out/fst/deserialize-web.d.ts.map +1 -1
  100. package/out/fst/deserialize-web.js +9 -2
  101. package/out/fst/deserialize-web.js.map +1 -1
  102. package/out/fst/matcher.d.ts +6 -1
  103. package/out/fst/matcher.d.ts.map +1 -1
  104. package/out/fst/matcher.js +6 -1
  105. package/out/fst/matcher.js.map +1 -1
  106. package/out/fst/types.d.ts +7 -0
  107. package/out/fst/types.d.ts.map +1 -1
  108. package/out/fst.d.ts +1 -0
  109. package/out/fst.d.ts.map +1 -1
  110. package/out/fst.js +1 -0
  111. package/out/fst.js.map +1 -1
  112. package/out/index.d.ts +4 -3
  113. package/out/index.d.ts.map +1 -1
  114. package/out/index.js +3 -2
  115. package/out/index.js.map +1 -1
  116. package/out/labels/street/canonical.d.ts +68 -0
  117. package/out/labels/street/canonical.d.ts.map +1 -0
  118. package/out/labels/street/canonical.js +234 -0
  119. package/out/labels/street/canonical.js.map +1 -0
  120. package/out/labels/street/centroid/schema.d.ts +10 -1
  121. package/out/labels/street/centroid/schema.d.ts.map +1 -1
  122. package/out/labels/street/centroid/schema.js +12 -0
  123. package/out/labels/street/centroid/schema.js.map +1 -1
  124. package/out/labels/street/interpolation.d.ts +9 -1
  125. package/out/labels/street/interpolation.d.ts.map +1 -1
  126. package/out/labels/street/interpolation.js +8 -5
  127. package/out/labels/street/interpolation.js.map +1 -1
  128. package/out/labels/street/morphology/fst/builder.d.ts +8 -0
  129. package/out/labels/street/morphology/fst/builder.d.ts.map +1 -1
  130. package/out/labels/street/morphology/fst/builder.js +5 -0
  131. package/out/labels/street/morphology/fst/builder.js.map +1 -1
  132. package/out/labels/street/morphology/fst/loader.d.ts +12 -0
  133. package/out/labels/street/morphology/fst/loader.d.ts.map +1 -1
  134. package/out/labels/street/morphology/fst/loader.js +18 -2
  135. package/out/labels/street/morphology/fst/loader.js.map +1 -1
  136. package/out/labels/street/normalize.d.ts +8 -0
  137. package/out/labels/street/normalize.d.ts.map +1 -1
  138. package/out/labels/street/normalize.js +23 -3
  139. package/out/labels/street/normalize.js.map +1 -1
  140. package/out/labels/street.d.ts +1 -0
  141. package/out/labels/street.d.ts.map +1 -1
  142. package/out/labels/street.js +1 -0
  143. package/out/labels/street.js.map +1 -1
  144. package/out/lookup/types.d.ts +0 -5
  145. package/out/lookup/types.d.ts.map +1 -1
  146. package/out/poi/lookup.d.ts +4 -0
  147. package/out/poi/lookup.d.ts.map +1 -1
  148. package/out/poi/lookup.js.map +1 -1
  149. package/out/schema/overture-match.d.ts +2 -1
  150. package/out/schema/overture-match.d.ts.map +1 -1
  151. package/out/schema/overture-match.js.map +1 -1
  152. package/package.json +12 -12
@@ -17,6 +17,7 @@ import { stageBareAdminNames } from "#candidate/bare-admin-names"
17
17
  import { createCapitalTable } from "#candidate/capital-schema"
18
18
  import type { CapitalPoint } from "#candidate/capitals"
19
19
  import { stageCountryDisplayNames } from "#candidate/country-display-names"
20
+ import { createCandidateDel1 } from "#candidate/del1"
20
21
  import { stageExtractRows } from "#candidate/extract-rows"
21
22
  import { createCandidateFTS } from "#candidate/fts"
22
23
  import { IMPORTANCE_JOIN_RADIUS_KM, loadImportanceIndex } from "#candidate/importance"
@@ -289,6 +290,16 @@ export interface BuildCandidateResult {
289
290
  * Count of rows written to `candidate_sitelinks`, or null when no sitelinks source was supplied.
290
291
  */
291
292
  sitelinks: number | null
293
+
294
+ /**
295
+ * Count of distinct prominent `name_key` values indexed in `candidate_del1`.
296
+ */
297
+ del1Keys: number
298
+
299
+ /**
300
+ * Count of `(del_key, name_key)` rows written to `candidate_del1`.
301
+ */
302
+ del1Rows: number
292
303
  }
293
304
 
294
305
  /**
@@ -726,15 +737,7 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
726
737
  progress("key-fold", `${fold}: ${rekeyed.toLocaleString()} rows rekeyed, ${merged.toLocaleString()} merged`)
727
738
  }
728
739
 
729
- progress("fts", "building FTS5-trigram fuzzy index")
730
- createCandidateFTS(kdb)
731
-
732
- const postcodePlacetypeID = ptcodes.get(POSTCODE_PLACETYPE)
733
-
734
- if (postcodePlacetypeID != null) {
735
- progress("postcode-index", `indexing postcode places by spr_id (placetype id ${postcodePlacetypeID})`)
736
- await createCandidatePostcodePlaceIndex(kdb, postcodePlacetypeID)
737
- }
740
+ const del1 = await buildCandidateIndexes(kdb, ptcodes, progress)
738
741
 
739
742
  kdb.exec("PRAGMA page_size=8192")
740
743
  kdb.exec("VACUUM")
@@ -767,9 +770,33 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
767
770
  outcomes,
768
771
  concordances: nConcordances,
769
772
  sitelinks: nSitelinks,
773
+ del1Keys: del1.keys,
774
+ del1Rows: del1.rows,
770
775
  }
771
776
  }
772
777
 
778
+ async function buildCandidateIndexes(
779
+ kdb: DatabaseClient<CandidateDatabase>,
780
+ ptcodes: ReadonlyMap<string, number>,
781
+ progress: (stage: string, detail: string) => void
782
+ ): Promise<{ keys: number; rows: number }> {
783
+ progress("fts", "building FTS5-trigram fuzzy index")
784
+ createCandidateFTS(kdb)
785
+
786
+ progress("del1", "building prominent-place SymSpell 1-delete fuzzy index")
787
+ const del1 = await createCandidateDel1(kdb)
788
+ progress("del1", `${del1.keys.toLocaleString()} keys, ${del1.rows.toLocaleString()} rows`)
789
+
790
+ const postcodePlacetypeID = ptcodes.get(POSTCODE_PLACETYPE)
791
+
792
+ if (postcodePlacetypeID != null) {
793
+ progress("postcode-index", `indexing postcode places by spr_id (placetype id ${postcodePlacetypeID})`)
794
+ await createCandidatePostcodePlaceIndex(kdb, postcodePlacetypeID)
795
+ }
796
+
797
+ return del1
798
+ }
799
+
773
800
  async function stageCandidateConcordancesAndSitelinks(
774
801
  src: DatabaseClient<WOFDatabase>,
775
802
  kdb: DatabaseClient<CandidateDatabase>,
@@ -21,10 +21,38 @@ import type { PlaceAttrs } from "#candidate/place-attrs"
21
21
  import type { CandidateDatabase } from "#candidate/schema"
22
22
  import type { WOFDatabase } from "#schema"
23
23
 
24
+ interface CountryLookup {
25
+ overture: Map<number, number | null>
26
+ rest: Map<number, number | null>
27
+ }
28
+
24
29
  /**
25
- * Build the ancestors sidecar (closure rows plus interval labels) from the source
26
- * `ancestors` table, excluding self rows and placetypes outside the containment ladder.
27
- * an edge to a parent with no current `spr` row is dropped and counted.
30
+ * Indexes each country code that has a unique current `country` row per part.
31
+ *
32
+ * A code shared by multiple `country` rows in a part (such as `XX`) maps to null.
33
+ */
34
+ function indexUniqueCountries(attrs: ReadonlyMap<number, PlaceAttrs>, countryPtID: number): CountryLookup {
35
+ const overture = new Map<number, number | null>()
36
+ const rest = new Map<number, number | null>()
37
+
38
+ for (const [sid, place] of attrs) {
39
+ if (place.ptid !== countryPtID) continue
40
+
41
+ const target = isOverturePartID(sid) ? overture : rest
42
+ target.set(place.cid, target.has(place.cid) ? null : sid)
43
+ }
44
+
45
+ return { overture, rest }
46
+ }
47
+
48
+ /**
49
+ * Build the ancestors sidecar (closure rows and interval labels) from `ancestors`.
50
+ *
51
+ * Excludes self rows and placetypes outside the containment ladder.
52
+ * An edge to a parent with no current `spr` row is dropped and counted.
53
+ *
54
+ * WOF files territories such as Puerto Rico under `dependency` with no `spr` row.
55
+ * A place with a `dependency` edge links to its part's unique `country` row.
28
56
  */
29
57
  export async function buildAncestorsSidecar(ctx: {
30
58
  src: DatabaseClient<WOFDatabase>
@@ -39,6 +67,23 @@ export async function buildAncestorsSidecar(ctx: {
39
67
  await createCandidateAncestorTable(ctx.out)
40
68
  await createCandidateIntervalTable(ctx.out)
41
69
 
70
+ const countryPtID = ptID("country")
71
+ const countriesByPart = indexUniqueCountries(attrs, countryPtID)
72
+
73
+ const resolveDependencyCountry = (id: number): number | null => {
74
+ const child = attrs.get(id)
75
+
76
+ if (!child || child.ptid === countryPtID) return null
77
+
78
+ const countryID = isOverturePartID(id)
79
+ ? countriesByPart.overture.has(child.cid)
80
+ ? countriesByPart.overture.get(child.cid)
81
+ : countriesByPart.rest.get(child.cid)
82
+ : countriesByPart.rest.get(child.cid)
83
+
84
+ return typeof countryID === "number" && countryID !== id ? countryID : null
85
+ }
86
+
42
87
  const insAncestor = out.prepare(
43
88
  `INSERT INTO ${CANDIDATE_ANCESTOR_TABLE} VALUES (${CANDIDATE_ANCESTOR_COLUMNS.map(() => "?").join(", ")})`
44
89
  )
@@ -51,14 +96,28 @@ export async function buildAncestorsSidecar(ctx: {
51
96
 
52
97
  let ancestorRows = 0
53
98
  let ancestorPlaces = 0
99
+ let dependencyFallbacks = 0
54
100
  let droppedParents = 0
55
101
 
56
102
  // The stream is grouped by child id, so each flush owns one place.
57
103
  let childID = -1
58
104
  let edges: Array<{ aid: number; apt: string }> = []
105
+ let hasDependency = false
59
106
 
60
107
  const flush = (): void => {
61
- if (childID < 0 || !edges.length) return
108
+ if (childID < 0) return
109
+
110
+ if (hasDependency && !edges.some((edge) => edge.apt === "country")) {
111
+ const countryID = resolveDependencyCountry(childID)
112
+
113
+ if (typeof countryID === "number") {
114
+ edges.push({ aid: countryID, apt: "country" })
115
+
116
+ dependencyFallbacks++
117
+ }
118
+ }
119
+
120
+ if (!edges.length) return
62
121
 
63
122
  // Deterministic nearest-first: containment depth descending, then ancestor id ascending,
64
123
  // matching the FTS backend's `ancestorLineage` ordering across rebuilds.
@@ -113,12 +172,19 @@ export async function buildAncestorsSidecar(ctx: {
113
172
  flush()
114
173
  childID = id
115
174
  edges = []
175
+ hasDependency = false
116
176
  }
117
177
 
118
178
  if (!attrs.has(id)) continue
119
179
 
120
180
  const apt = String(r.ancestor_placetype ?? "")
121
181
 
182
+ if (apt === "dependency") {
183
+ hasDependency = true
184
+
185
+ continue
186
+ }
187
+
122
188
  if (placetypeDepth(apt) === 0) continue
123
189
 
124
190
  const aid = Number(r.ancestor_id)
@@ -200,6 +266,9 @@ export async function buildAncestorsSidecar(ctx: {
200
266
  "ancestors",
201
267
  `${ancestorRows.toLocaleString()} closure rows across ${ancestorPlaces.toLocaleString()} places; ` +
202
268
  `${preOf.size.toLocaleString()} interval labels` +
269
+ (dependencyFallbacks
270
+ ? `; ${dependencyFallbacks.toLocaleString()} dependency ancestors resolved to territory country rows`
271
+ : "") +
203
272
  (droppedParents ? `; ${droppedParents.toLocaleString()} edges dropped (parent has no current spr row)` : "") +
204
273
  (cycleSkipped ? `; ${cycleSkipped.toLocaleString()} places skipped (canonical-parent cycle)` : "")
205
274
  )
@@ -0,0 +1,218 @@
1
+ // SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
2
+ // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
3
+
4
+ import type { DatabaseClient } from "@mailwoman/sqlite/client"
5
+ import { sql, type Kysely } from "kysely"
6
+
7
+ /**
8
+ * Name of the clustered `WITHOUT ROWID` SymSpell 1-delete index table.
9
+ * It indexes prominent primary candidate names.
10
+ */
11
+ export const CANDIDATE_DEL1_TABLE = "candidate_del1"
12
+
13
+ /**
14
+ * Minimum Unicode code-point length indexed in {@link CANDIDATE_DEL1_TABLE}.
15
+ *
16
+ * Below four characters, single-character edits collide broadly across short names.
17
+ */
18
+ const CANDIDATE_DEL1_MIN_LENGTH = 4
19
+
20
+ /**
21
+ * Maximum Unicode code-point length indexed in {@link CANDIDATE_DEL1_TABLE}.
22
+ *
23
+ * Longer names fall back to `candidate_fts` and avoid excessive delete keys per entry.
24
+ */
25
+ export const CANDIDATE_DEL1_MAX_LENGTH = 40
26
+
27
+ /**
28
+ * Minimum population for sub-region administrative and locality places in {@link CANDIDATE_DEL1_TABLE}.
29
+ */
30
+ const CANDIDATE_DEL1_MIN_POPULATION = 5000
31
+
32
+ const UNCONDITIONAL_PLACETYPES = ["country", "region", "macroregion"] as const
33
+
34
+ const POPULATED_PLACETYPES = ["county", "macrocounty", "locality", "borough", "localadmin"] as const
35
+
36
+ const HAS_LETTER_RE = /\p{L}/u
37
+
38
+ /**
39
+ * One SymSpell 1-delete index entry.
40
+ *
41
+ * Each row maps a 0- or 1-character deletion back to its canonical `candidate.name_key`.
42
+ */
43
+ export interface CandidateDel1Table {
44
+ del_key: string
45
+ name_key: string
46
+ }
47
+
48
+ /**
49
+ * Counts produced by {@link createCandidateDel1}.
50
+ */
51
+ export interface CandidateDel1Result {
52
+ /**
53
+ * Distinct prominent `name_key` values indexed.
54
+ */
55
+ keys: number
56
+ /**
57
+ * Total `(del_key, name_key)` rows written to {@link CANDIDATE_DEL1_TABLE}.
58
+ */
59
+ rows: number
60
+ }
61
+
62
+ /**
63
+ * Returns the first Unicode code point of `text`, or the empty string when `text` is empty.
64
+ */
65
+ export function firstCodePoint(text: string): string {
66
+ const cp = text.codePointAt(0)
67
+
68
+ return typeof cp === "number" ? String.fromCodePoint(cp) : ""
69
+ }
70
+
71
+ /**
72
+ * Computes the deduplicated SymSpell 1-delete key set (`{text} ∪ del1(text)`),
73
+ * measured in Unicode code points.
74
+ *
75
+ * Returns an empty array when `text` contains no letter (skipping numeric postcodes)
76
+ * or falls outside `[4, maxLength]` code points.
77
+ */
78
+ export function del1Keys(text: string, maxLength = CANDIDATE_DEL1_MAX_LENGTH): string[] {
79
+ if (!HAS_LETTER_RE.test(text)) return []
80
+
81
+ const chars = Array.from(text)
82
+
83
+ if (chars.length < CANDIDATE_DEL1_MIN_LENGTH || chars.length > maxLength) return []
84
+
85
+ const seen = new Set<string>([text])
86
+
87
+ for (let i = 0; i < chars.length; i++) {
88
+ seen.add(chars.slice(0, i).join("") + chars.slice(i + 1).join(""))
89
+ }
90
+
91
+ return [...seen]
92
+ }
93
+
94
+ /**
95
+ * Reports whether `a` and `b` lie within Damerau-Levenshtein distance 1 in code points.
96
+ *
97
+ * Counts one insertion, deletion, substitution, or adjacent transposition as one edit.
98
+ */
99
+ export function isWithinOneEdit(a: string, b: string): boolean {
100
+ if (a === b) return true
101
+
102
+ const ca = Array.from(a)
103
+ const cb = Array.from(b)
104
+
105
+ if (Math.abs(ca.length - cb.length) > 1) return false
106
+
107
+ if (ca.length === cb.length) {
108
+ let firstMismatch = -1
109
+ let secondMismatch = -1
110
+
111
+ for (let i = 0; i < ca.length; i++) {
112
+ if (ca[i] !== cb[i]) {
113
+ if (firstMismatch === -1) {
114
+ firstMismatch = i
115
+ } else if (secondMismatch === -1) {
116
+ secondMismatch = i
117
+ } else {
118
+ return false
119
+ }
120
+ }
121
+ }
122
+
123
+ if (secondMismatch === -1) return true
124
+
125
+ return (
126
+ secondMismatch === firstMismatch + 1 &&
127
+ ca[firstMismatch] === cb[secondMismatch] &&
128
+ ca[secondMismatch] === cb[firstMismatch]
129
+ )
130
+ }
131
+
132
+ const [shorter, longer] = ca.length < cb.length ? [ca, cb] : [cb, ca]
133
+ let i = 0
134
+ let j = 0
135
+ let edits = 0
136
+
137
+ while (i < shorter.length && j < longer.length) {
138
+ if (shorter[i] === longer[j]) {
139
+ i++
140
+
141
+ j++
142
+ } else {
143
+ edits++
144
+
145
+ j++
146
+
147
+ if (edits > 1) return false
148
+ }
149
+ }
150
+
151
+ return true
152
+ }
153
+
154
+ async function createCandidateDel1Table<DB>(db: Kysely<DB>): Promise<void> {
155
+ await db.schema
156
+ .createTable(CANDIDATE_DEL1_TABLE)
157
+ .addColumn("del_key", "text", (c) => c.notNull())
158
+ .addColumn("name_key", "text", (c) => c.notNull())
159
+ .addPrimaryKeyConstraint("candidate_del1_pk", ["del_key", "name_key"])
160
+ .modifyEnd(sql`without rowid`)
161
+ .execute()
162
+ }
163
+
164
+ /**
165
+ * Build (or rebuild) {@link CANDIDATE_DEL1_TABLE} from the materialized `candidate` table.
166
+ *
167
+ * Indexes distinct primary `name_key` values for countries, regions, macroregions,
168
+ * and counties, macrocounties, localities, boroughs, and localadmins with population >= 5,000.
169
+ * Call after `candidate` is materialized and any key folds have run.
170
+ */
171
+ export async function createCandidateDel1<DB>(db: DatabaseClient<DB>): Promise<CandidateDel1Result> {
172
+ await db.schema.dropTable(CANDIDATE_DEL1_TABLE).ifExists().execute()
173
+ await createCandidateDel1Table(db)
174
+
175
+ const unconditionalList = UNCONDITIONAL_PLACETYPES.map((p) => `'${p}'`).join(", ")
176
+ const populatedList = POPULATED_PLACETYPES.map((p) => `'${p}'`).join(", ")
177
+
178
+ const selectProminent = db.prepare(
179
+ "SELECT DISTINCT c.name_key " +
180
+ "FROM candidate c " +
181
+ "JOIN placetype_codes pc ON pc.id = c.placetype_id " +
182
+ "WHERE c.name_key IS NOT NULL " +
183
+ "AND c.is_primary = 1 " +
184
+ `AND (pc.placetype IN (${unconditionalList}) ` +
185
+ `OR (pc.placetype IN (${populatedList}) AND c.population >= ?))`
186
+ )
187
+
188
+ const insertRow = db.prepare(`INSERT OR IGNORE INTO ${CANDIDATE_DEL1_TABLE} (del_key, name_key) VALUES (?, ?)`)
189
+
190
+ let keys = 0
191
+ let rows = 0
192
+
193
+ db.exec("BEGIN")
194
+
195
+ try {
196
+ for (const row of selectProminent.iterate(CANDIDATE_DEL1_MIN_POPULATION) as Iterable<{ name_key: string }>) {
197
+ const nameKey = String(row.name_key)
198
+ const deletes = del1Keys(nameKey)
199
+
200
+ if (!deletes.length) continue
201
+
202
+ keys++
203
+
204
+ for (const delKey of deletes) {
205
+ insertRow.run(delKey, nameKey)
206
+
207
+ rows++
208
+ }
209
+ }
210
+
211
+ db.exec("COMMIT")
212
+ } catch (error) {
213
+ db.exec("ROLLBACK")
214
+ throw error
215
+ }
216
+
217
+ return { keys, rows }
218
+ }