@mailwoman/resolver-wof-sqlite 11.4.0 → 12.0.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 (67) hide show
  1. package/lib/build/candidate.ts +186 -0
  2. package/lib/build/population-corrections.ts +11 -2
  3. package/lib/candidate/lookup.ts +159 -15
  4. package/lib/candidate/name-roles.ts +112 -6
  5. package/lib/candidate/outcomes.ts +191 -0
  6. package/lib/candidate/schema.ts +67 -3
  7. package/lib/geonames/aliases.ts +39 -1
  8. package/lib/labels/street/normalize.ts +2 -1
  9. package/lib/landmark.ts +51 -4
  10. package/lib/lookup/types.ts +25 -0
  11. package/lib/outcome/memberships.ts +131 -0
  12. package/lib/outcome/schema.ts +147 -0
  13. package/lib/poi/schema.ts +2 -1
  14. package/lib/ranking/primary-preference.ts +14 -6
  15. package/out/build/candidate.d.ts +41 -0
  16. package/out/build/candidate.d.ts.map +1 -1
  17. package/out/build/candidate.js +84 -1
  18. package/out/build/candidate.js.map +1 -1
  19. package/out/build/population-corrections.d.ts +2 -2
  20. package/out/build/population-corrections.d.ts.map +1 -1
  21. package/out/build/population-corrections.js +10 -2
  22. package/out/build/population-corrections.js.map +1 -1
  23. package/out/candidate/lookup.d.ts +14 -3
  24. package/out/candidate/lookup.d.ts.map +1 -1
  25. package/out/candidate/lookup.js +101 -9
  26. package/out/candidate/lookup.js.map +1 -1
  27. package/out/candidate/name-roles.d.ts +3 -2
  28. package/out/candidate/name-roles.d.ts.map +1 -1
  29. package/out/candidate/name-roles.js +75 -5
  30. package/out/candidate/name-roles.js.map +1 -1
  31. package/out/candidate/outcomes.d.ts +57 -0
  32. package/out/candidate/outcomes.d.ts.map +1 -0
  33. package/out/candidate/outcomes.js +109 -0
  34. package/out/candidate/outcomes.js.map +1 -0
  35. package/out/candidate/schema.d.ts +45 -3
  36. package/out/candidate/schema.d.ts.map +1 -1
  37. package/out/candidate/schema.js +34 -0
  38. package/out/candidate/schema.js.map +1 -1
  39. package/out/geonames/aliases.d.ts +10 -0
  40. package/out/geonames/aliases.d.ts.map +1 -1
  41. package/out/geonames/aliases.js +33 -1
  42. package/out/geonames/aliases.js.map +1 -1
  43. package/out/labels/street/normalize.d.ts.map +1 -1
  44. package/out/labels/street/normalize.js +1 -1
  45. package/out/labels/street/normalize.js.map +1 -1
  46. package/out/landmark.d.ts +15 -3
  47. package/out/landmark.d.ts.map +1 -1
  48. package/out/landmark.js +38 -3
  49. package/out/landmark.js.map +1 -1
  50. package/out/lookup/types.d.ts +21 -0
  51. package/out/lookup/types.d.ts.map +1 -1
  52. package/out/outcome/memberships.d.ts +58 -0
  53. package/out/outcome/memberships.d.ts.map +1 -0
  54. package/out/outcome/memberships.js +83 -0
  55. package/out/outcome/memberships.js.map +1 -0
  56. package/out/outcome/schema.d.ts +74 -0
  57. package/out/outcome/schema.d.ts.map +1 -0
  58. package/out/outcome/schema.js +63 -0
  59. package/out/outcome/schema.js.map +1 -0
  60. package/out/poi/schema.d.ts +2 -1
  61. package/out/poi/schema.d.ts.map +1 -1
  62. package/out/poi/schema.js.map +1 -1
  63. package/out/ranking/primary-preference.d.ts +9 -5
  64. package/out/ranking/primary-preference.d.ts.map +1 -1
  65. package/out/ranking/primary-preference.js +11 -3
  66. package/out/ranking/primary-preference.js.map +1 -1
  67. package/package.json +15 -15
@@ -23,18 +23,25 @@ import { IMPORTANCE_JOIN_RADIUS_KM, loadImportanceIndex } from "#candidate/impor
23
23
  import { applyCandidateKeyFold, type CandidateKeyFold } from "#candidate/key-fold"
24
24
  import { GLOSS_KEY_THRESHOLD, stampNameRoles } from "#candidate/name-roles"
25
25
  import { refuseNicknamesOfNamesakes } from "#candidate/nickname-namesakes"
26
+ import { type CandidateOutcomeInputs, type CandidateOutcomeResult, stageCandidateOutcomes } from "#candidate/outcomes"
26
27
  import { stageOvertureTwins } from "#candidate/overture-twins"
27
28
  import type { PlaceAttrs } from "#candidate/place-attrs"
28
29
  import {
29
30
  CANDIDATE_COLUMNS,
31
+ CANDIDATE_CONCORDANCES_TABLE,
32
+ CANDIDATE_SITELINKS_TABLE,
33
+ createCandidateConcordancesTable,
30
34
  createCandidatePostcodePlaceIndex,
35
+ createCandidateSitelinksTable,
31
36
  createCandidateStagingTables,
32
37
  createCandidateTable,
33
38
  type CandidateDatabase,
34
39
  POSTCODE_PLACETYPE,
35
40
  } from "#candidate/schema"
36
41
  import { normalizeLocalityForKey } from "#labels/street/normalize"
42
+ import type { LandmarkDatabase } from "#landmark"
37
43
  import type { WOFDatabase } from "#schema"
44
+ import { hasTable } from "#sqlite-utils"
38
45
 
39
46
  /**
40
47
  * Options for {@link buildCandidateTable}.
@@ -122,6 +129,26 @@ export interface BuildCandidateOptions {
122
129
  * @defaultValue none
123
130
  */
124
131
  keyFolds?: readonly CandidateKeyFold[]
132
+
133
+ /**
134
+ * The pinned outcome definitions and the GeoNames dumps whose feature codes become assertions.
135
+ *
136
+ * Without it the artifact has no outcome tables, and a request that filters
137
+ * or orders by outcome against it is refused.
138
+ */
139
+ outcomes?: CandidateOutcomeInputs
140
+
141
+ /**
142
+ * Optional map of Wikidata QID (e.g. `"Q11299"`) to Wikipedia sitelink count,
143
+ * joined via `wd:id` concordances into `candidate_sitelinks`.
144
+ */
145
+ sitelinksByQID?: ReadonlyMap<string, number>
146
+
147
+ /**
148
+ * Optional `landmarks.db` path whose `landmark_name (qid, sitelinks)` table supplies
149
+ * sitelink counts joined via `wd:id` concordances into `candidate_sitelinks`.
150
+ */
151
+ landmarksDBPath?: PathBuilderLike
125
152
  }
126
153
 
127
154
  /**
@@ -212,6 +239,18 @@ export interface BuildCandidateResult {
212
239
  */
213
240
  roleAbbr: number
214
241
 
242
+ /**
243
+ * The count of alias rows stamped `name_role = 'variant'`, which marks an
244
+ * own-name spelling or transliteration variant.
245
+ */
246
+ roleVariant: number
247
+
248
+ /**
249
+ * The count of alias rows stamped `name_role = 'foreign-script'`, which marks a
250
+ * non-Latin alias outside the country's written scripts.
251
+ */
252
+ roleForeignScript: number
253
+
215
254
  /**
216
255
  * The count of admin places whose staged key count reached the gloss key threshold.
217
256
  * It is the denominator for `keyTailWithRole`.
@@ -234,6 +273,22 @@ export interface BuildCandidateResult {
234
273
  * or null with `overtureMatches`.
235
274
  */
236
275
  overtureTwinRowsDropped: number | null
276
+
277
+ /**
278
+ * The outcome tables' counts, or null when no definitions were given.
279
+ */
280
+ outcomes: CandidateOutcomeResult | null
281
+
282
+ /**
283
+ * Count of `wd:id` rows copied into `concordances`, or null when the source
284
+ * admin database lacked `concordances`.
285
+ */
286
+ concordances: number | null
287
+
288
+ /**
289
+ * Count of rows written to `candidate_sitelinks`, or null when no sitelinks source was supplied.
290
+ */
291
+ sitelinks: number | null
237
292
  }
238
293
 
239
294
  /**
@@ -631,6 +686,12 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
631
686
  .execute()
632
687
  }
633
688
 
689
+ const outcomes: CandidateOutcomeResult | null = opts.outcomes
690
+ ? await stageCandidateOutcomes({ src, out: kdb, attrs, ptcodes, inputs: opts.outcomes, progress })
691
+ : null
692
+
693
+ const { nConcordances, nSitelinks } = await stageCandidateConcordancesAndSitelinks(src, kdb, attrs, opts, progress)
694
+
634
695
  if (opts.capitals?.length) {
635
696
  await createCapitalTable<CandidateDatabase>(kdb)
636
697
 
@@ -703,5 +764,130 @@ export async function buildCandidateTable(opts: BuildCandidateOptions): Promise<
703
764
  populationEstimated: typeof importance?.stats.estimates === "number" ? importance.estimated : null,
704
765
  overtureMatches: twins ? twins.matches : null,
705
766
  overtureTwinRowsDropped: twins ? twins.rowsDropped : null,
767
+ outcomes,
768
+ concordances: nConcordances,
769
+ sitelinks: nSitelinks,
770
+ }
771
+ }
772
+
773
+ async function stageCandidateConcordancesAndSitelinks(
774
+ src: DatabaseClient<WOFDatabase>,
775
+ kdb: DatabaseClient<CandidateDatabase>,
776
+ attrs: ReadonlyMap<number, PlaceAttrs>,
777
+ opts: Pick<BuildCandidateOptions, "sitelinksByQID" | "landmarksDBPath">,
778
+ progress: (stage: string, detail: string) => void
779
+ ): Promise<{ nConcordances: number | null; nSitelinks: number | null }> {
780
+ const { nConcordances, qidBySPRID } = await copyCandidateConcordances(src, kdb, attrs, progress)
781
+ const nSitelinks = await populateCandidateSitelinks(kdb, qidBySPRID, opts, progress)
782
+
783
+ return { nConcordances, nSitelinks }
784
+ }
785
+
786
+ async function copyCandidateConcordances(
787
+ src: DatabaseClient<WOFDatabase>,
788
+ kdb: DatabaseClient<CandidateDatabase>,
789
+ attrs: ReadonlyMap<number, PlaceAttrs>,
790
+ progress: (stage: string, detail: string) => void
791
+ ): Promise<{ nConcordances: number | null; qidBySPRID: Map<number, string> }> {
792
+ const qidBySPRID = new Map<number, string>()
793
+
794
+ if (!hasTable(src, CANDIDATE_CONCORDANCES_TABLE)) {
795
+ return { nConcordances: null, qidBySPRID }
796
+ }
797
+
798
+ await createCandidateConcordancesTable(kdb)
799
+
800
+ const insConc = kdb.prepare(
801
+ `INSERT OR IGNORE INTO ${CANDIDATE_CONCORDANCES_TABLE} (id, other_source, other_id) VALUES (?, ?, ?)`
802
+ )
803
+
804
+ let copied = 0
805
+ kdb.exec("BEGIN")
806
+
807
+ for (const r of src
808
+ .prepare("SELECT id, other_source, other_id FROM concordances WHERE other_source = 'wd:id'")
809
+ .iterate()) {
810
+ const id = Number(r.id)
811
+
812
+ if (!attrs.has(id)) continue
813
+ const otherID = String(r.other_id ?? "").trim()
814
+
815
+ if (!otherID) continue
816
+ insConc.run(id, "wd:id", otherID)
817
+
818
+ if (!qidBySPRID.has(id)) {
819
+ qidBySPRID.set(id, otherID)
820
+ }
821
+
822
+ copied++
823
+ }
824
+
825
+ kdb.exec("COMMIT")
826
+ progress("concordances", `${copied.toLocaleString()} Wikidata concordances copied`)
827
+
828
+ return { nConcordances: copied, qidBySPRID }
829
+ }
830
+
831
+ async function populateCandidateSitelinks(
832
+ kdb: DatabaseClient<CandidateDatabase>,
833
+ qidBySPRID: ReadonlyMap<number, string>,
834
+ opts: Pick<BuildCandidateOptions, "sitelinksByQID" | "landmarksDBPath">,
835
+ progress: (stage: string, detail: string) => void
836
+ ): Promise<number | null> {
837
+ if (!opts.sitelinksByQID && !opts.landmarksDBPath) {
838
+ return null
839
+ }
840
+
841
+ const sitelinksMap = new Map<string, number>()
842
+
843
+ if (opts.landmarksDBPath && (await pathExists(opts.landmarksDBPath))) {
844
+ using ldb = new DatabaseClient<LandmarkDatabase>(opts.landmarksDBPath, { readOnly: true })
845
+
846
+ if (hasTable(ldb, "landmark_name")) {
847
+ for (const r of ldb
848
+ .prepare(
849
+ "SELECT qid, MAX(sitelinks) AS sitelinks FROM landmark_name WHERE qid IS NOT NULL AND sitelinks IS NOT NULL GROUP BY qid"
850
+ )
851
+ .iterate()) {
852
+ const qid = String(r.qid ?? "").trim()
853
+ const count = Number(r.sitelinks)
854
+
855
+ if (qid && Number.isFinite(count) && count >= 0) {
856
+ sitelinksMap.set(qid, Math.trunc(count))
857
+ }
858
+ }
859
+ }
860
+ }
861
+
862
+ if (opts.sitelinksByQID) {
863
+ for (const [qid, count] of opts.sitelinksByQID) {
864
+ if (qid && Number.isFinite(count) && count >= 0) {
865
+ sitelinksMap.set(qid, Math.trunc(count))
866
+ }
867
+ }
868
+ }
869
+
870
+ await createCandidateSitelinksTable(kdb)
871
+
872
+ const insSitelinks = kdb.prepare(
873
+ `INSERT OR REPLACE INTO ${CANDIDATE_SITELINKS_TABLE} (spr_id, sitelinks) VALUES (?, ?)`
874
+ )
875
+
876
+ let written = 0
877
+ kdb.exec("BEGIN")
878
+
879
+ for (const [sprID, qid] of qidBySPRID) {
880
+ const count = sitelinksMap.get(qid)
881
+
882
+ if (typeof count !== "number") continue
883
+
884
+ insSitelinks.run(sprID, count)
885
+
886
+ written++
706
887
  }
888
+
889
+ kdb.exec("COMMIT")
890
+ progress("sitelinks", `${written.toLocaleString()} candidate sitelink counts stored`)
891
+
892
+ return written
707
893
  }
@@ -44,13 +44,22 @@ export interface PopulationCorrection {
44
44
  /**
45
45
  * WOF id → the corrected population.
46
46
  *
47
- * One entry, because one row has been followed.
48
- * A second correction requires the same review.
47
+ * Each entry was checked against the record's own `gn:id` concordance and coordinates.
48
+ * Another correction requires the same review.
49
49
  *
50
50
  * Read the row's `gn:id` and confirm the coordinates agree.
51
51
  * Then record the second source's value.
52
52
  */
53
53
  export const POPULATION_CORRECTIONS: Readonly<Record<number, PopulationCorrection>> = {
54
+ 101_922_341: {
55
+ geonamesID: "284315",
56
+ population: 29_019,
57
+ recorded: 0,
58
+ note:
59
+ "Bethlehem (Beit Lahm), West Bank (`PS`). The WOF record sits at 31.706 / 35.204 with no `wof:population` " +
60
+ "or `gn:population` (`qs:pop: 0`). GeoNames 284315 — the id that record's own `gn:id` concordance lists — " +
61
+ "sits at 31.705 / 35.204, about 146 m away, classed `PPLA2`, with population 29,019.",
62
+ },
54
63
  102_030_887: {
55
64
  geonamesID: "1278149",
56
65
  population: 1_175_116,
@@ -9,6 +9,7 @@ import {
9
9
  populationScoreUnmeasured,
10
10
  referentialFromPopulation,
11
11
  } from "@mailwoman/core/resolver"
12
+ import { refuseMissingOutcomeTables } from "@mailwoman/core/resolver/outcome"
12
13
  import { allRows } from "@mailwoman/core/utils"
13
14
  import { jaroWinkler, levenshteinSimilarity } from "@mailwoman/match/comparators"
14
15
  import { partitionByContainment } from "@mailwoman/resolver"
@@ -26,7 +27,13 @@ import {
26
27
  import { readGazetteerCoverageManifest } from "#candidate/coverage-manifest"
27
28
  import { CANDIDATE_FTS_TABLE } from "#candidate/fts"
28
29
  import { candidateQueryKeyFold } from "#candidate/key-fold"
29
- import type { CandidateDatabase, CandidateTable, CountryCodeTable, PlacetypeCodeTable } from "#candidate/schema"
30
+ import {
31
+ CANDIDATE_SITELINKS_TABLE,
32
+ type CandidateDatabase,
33
+ type CandidateTable,
34
+ type CountryCodeTable,
35
+ type PlacetypeCodeTable,
36
+ } from "#candidate/schema"
30
37
  import {
31
38
  POSTAL_CITY_CANDIDATE_TABLE,
32
39
  type PostalCityCandidateTable,
@@ -34,6 +41,7 @@ import {
34
41
  import { REGION_CLASS_PLACETYPES, regionQualifierProbeKeys } from "#labels/region"
35
42
  import { type NameKey, normalizeLocalityForKey, stripLocalityQualifier } from "#labels/street/normalize"
36
43
  import type { FindPlaceQuery, PlaceCandidate, PlaceLookup, WOFPlacetype } from "#lookup/types"
44
+ import { missingOutcomeTablesIn, OutcomeMembershipReader, outcomeAdmitPredicate } from "#outcome/memberships"
37
45
  import { rankByPrimaryPreference, type RankedRow, regionAliasMargin, RERANK_FETCH } from "#ranking/primary-preference"
38
46
  import { applyProximityRerank } from "#ranking/proximity-rerank"
39
47
  import { hasColumn, hasTable } from "#sqlite-utils"
@@ -70,8 +78,8 @@ type CandidateRow = Pick<
70
78
  | "is_primary"
71
79
  | "population"
72
80
  > &
73
- // Optional because older artifacts may not include `importance`.
74
- Partial<Pick<CandidateTable, "importance">>
81
+ // Optional because older artifacts may not include `importance` or `name_role`.
82
+ Partial<Pick<CandidateTable, "importance" | "name_role">>
75
83
 
76
84
  /**
77
85
  * What a containment re-rank needs beside the rows: the keys to inject contained
@@ -83,6 +91,11 @@ interface ContainmentOptions {
83
91
  shapeFilters: string[]
84
92
  shapeParams: Array<string | number>
85
93
  limit: number
94
+ /**
95
+ * The outcome filter's predicate, also among `shapeFilters`, for the injections
96
+ * that skip the shape filters.
97
+ */
98
+ outcomeFilter: { sql: string; params: number[] } | null
86
99
  }
87
100
 
88
101
  const FUZZY_FETCH = 40
@@ -93,6 +106,14 @@ function wordFuzzySimilarity(a: string, b: string): number {
93
106
  return Math.max(jaroWinkler(a, b), levenshteinSimilarity(a, b))
94
107
  }
95
108
 
109
+ /**
110
+ * The number of words in a folded name key.
111
+ * A folded key separates its words with single spaces.
112
+ */
113
+ function wordCount(key: string): number {
114
+ return key ? key.split(" ").length : 0
115
+ }
116
+
96
117
  const POSTCODE_CONTAINMENT_THRESHOLD_KM = 25
97
118
 
98
119
  function ftsTrigramQuery(s: string): string {
@@ -109,6 +130,14 @@ function ftsTrigramQuery(s: string): string {
109
130
  return [...grams].map((g) => `"${g}"`).join(" OR ")
110
131
  }
111
132
 
133
+ /**
134
+ * A {@link PlaceCandidate} extended with cross-layer sitelink prominence
135
+ * when the artifact includes `candidate_sitelinks`.
136
+ */
137
+ export type CandidatePlace = PlaceCandidate & {
138
+ sitelinkProminence?: number | null
139
+ }
140
+
112
141
  /**
113
142
  * Node {@link PlaceLookup} over `candidate.db`.
114
143
  */
@@ -144,6 +173,11 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
144
173
  readonly #qualifierProbe: ReturnType<DatabaseClient["prepare"]> | undefined
145
174
 
146
175
  #placeProbe: ReturnType<DatabaseClient["prepare"]> | undefined
176
+
177
+ readonly #missingOutcomeTables: readonly string[]
178
+ readonly #outcomes: OutcomeMembershipReader | null
179
+ readonly #wikidataProbe: ReturnType<DatabaseClient["prepare"]> | undefined
180
+ readonly #sitelinkProbe: ReturnType<DatabaseClient["prepare"]> | undefined
147
181
  /**
148
182
  * The folds the artifact recorded for its `name_key` column, applied to every query key.
149
183
  */
@@ -213,6 +247,69 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
213
247
  }
214
248
 
215
249
  this.artifactCoverage = readGazetteerCoverageManifest(this.database)
250
+
251
+ this.#missingOutcomeTables = missingOutcomeTablesIn(this.database)
252
+ this.#outcomes = OutcomeMembershipReader.open(this.database, { recordColumn: "spr_id", layer: "candidate" })
253
+
254
+ // The unified build's `concordances` table holds each record's `wd:id`.
255
+ if (hasTable(this.database, "concordances")) {
256
+ this.#wikidataProbe = this.database.prepare(
257
+ "SELECT other_id FROM concordances WHERE id = ? AND other_source = 'wd:id' LIMIT 1"
258
+ )
259
+ }
260
+
261
+ if (hasTable(this.database, CANDIDATE_SITELINKS_TABLE)) {
262
+ this.#sitelinkProbe = this.database.prepare(
263
+ `SELECT sitelinks FROM ${CANDIDATE_SITELINKS_TABLE} WHERE spr_id = ? LIMIT 1`
264
+ )
265
+ }
266
+ }
267
+
268
+ /**
269
+ * The outcome tables the artifact lacks, empty when it holds them all.
270
+ */
271
+ missingOutcomeTables(): readonly string[] {
272
+ return this.#missingOutcomeTables
273
+ }
274
+
275
+ /**
276
+ * The fetch predicate of a query's outcome filter, or null when the query sets none.
277
+ *
278
+ * @throws {OutcomeRequestError} When the artifact predates the outcome tables.
279
+ */
280
+ #outcomeFilter(query: FindPlaceQuery): { sql: string; params: number[] } | null {
281
+ if (!query.outcome) return null
282
+
283
+ refuseMissingOutcomeTables("candidate.db", this.#missingOutcomeTables)
284
+
285
+ if (!query.outcome.admit) return null
286
+
287
+ return outcomeAdmitPredicate(
288
+ query.outcome.admit,
289
+ "spr_id",
290
+ "candidate.spr_id",
291
+ "(SELECT pc.placetype FROM placetype_codes pc WHERE pc.id = candidate.placetype_id)"
292
+ )
293
+ }
294
+
295
+ /**
296
+ * The record's Wikidata item, or null when the artifact records none.
297
+ */
298
+ #wikidataOf(sprID: number): string | null {
299
+ const row = this.#wikidataProbe?.get(sprID) as { other_id: string } | undefined
300
+
301
+ return row ? String(row.other_id) : null
302
+ }
303
+
304
+ /**
305
+ * Cross-layer prominence `log10(sitelinks + 1)` from `candidate_sitelinks`, or null when unrecorded.
306
+ */
307
+ #sitelinkProminenceOf(sprID: number): number | null {
308
+ const row = this.#sitelinkProbe?.get(sprID) as { sitelinks: number } | undefined
309
+
310
+ return row && typeof row.sitelinks === "number" && Number.isFinite(row.sitelinks)
311
+ ? Math.log10(row.sitelinks + 1)
312
+ : null
216
313
  }
217
314
 
218
315
  #ancestorLineage(id: number | string): Ancestor[] {
@@ -326,6 +423,13 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
326
423
 
327
424
  for (const row of rows) {
328
425
  row.containedByQualifier = contained(Number(row.spr_id))
426
+
427
+ // A foreign-script namesake contained by the query's stated qualifier
428
+ // (`Москва, Айдахо`, `בית לחם, פנסילבניה`) re-enters the exact tier
429
+ // so `partitionByContainment` places it ahead of uncontained home-script candidates.
430
+ if (row.containedByQualifier && row.name_role === "foreign-script" && row.demoted) {
431
+ row.demoted = false
432
+ }
329
433
  }
330
434
 
331
435
  const present = new Set(rows.map((row) => Number(row.spr_id)))
@@ -333,7 +437,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
333
437
 
334
438
  const injectSQL = (primaryOnly: boolean): string =>
335
439
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
336
- `${this.#importanceSelect} FROM candidate WHERE ${["name_key = ?", ...opts.shapeFilters, ...(primaryOnly ? ["is_primary = 1"] : [])].join(" AND ")} ` +
440
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE ${["name_key = ?", ...opts.shapeFilters, ...(primaryOnly ? ["is_primary = 1"] : [])].join(" AND ")} ` +
337
441
  "ORDER BY neg_rank ASC LIMIT ?"
338
442
 
339
443
  const injectFrom = (key: string, primaryOnly: boolean): void => {
@@ -356,23 +460,39 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
356
460
 
357
461
  injectFrom(opts.nameKey, false)
358
462
 
359
- // Also inject contained neighborhood-band namesakes (primary-keyed only).
463
+ // Also inject contained neighborhood-band namesakes keyed by the primary name
464
+ // or by an `abbr` alias whose word count equals the primary name's.
465
+ // Such an alias respells the name, as `Mount Tabor` does `Mt. Tabor`.
466
+ // An alias with fewer words drops one, as `Camden` does `Camden Town`, and is the
467
+ // exact name of a larger place, the borough of Camden, so it stays out.
360
468
  const bandIDs = ["neighbourhood", "macrohood", "microhood"]
361
469
  .map((placetype) => this.#placetypeToID.get(placetype))
362
470
  .filter((id) => typeof id === "number")
363
471
 
364
472
  if (bandIDs.length) {
473
+ const bandNames = this.#hasNameRole ? "(is_primary = 1 OR name_role = 'abbr')" : "is_primary = 1"
474
+
365
475
  const bandSQL =
366
476
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
367
- `${this.#importanceSelect} FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.map(() => "?").join(",")}) AND is_primary = 1 ` +
368
- "ORDER BY neg_rank ASC LIMIT ?"
477
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE name_key = ? AND placetype_id IN (${bandIDs.map(() => "?").join(",")}) AND ${bandNames} ` +
478
+ `${opts.outcomeFilter ? `AND ${opts.outcomeFilter.sql} ` : ""}ORDER BY neg_rank ASC LIMIT ?`
369
479
 
370
- const fetched = allRows<CandidateRow>(this.database.prepare(bandSQL), opts.nameKey, ...bandIDs, RERANK_FETCH)
480
+ const fetched = allRows<CandidateRow>(
481
+ this.database.prepare(bandSQL),
482
+ opts.nameKey,
483
+ ...bandIDs,
484
+ ...(opts.outcomeFilter?.params ?? []),
485
+ RERANK_FETCH
486
+ )
487
+
488
+ const queryWords = wordCount(opts.nameKey)
371
489
 
372
490
  for (const row of fetched) {
373
491
  const sprID = Number(row.spr_id)
374
492
 
375
493
  if (present.has(sprID) || !contained(sprID)) continue
494
+
495
+ if (!row.is_primary && (!row.name || wordCount(normalizeLocalityForKey(row.name)) !== queryWords)) continue
376
496
  present.add(sprID)
377
497
 
378
498
  injected.push({ ...row, effectiveNegRank: row.neg_rank, demoted: false, containedByQualifier: true })
@@ -430,7 +550,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
430
550
  return { lat: Number(row.latitude), lon: Number(row.longitude) }
431
551
  }
432
552
 
433
- async findPlace(query: FindPlaceQuery): Promise<PlaceCandidate[]> {
553
+ async findPlace(query: FindPlaceQuery): Promise<CandidatePlace[]> {
434
554
  let text = (query.text ?? "").trim()
435
555
 
436
556
  if (!text) return []
@@ -447,7 +567,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
447
567
 
448
568
  if (!nameKey) return []
449
569
 
450
- if (query.postcode && this.#postalCityProbe && this.#wantsLocality(query.placetype)) {
570
+ // The postal-city probe reads no outcome tables, so an outcome query skips it.
571
+ if (query.postcode && !query.outcome && this.#postalCityProbe && this.#wantsLocality(query.placetype)) {
451
572
  const hit = this.#postalCityProbe.get(nameKey, query.postcode.trim()) as
452
573
  | Pick<PostalCityCandidateTable, "spr_id" | "name" | "latitude" | "longitude">
453
574
  | undefined
@@ -526,6 +647,14 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
526
647
  shapeParams.push(...query.excludeNameRoles)
527
648
  }
528
649
 
650
+ // The outcome filter is a predicate of the fetch, so a matching row is never lost to the row limit.
651
+ const outcomeFilter = this.#outcomeFilter(query)
652
+
653
+ if (outcomeFilter) {
654
+ shapeFilters.push(outcomeFilter.sql)
655
+ shapeParams.push(...outcomeFilter.params)
656
+ }
657
+
529
658
  filters.push(...shapeFilters)
530
659
  filterParams.push(...shapeParams)
531
660
 
@@ -662,6 +791,7 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
662
791
  shapeFilters,
663
792
  shapeParams,
664
793
  limit,
794
+ outcomeFilter,
665
795
  }
666
796
 
667
797
  if (query.regionQualifier?.trim() && this.#qualifierProbe && this.#wantsLocality(query.placetype)) {
@@ -677,6 +807,13 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
677
807
 
678
808
  const candidates = rows.map((row) => this.#toCandidate(row, regionScopeMiss))
679
809
 
810
+ if (query.outcome) {
811
+ for (const candidate of candidates) {
812
+ candidate.outcomes = this.#outcomes!.read(candidate.id, candidate.placetype, query.outcome)
813
+ candidate.wikidata = this.#wikidataOf(candidate.id)
814
+ }
815
+ }
816
+
680
817
  if (query.bias && query.bias.length) {
681
818
  applyProximityRerank(candidates, query.bias)
682
819
  }
@@ -687,12 +824,12 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
687
824
  /**
688
825
  * One place by its `spr_id`, read from its primary-name row, or null when the table holds no row for it.
689
826
  */
690
- place(id: number): PlaceCandidate | null {
827
+ place(id: number): CandidatePlace | null {
691
828
  if (!Number.isInteger(id)) return null
692
829
 
693
830
  this.#placeProbe ??= this.database.prepare(
694
831
  "SELECT spr_id, name, country_id, placetype_id, latitude, longitude, min_lat, min_lon, max_lat, max_lon, neg_rank, is_primary, population" +
695
- `${this.#importanceSelect} FROM candidate WHERE spr_id = ? ORDER BY is_primary DESC LIMIT 1`
832
+ `${this.#importanceSelect}${this.#roleSelect} FROM candidate WHERE spr_id = ? ORDER BY is_primary DESC LIMIT 1`
696
833
  )
697
834
 
698
835
  const row = this.#placeProbe.get(id) as CandidateRow | undefined
@@ -700,13 +837,16 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
700
837
  return row ? this.#toCandidate({ ...row, effectiveNegRank: row.neg_rank, demoted: false }, false) : null
701
838
  }
702
839
 
703
- #toCandidate(row: RankedRow<CandidateRow>, regionScopeMiss: boolean): PlaceCandidate {
840
+ #toCandidate(row: RankedRow<CandidateRow>, regionScopeMiss: boolean): CandidatePlace {
841
+ const sprID = Number(row.spr_id)
704
842
  const hasBbox = row.min_lat != null && row.max_lat != null && row.min_lon != null && row.max_lon != null
705
- const parent = this.#ancestorLineage(Number(row.spr_id))[0]
843
+ const parent = this.#ancestorLineage(sprID)[0]
706
844
  const hasPopulation = row.population !== null && row.population > 0
845
+ const wikidata = this.#wikidataProbe ? this.#wikidataOf(sprID) : null
846
+ const sitelinkProminence = this.#sitelinkProbe ? this.#sitelinkProminenceOf(sprID) : null
707
847
 
708
848
  return {
709
- id: Number(row.spr_id),
849
+ id: sprID,
710
850
  name: String(row.name ?? ""),
711
851
  placetype: (this.#idToPlacetype.get(Number(row.placetype_id)) ?? "") as WOFPlacetype,
712
852
 
@@ -734,6 +874,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
734
874
 
735
875
  matchedAlias: row.is_primary === 0 ? true : null,
736
876
 
877
+ nameRole: typeof row.name_role === "string" ? row.name_role : null,
878
+
737
879
  population: hasPopulation ? row.population : null,
738
880
  referential: hasPopulation ? referentialFromPopulation(row.population) : null,
739
881
  encyclopedic: null,
@@ -748,6 +890,8 @@ export class WOFCandidateTableLookup extends SQLiteLookup<CandidateDatabase> imp
748
890
  }
749
891
  : null,
750
892
  mismatch: null,
893
+ ...(wikidata ? { wikidata } : {}),
894
+ ...(sitelinkProminence != null ? { sitelinkProminence } : {}),
751
895
  }
752
896
  }
753
897
  }