@mailwoman/resolver-wof-sqlite 12.1.0 → 12.2.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 (49) hide show
  1. package/lib/address/keys/lookup.ts +114 -0
  2. package/lib/address/keys/open.ts +1 -0
  3. package/lib/address/keys/point-lookup.ts +57 -2
  4. package/lib/address/point/schema.ts +113 -35
  5. package/lib/address/point.ts +141 -5
  6. package/lib/labels/street/normalize.ts +121 -1
  7. package/lib/landmark.ts +43 -2
  8. package/lib/poi/lookup.ts +144 -52
  9. package/lib/poi/schema.ts +9 -1
  10. package/lib/weights/overlay-linker.ts +6 -2
  11. package/out/address/keys/lookup.d.ts +25 -0
  12. package/out/address/keys/lookup.d.ts.map +1 -1
  13. package/out/address/keys/lookup.js +63 -0
  14. package/out/address/keys/lookup.js.map +1 -1
  15. package/out/address/keys/open.d.ts.map +1 -1
  16. package/out/address/keys/open.js +1 -0
  17. package/out/address/keys/open.js.map +1 -1
  18. package/out/address/keys/point-lookup.d.ts +6 -1
  19. package/out/address/keys/point-lookup.d.ts.map +1 -1
  20. package/out/address/keys/point-lookup.js +39 -1
  21. package/out/address/keys/point-lookup.js.map +1 -1
  22. package/out/address/point/schema.d.ts +3 -1
  23. package/out/address/point/schema.d.ts.map +1 -1
  24. package/out/address/point/schema.js +87 -31
  25. package/out/address/point/schema.js.map +1 -1
  26. package/out/address/point.d.ts +12 -1
  27. package/out/address/point.d.ts.map +1 -1
  28. package/out/address/point.js +88 -4
  29. package/out/address/point.js.map +1 -1
  30. package/out/labels/street/normalize.d.ts.map +1 -1
  31. package/out/labels/street/normalize.js +115 -1
  32. package/out/labels/street/normalize.js.map +1 -1
  33. package/out/landmark.d.ts +8 -0
  34. package/out/landmark.d.ts.map +1 -1
  35. package/out/landmark.js +25 -2
  36. package/out/landmark.js.map +1 -1
  37. package/out/poi/lookup.d.ts +5 -1
  38. package/out/poi/lookup.d.ts.map +1 -1
  39. package/out/poi/lookup.js +111 -53
  40. package/out/poi/lookup.js.map +1 -1
  41. package/out/poi/schema.d.ts +7 -2
  42. package/out/poi/schema.d.ts.map +1 -1
  43. package/out/poi/schema.js +3 -0
  44. package/out/poi/schema.js.map +1 -1
  45. package/out/weights/overlay-linker.d.ts +1 -1
  46. package/out/weights/overlay-linker.d.ts.map +1 -1
  47. package/out/weights/overlay-linker.js +5 -1
  48. package/out/weights/overlay-linker.js.map +1 -1
  49. package/package.json +12 -12
@@ -357,6 +357,14 @@ function expandStreetSuffix(full: string): (words: string[]) => void {
357
357
  }
358
358
  }
359
359
 
360
+ /**
361
+ * Matches a Central European dual house number (`conscription/orientation` or `building/flat`),
362
+ * such as Czech `481/32` or Polish `12/4`, capturing the leading building number.
363
+ *
364
+ * Kept off `en` and `us`, where `12/345` denotes unit 12 at house number 345.
365
+ */
366
+ const SLASH_HOUSE_NUMBER_BASE = /^(\d+[a-z]?)\/\d+[a-z]?$/
367
+
360
368
  /**
361
369
  * The rules every locale has unless its row states another.
362
370
  */
@@ -417,6 +425,7 @@ const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
417
425
  ...SHARED_KEY_RULES,
418
426
  streetKey: (street) => wordStreetKey(street, expandStreetSuffix("strasse")),
419
427
  canonicalMorphology: "germanic-fused",
428
+ houseNumberBase: SLASH_HOUSE_NUMBER_BASE,
420
429
  },
421
430
  it: { ...SHARED_KEY_RULES, streetKey: (street) => wordStreetKey(street, expandLeadingWord(IT_STREET_TYPE_ABBREV)) },
422
431
  nl: {
@@ -436,6 +445,7 @@ const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
436
445
  words.shift()
437
446
  }
438
447
  }),
448
+ houseNumberBase: SLASH_HOUSE_NUMBER_BASE,
439
449
  },
440
450
  vn: {
441
451
  ...SHARED_KEY_RULES,
@@ -462,7 +472,10 @@ const STREET_KEY_RULES: Readonly<Record<string, StreetKeyRules>> = {
462
472
  // 之 and 附 join a sub-number to a base number, and the Taiwanese register stores the base.
463
473
  houseNumberBase: /^(\d+)(?:[之附]\d+)+$/u,
464
474
  },
465
- und: SHARED_KEY_RULES,
475
+ und: {
476
+ ...SHARED_KEY_RULES,
477
+ houseNumberBase: SLASH_HOUSE_NUMBER_BASE,
478
+ },
466
479
  }
467
480
 
468
481
  /**
@@ -703,6 +716,88 @@ export function directionalRelaxedKeys(key: StreetKey): StreetKey[] {
703
716
  return forms.filter((form) => form !== key) as StreetKey[]
704
717
  }
705
718
 
719
+ /**
720
+ * Canonical USPS topographic and natural-feature words that appear abbreviated mid-street before a
721
+ * thoroughfare suffix (`Little Crk Xing` → `little creek crossing`, `Oak Rdg Rd` → `oak ridge road`).
722
+ *
723
+ * This restriction to feature words keeps doubled road-suffix tails
724
+ * (`Saint Pauls PL St` → `saint pauls place`) unchanged.
725
+ */
726
+ const INTERIOR_FEATURE_CANONICALS: ReadonlySet<string> = new Set([
727
+ "beach",
728
+ "bluff",
729
+ "bluffs",
730
+ "branch",
731
+ "brook",
732
+ "brooks",
733
+ "burg",
734
+ "canyon",
735
+ "cliff",
736
+ "cliffs",
737
+ "cove",
738
+ "coves",
739
+ "creek",
740
+ "crest",
741
+ "dale",
742
+ "falls",
743
+ "field",
744
+ "fields",
745
+ "ford",
746
+ "fords",
747
+ "forest",
748
+ "fork",
749
+ "forks",
750
+ "glen",
751
+ "glens",
752
+ "grove",
753
+ "groves",
754
+ "harbor",
755
+ "harbors",
756
+ "haven",
757
+ "hill",
758
+ "hills",
759
+ "hollow",
760
+ "island",
761
+ "islands",
762
+ "knoll",
763
+ "knolls",
764
+ "lake",
765
+ "lakes",
766
+ "meadow",
767
+ "meadows",
768
+ "mill",
769
+ "mills",
770
+ "mountain",
771
+ "mountains",
772
+ "orchard",
773
+ "pine",
774
+ "pines",
775
+ "plain",
776
+ "plains",
777
+ "point",
778
+ "points",
779
+ "prairie",
780
+ "ranch",
781
+ "rapids",
782
+ "ridge",
783
+ "ridges",
784
+ "river",
785
+ "shoal",
786
+ "shoals",
787
+ "shore",
788
+ "shores",
789
+ "spring",
790
+ "springs",
791
+ "stream",
792
+ "summit",
793
+ "valley",
794
+ "valleys",
795
+ "view",
796
+ "views",
797
+ "well",
798
+ "wells",
799
+ ])
800
+
706
801
  /**
707
802
  * Lists the lookup keys to probe for a street span, most literal first, adding the
708
803
  * English respellings for a locale whose rules probe them.
@@ -733,6 +828,31 @@ export function streetKeyVariants(street: string, locale: StreetLocale): StreetK
733
828
  }
734
829
  }
735
830
 
831
+ // `normalizeStreetForKey` stops after expanding the trailing suffix, leaving abbreviated
832
+ // topographic words before it unexpanded ("Little Crk Xing" → "little crk crossing").
833
+ // Probe the interior-expanded form as a query-side variant so pre-built databases stay valid.
834
+ if (tokens.length >= MIN_TOKENS_FOR_TAIL_MERGE) {
835
+ let expandedAny = false
836
+
837
+ const expanded = tokens.map((token, i) => {
838
+ if (i === 0 || i === tokens.length - 1) return token
839
+ const canonical = US_STREET_SUFFIX_LOOKUP.get(token)?.toLowerCase()
840
+
841
+ if (!canonical || canonical === token || !INTERIOR_FEATURE_CANONICALS.has(canonical)) return token
842
+ expandedAny = true
843
+
844
+ return canonical
845
+ })
846
+
847
+ if (expandedAny) {
848
+ const candidate = expanded.join(" ") as StreetKey
849
+
850
+ if (!variants.includes(candidate)) {
851
+ variants.push(candidate)
852
+ }
853
+ }
854
+ }
855
+
736
856
  // NAD writes a numbered street with its ordinal suffix ("48th St")
737
857
  // and NYC Open Data writes the bare number ("48 ST").
738
858
  // The build keys each row as written, so the reader probes both forms.
package/lib/landmark.ts CHANGED
@@ -19,8 +19,17 @@ import { missingOutcomeTablesIn, OutcomeMembershipReader, outcomeAdmitPredicate
19
19
  import type { LandmarkOutcomeDatabase } from "#outcome/schema"
20
20
  import { prepareAll, type PreparedAll } from "#sqlite-utils"
21
21
 
22
+ /**
23
+ * One country that a border or single-country landmark spans.
24
+ */
25
+ export interface LandmarkCountryTable {
26
+ qid: string
27
+ country: string
28
+ }
29
+
22
30
  export interface LandmarkDatabase extends LandmarkOutcomeDatabase {
23
31
  landmark_name: LandmarkNameTable
32
+ landmark_country: LandmarkCountryTable
24
33
  }
25
34
 
26
35
  /**
@@ -64,6 +73,14 @@ export async function createLandmarkTables(db: Kysely<LandmarkDatabase>): Promis
64
73
  .addPrimaryKeyConstraint("landmark_name_pk", ["name_key", "qid"])
65
74
  .modifyEnd(sql`without rowid`)
66
75
  .execute()
76
+
77
+ await db.schema
78
+ .createTable("landmark_country")
79
+ .addColumn("qid", "text", (c) => c.notNull())
80
+ .addColumn("country", "text", (c) => c.notNull())
81
+ .addPrimaryKeyConstraint("landmark_country_pk", ["qid", "country"])
82
+ .modifyEnd(sql`without rowid`)
83
+ .execute()
67
84
  }
68
85
 
69
86
  /**
@@ -81,6 +98,7 @@ export class LandmarkSqliteLookup implements LandmarkLookup, Disposable {
81
98
  readonly #db: DatabaseClient<LandmarkDatabase>
82
99
 
83
100
  readonly #byName: PreparedAll<[nameKey: string], LandmarkNameTable>
101
+ readonly #countriesByQID: PreparedAll<[qid: string], Pick<LandmarkCountryTable, "country">> | null
84
102
 
85
103
  readonly #layer: string
86
104
  readonly #missingOutcomeTables: readonly string[]
@@ -94,6 +112,15 @@ export class LandmarkSqliteLookup implements LandmarkLookup, Disposable {
94
112
  this.#db = new DatabaseClient<LandmarkDatabase>(path, { readOnly: true })
95
113
 
96
114
  this.#byName = prepareAll(this.#db, LANDMARK_BY_NAME_SQL)
115
+
116
+ const hasCountryTable = Boolean(
117
+ this.#db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'landmark_country'").get()
118
+ )
119
+
120
+ this.#countriesByQID = hasCountryTable
121
+ ? prepareAll(this.#db, "SELECT country FROM landmark_country WHERE qid = ? ORDER BY country")
122
+ : null
123
+
97
124
  this.#layer = layer
98
125
  this.#missingOutcomeTables = missingOutcomeTablesIn(this.#db)
99
126
  this.#outcomes = OutcomeMembershipReader.open(this.#db, { recordColumn: "qid", layer })
@@ -107,19 +134,33 @@ export class LandmarkSqliteLookup implements LandmarkLookup, Disposable {
107
134
  find(name: string, outcome?: OutcomeQuery): LandmarkHit[] {
108
135
  const key = landmarkNameKey(name)
109
136
 
110
- if (!outcome) return landmarkHitsFromRows(this.#byName(key), name)
137
+ if (!outcome) return this.#attachCountries(landmarkHitsFromRows(this.#byName(key), name))
111
138
 
112
139
  refuseMissingOutcomeTables(`the ${this.#layer} database`, this.#missingOutcomeTables)
113
140
 
114
141
  const rows = outcome.admit ? this.#admittedRows(key, outcome.admit) : this.#byName(key)
115
142
 
116
143
  // A landmark row's defaults are keyed by its `kind`, as a candidate row's are by its placetype.
117
- return landmarkHitsFromRows(rows, name).map((hit) => ({
144
+ return this.#attachCountries(landmarkHitsFromRows(rows, name)).map((hit) => ({
118
145
  ...hit,
119
146
  outcomes: this.#outcomes!.read(hit.qid, hit.kind, outcome),
120
147
  }))
121
148
  }
122
149
 
150
+ #attachCountries(hits: LandmarkHit[]): LandmarkHit[] {
151
+ if (!this.#countriesByQID || !hits.length) return hits
152
+
153
+ return hits.map((hit) => {
154
+ const stored = this.#countriesByQID!(hit.qid).map((row) => row.country)
155
+
156
+ if (!stored.length) return hit
157
+
158
+ const ordered = hit.country ? [hit.country, ...stored.filter((code) => code !== hit.country)] : stored
159
+
160
+ return { ...hit, countries: ordered }
161
+ })
162
+ }
163
+
123
164
  missingOutcomeTables(): readonly string[] {
124
165
  return this.#missingOutcomeTables
125
166
  }
package/lib/poi/lookup.ts CHANGED
@@ -19,6 +19,7 @@ import type { DatabaseClient } from "@mailwoman/sqlite/client"
19
19
  import { SQLiteLookup, type SQLiteLookupOptions } from "@mailwoman/sqlite/lookup"
20
20
  import { gridDisk, latLngToCell } from "@sister.software/h3"
21
21
 
22
+ import { normalizeLocalityForKey } from "#labels/street/normalize"
22
23
  import type { POICategoryCodeTable, POIDatabase, POITable } from "#poi/schema"
23
24
  /**
24
25
  * Resolution the `poi` table's `h3_cell` column is keyed at, matching the builder (spec §3.4).
@@ -53,6 +54,23 @@ const BRAND_MAX_DISTANCE_KM = 500
53
54
  */
54
55
  const DEFAULT_LIMIT = 20
55
56
 
57
+ /**
58
+ * Minimum candidate rows fetched from FTS5 before country filtering, distance sorting, and final slicing.
59
+ */
60
+ const FTS_NAME_CANDIDATE_FLOOR = 250
61
+
62
+ /**
63
+ * Multiplier applied to `limit` for FTS5 candidate fetches.
64
+ *
65
+ * Keeps local hits from large chains and cross-country namesakes before sorting.
66
+ */
67
+ const FTS_NAME_CANDIDATE_FACTOR = 8
68
+
69
+ /**
70
+ * Maximum `name_key` values bound in one `IN (...)` hydration statement.
71
+ */
72
+ const HYDRATE_KEY_CHUNK_SIZE = 400
73
+
56
74
  export interface POISearchQuery {
57
75
  /**
58
76
  * Poi-taxonomy category ids (string side of the dictionary) to search.
@@ -72,9 +90,13 @@ export interface POISearchQuery {
72
90
  */
73
91
  brandWikidata?: string
74
92
  /**
75
- * Free-text name (FTS5).
93
+ * Free-text name (exact `name_key` index plus FTS5 fallback).
76
94
  */
77
95
  name?: string
96
+ /**
97
+ * ISO 3166-1 alpha-2 country code filter applied before sorting and slicing.
98
+ */
99
+ country?: string | null
78
100
  /**
79
101
  * Search center.
80
102
  *
@@ -136,7 +158,9 @@ type POIRow = Pick<
136
158
  | "confidence"
137
159
  | "name_key"
138
160
  | "gers_id"
139
- >
161
+ > & {
162
+ street?: string | null
163
+ }
140
164
 
141
165
  /**
142
166
  * Node reader over `poi.db`.
@@ -144,6 +168,8 @@ type POIRow = Pick<
144
168
  export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLookup<DB> {
145
169
  readonly #categoryToID = new Map<string, number>()
146
170
  readonly #idToCategory = new Map<number, string>()
171
+ readonly #hasStreet: boolean
172
+ readonly #columns: string
147
173
 
148
174
  /**
149
175
  * `(h3_cell, category_id)` → the cell's category-clustered range, most-confident-first.
@@ -154,6 +180,14 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
154
180
  * The sort happens in JS.
155
181
  */
156
182
  readonly #brandProbe: ReturnType<DatabaseClient["prepare"]>
183
+ /**
184
+ * Exact `name_key` lookup over the `poi_name_key` B-tree index.
185
+ */
186
+ readonly #exactNameProbe: ReturnType<DatabaseClient["prepare"]>
187
+ /**
188
+ * Exact `name_key` lookup scoped to one ISO country code.
189
+ */
190
+ readonly #exactNameCountryProbe: ReturnType<DatabaseClient["prepare"]>
157
191
  /**
158
192
  * FTS5 `match` over `poi_search`, returning candidate `name_key`s to hydrate.
159
193
  */
@@ -171,13 +205,25 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
171
205
  this.#idToCategory.set(Number(r.id), String(r.category))
172
206
  }
173
207
 
174
- const columns = "name, category_id, brand_wikidata, latitude, longitude, country, confidence, name_key, gers_id"
208
+ // Older sealed `poi.db` artifacts predate the `street` column, so detect it once at open time.
209
+ const tableColumns = allRows<{ name: string }>(this.database.prepare("PRAGMA table_info(poi)"))
210
+ this.#hasStreet = tableColumns.some((column) => column.name === "street")
211
+
212
+ this.#columns = this.#hasStreet
213
+ ? "name, category_id, brand_wikidata, latitude, longitude, country, confidence, name_key, gers_id, street"
214
+ : "name, category_id, brand_wikidata, latitude, longitude, country, confidence, name_key, gers_id"
175
215
 
176
216
  this.#categoryCellProbe = this.database.prepare(
177
- `SELECT ${columns} FROM poi WHERE h3_cell = ? AND category_id = ? ORDER BY neg_rank ASC LIMIT ?`
217
+ `SELECT ${this.#columns} FROM poi WHERE h3_cell = ? AND category_id = ? ORDER BY neg_rank ASC LIMIT ?`
178
218
  )
179
219
 
180
- this.#brandProbe = this.database.prepare(`SELECT ${columns} FROM poi WHERE brand_wikidata = ?`)
220
+ this.#brandProbe = this.database.prepare(`SELECT ${this.#columns} FROM poi WHERE brand_wikidata = ?`)
221
+
222
+ this.#exactNameProbe = this.database.prepare(`SELECT ${this.#columns} FROM poi WHERE name_key = ?`)
223
+
224
+ this.#exactNameCountryProbe = this.database.prepare(
225
+ `SELECT ${this.#columns} FROM poi WHERE name_key = ? AND country = ?`
226
+ )
181
227
 
182
228
  this.#nameFTSProbe = this.database.prepare(
183
229
  "SELECT name_key FROM poi_search WHERE poi_search MATCH ? ORDER BY bm25(poi_search) LIMIT ?"
@@ -186,9 +232,10 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
186
232
 
187
233
  search(query: POISearchQuery): POISearchHit[] {
188
234
  const limit = Math.max(1, query.limit ?? DEFAULT_LIMIT)
235
+ const country = query.country?.trim() ? query.country.trim().toUpperCase() : null
189
236
 
190
237
  if (query.name) {
191
- return this.#searchByName(query.name, limit, query.center ?? undefined)
238
+ return this.#searchByName(query.name, limit, query.center ?? undefined, country)
192
239
  }
193
240
 
194
241
  if (query.categoryIDs?.length || query.brandWikidata) {
@@ -197,10 +244,10 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
197
244
  }
198
245
 
199
246
  if (query.brandWikidata) {
200
- return this.#searchBrand(query.brandWikidata, query.center, limit)
247
+ return this.#searchBrand(query.brandWikidata, query.center, limit, country)
201
248
  }
202
249
 
203
- return this.#searchKRing(query, limit)
250
+ return this.#searchKRing(query, limit, country)
204
251
  }
205
252
 
206
253
  return []
@@ -216,21 +263,28 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
216
263
  * The lookup drops rows past {@link BRAND_MAX_DISTANCE_KM}.
217
264
  * It returns the nearest `limit` rows.
218
265
  */
219
- #searchBrand(brandWikidata: string, center: { latitude: number; longitude: number }, limit: number): POISearchHit[] {
266
+ #searchBrand(
267
+ brandWikidata: string,
268
+ center: { latitude: number; longitude: number },
269
+ limit: number,
270
+ country: string | null
271
+ ): POISearchHit[] {
220
272
  const rows = allRows<POIRow>(this.#brandProbe, brandWikidata)
221
273
 
222
274
  return sortByDistance(rows, center)
223
275
  .filter(
224
- (row) => haversine(center.latitude, center.longitude, row.latitude, row.longitude) <= BRAND_MAX_DISTANCE_KM
276
+ (row) =>
277
+ (!country || row.country === country) &&
278
+ haversine(center.latitude, center.longitude, row.latitude, row.longitude) <= BRAND_MAX_DISTANCE_KM
225
279
  )
226
280
  .slice(0, limit)
227
- .map((row) => toHit(row, this.#idToCategory, center))
281
+ .map((row) => toHit(row, this.#idToCategory, center, this.#hasStreet))
228
282
  }
229
283
 
230
284
  /**
231
285
  * Category path: k-ring expansion from `query.center`'s res-9 cell, probing each new ring's cells.
232
286
  */
233
- #searchKRing(query: POISearchQuery, limit: number): POISearchHit[] {
287
+ #searchKRing(query: POISearchQuery, limit: number, country: string | null): POISearchHit[] {
234
288
  const center = query.center!
235
289
  const maxRings = query.maxRings ?? DEFAULT_MAX_RINGS
236
290
  const categoryIDs: number[] = []
@@ -265,7 +319,9 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
265
319
  const shortCell = shortCellToInt(cell)
266
320
 
267
321
  for (const categoryID of categoryIDs) {
268
- rows.push(...allRows<POIRow>(this.#categoryCellProbe, shortCell, categoryID, limit))
322
+ const cellRows = allRows<POIRow>(this.#categoryCellProbe, shortCell, categoryID, limit)
323
+
324
+ rows.push(...(country ? cellRows.filter((row) => row.country === country) : cellRows))
269
325
  }
270
326
  }
271
327
 
@@ -274,75 +330,109 @@ export class POILookup<DB extends POIDatabase = POIDatabase> extends SQLiteLooku
274
330
  if (rows.length >= limit) break
275
331
  }
276
332
 
277
- return rows.slice(0, limit).map((row) => toHit(row, this.#idToCategory, center))
333
+ return rows.slice(0, limit).map((row) => toHit(row, this.#idToCategory, center, this.#hasStreet))
278
334
  }
279
335
 
280
336
  /**
281
- * Name path: FTS5 match → hydrate by name_key.
337
+ * Name path: exact `name_key` B-tree lookup plus expanded FTS5 match fallback.
282
338
  *
283
- * No center is required.
284
- * Hits are distance-sorted when one is given.
339
+ * Exact rows hydrate directly over `poi_name_key` before any limit applies,
340
+ * so large chains and cross-country namesakes keep their local match.
341
+ * FTS5 adds decorated and partial-name candidates using an expanded candidate window.
285
342
  *
286
- * Hydration is one batched `where name_key IN (...)` query over the unique `name_key`s
287
- * of the FTS hits, since a per-hit probe would be up to `limit` full table scans.
343
+ * Country filtering and optional distance sorting run over the hydrated union before slicing to `limit`.
288
344
  */
289
- #searchByName(name: string, limit: number, center?: { latitude: number; longitude: number }): POISearchHit[] {
345
+ #searchByName(
346
+ name: string,
347
+ limit: number,
348
+ center: { latitude: number; longitude: number } | undefined,
349
+ country: string | null
350
+ ): POISearchHit[] {
351
+ const exactKey = normalizeLocalityForKey(name)
290
352
  const matchQuery = sanitizePOINameQuery(name)
291
353
 
292
- if (!matchQuery) return []
354
+ if (!exactKey && !matchQuery) return []
293
355
 
294
- const ftsHits = allRows<{ name_key: string | null }>(this.#nameFTSProbe, matchQuery, limit)
295
- const uniqueKeys: string[] = []
296
- const seenKeys = new Set<string>()
356
+ const exactRows = exactKey
357
+ ? country
358
+ ? allRows<POIRow>(this.#exactNameCountryProbe, exactKey, country)
359
+ : allRows<POIRow>(this.#exactNameProbe, exactKey)
360
+ : []
297
361
 
298
- for (const hit of ftsHits) {
299
- if (!hit.name_key || seenKeys.has(hit.name_key)) continue
300
- seenKeys.add(hit.name_key)
301
- uniqueKeys.push(hit.name_key)
302
- }
362
+ const ftsRows: POIRow[] = []
363
+
364
+ if (matchQuery) {
365
+ const candidateLimit = Math.max(limit * FTS_NAME_CANDIDATE_FACTOR, FTS_NAME_CANDIDATE_FLOOR)
366
+ const ftsHits = allRows<{ name_key: string | null }>(this.#nameFTSProbe, matchQuery, candidateLimit)
367
+ const uniqueKeys: string[] = []
368
+ const seenKeys = new Set<string>(exactKey ? [exactKey] : [])
303
369
 
304
- if (!uniqueKeys.length) return []
370
+ for (const hit of ftsHits) {
371
+ if (!hit.name_key || seenKeys.has(hit.name_key)) continue
372
+ seenKeys.add(hit.name_key)
373
+ uniqueKeys.push(hit.name_key)
374
+ }
305
375
 
306
- const hydrated = this.#hydrateByNameKeys(uniqueKeys)
307
- const rowsByKey = new Map<string, POIRow[]>()
376
+ if (uniqueKeys.length) {
377
+ const hydrated = this.#hydrateByNameKeys(uniqueKeys, country)
378
+ const rowsByKey = new Map<string, POIRow[]>()
308
379
 
309
- for (const row of hydrated) {
310
- if (row.name_key === null) continue
311
- const bucket = rowsByKey.get(row.name_key)
380
+ for (const row of hydrated) {
381
+ if (row.name_key === null) continue
382
+ const bucket = rowsByKey.get(row.name_key)
312
383
 
313
- if (bucket) {
314
- bucket.push(row)
315
- } else {
316
- rowsByKey.set(row.name_key, [row])
384
+ if (bucket) {
385
+ bucket.push(row)
386
+ } else {
387
+ rowsByKey.set(row.name_key, [row])
388
+ }
389
+ }
390
+
391
+ for (const key of uniqueKeys) {
392
+ ftsRows.push(...(rowsByKey.get(key) ?? []))
393
+ }
317
394
  }
318
395
  }
319
396
 
320
- let rows: POIRow[] = []
397
+ let rows: POIRow[] = [...exactRows, ...ftsRows]
321
398
 
322
- for (const key of uniqueKeys) {
323
- rows.push(...(rowsByKey.get(key) ?? []))
324
- }
399
+ if (!rows.length) return []
325
400
 
326
401
  if (center) {
327
402
  rows = sortByDistance(rows, center)
328
403
  }
329
404
 
330
- return rows.slice(0, limit).map((row) => toHit(row, this.#idToCategory, center))
405
+ return rows.slice(0, limit).map((row) => toHit(row, this.#idToCategory, center, this.#hasStreet))
331
406
  }
332
407
 
333
408
  /**
334
409
  * Batched hydration for the FTS name path: `where name_key IN (?, ?, …)`,
335
- * one query for the whole batch instead of one probe per FTS hit.
410
+ * one query per chunk instead of one probe per FTS hit.
336
411
  *
337
412
  * This is a cold path (name search only) with variable arity per call,
338
- * so the statement is prepared fresh each time rather than cached.
413
+ * so each statement is prepared fresh rather than cached.
339
414
  */
340
- #hydrateByNameKeys(nameKeys: string[]): POIRow[] {
341
- const columns = "name, category_id, brand_wikidata, latitude, longitude, country, confidence, name_key, gers_id"
342
- const placeholders = nameKeys.map(() => "?").join(", ")
343
- const stmt = this.database.prepare(`SELECT ${columns} FROM poi WHERE name_key IN (${placeholders})`)
415
+ #hydrateByNameKeys(nameKeys: string[], country: string | null): POIRow[] {
416
+ const results: POIRow[] = []
417
+
418
+ for (let offset = 0; offset < nameKeys.length; offset += HYDRATE_KEY_CHUNK_SIZE) {
419
+ const chunk = nameKeys.slice(offset, offset + HYDRATE_KEY_CHUNK_SIZE)
420
+ const placeholders = chunk.map(() => "?").join(", ")
421
+
422
+ if (country) {
423
+ const stmt = this.database.prepare(
424
+ `SELECT ${this.#columns} FROM poi WHERE name_key IN (${placeholders}) AND country = ?`
425
+ )
426
+
427
+ results.push(...allRows<POIRow>(stmt, ...chunk, country))
428
+ } else {
429
+ const stmt = this.database.prepare(`SELECT ${this.#columns} FROM poi WHERE name_key IN (${placeholders})`)
430
+
431
+ results.push(...allRows<POIRow>(stmt, ...chunk))
432
+ }
433
+ }
344
434
 
345
- return allRows<POIRow>(stmt, ...nameKeys)
435
+ return results
346
436
  }
347
437
  }
348
438
 
@@ -357,7 +447,8 @@ function sortByDistance(rows: POIRow[], center: { latitude: number; longitude: n
357
447
  function toHit(
358
448
  row: POIRow,
359
449
  idToCategory: ReadonlyMap<number, string>,
360
- center?: { latitude: number; longitude: number }
450
+ center: { latitude: number; longitude: number } | undefined,
451
+ hasStreet: boolean
361
452
  ): POISearchHit {
362
453
  return {
363
454
  name: row.name,
@@ -369,6 +460,7 @@ function toHit(
369
460
  confidence: row.confidence,
370
461
  gersID: row.gers_id,
371
462
  distanceM: center ? haversine(center.latitude, center.longitude, row.latitude, row.longitude) * 1000 : null,
463
+ ...(hasStreet ? { street: row.street ?? null } : {}),
372
464
  }
373
465
  }
374
466
 
package/lib/poi/schema.ts CHANGED
@@ -20,7 +20,7 @@
20
20
 
21
21
  import type { layerschemadatabase } from "@mailwoman/core/layers"
22
22
  import type { DatabaseClient } from "@mailwoman/sqlite/client"
23
- import { sql, type Kysely } from "kysely"
23
+ import { type ColumnType, sql, type Kysely } from "kysely"
24
24
 
25
25
  import type { NameKey } from "#labels/street/normalize"
26
26
  import type { OutcomeDatabase } from "#outcome/schema"
@@ -73,6 +73,10 @@ export interface POITable {
73
73
  * Nullable metadata, never a key.
74
74
  */
75
75
  gers_id: string | null
76
+ /**
77
+ * Freeform street line from the source address, or null when absent.
78
+ */
79
+ street: ColumnType<string | null, string | null | undefined, string | null>
76
80
  }
77
81
 
78
82
  /**
@@ -95,6 +99,7 @@ export interface POIStageTable {
95
99
  country: string | null
96
100
  confidence: number | null
97
101
  gers_id: string | null
102
+ street: ColumnType<string | null, string | null | undefined, string | null>
98
103
  }
99
104
 
100
105
  /**
@@ -127,6 +132,7 @@ export const POI_COLUMNS = [
127
132
  "country",
128
133
  "confidence",
129
134
  "gers_id",
135
+ "street",
130
136
  ] as const
131
137
 
132
138
  export async function createPOIStagingTables(db: Kysely<POIDatabase>): Promise<void> {
@@ -150,6 +156,7 @@ export async function createPOIStagingTables(db: Kysely<POIDatabase>): Promise<v
150
156
  .addColumn("country", "text")
151
157
  .addColumn("confidence", "real")
152
158
  .addColumn("gers_id", "text")
159
+ .addColumn("street", "text")
153
160
  .execute()
154
161
  }
155
162
 
@@ -168,6 +175,7 @@ export async function createPOITable(db: Kysely<POIDatabase>): Promise<void> {
168
175
  .addColumn("country", "text", (c) => c.notNull())
169
176
  .addColumn("confidence", "real", (c) => c.notNull())
170
177
  .addColumn("gers_id", "text")
178
+ .addColumn("street", "text")
171
179
  .addPrimaryKeyConstraint("poi_pk", ["h3_cell", "category_id", "neg_rank", "rowid_key"])
172
180
  // `without rowid` has no first-class builder. The raw modifier is the idiomatic fallback.
173
181
  .modifyEnd(sql`without rowid`)
@@ -26,7 +26,7 @@ import { repoRootPath, repoRootPathBuilder, workspacePathBuilder } from "@mailwo
26
26
  import { readReleaseConfig, repoCommittedSoftFeedSources } from "@mailwoman/core/repo/release-config"
27
27
  import { spawnProcessSync } from "@mailwoman/core/scripting/process"
28
28
  import { parseJSONStrict } from "@mailwoman/core/values/json"
29
- import type { PathBuilder, PathBuilderLike } from "path-ts"
29
+ import { basename, type PathBuilder, type PathBuilderLike } from "path-ts"
30
30
  import { Globerator } from "spliterator/node/fs"
31
31
 
32
32
  import { $public } from "#env"
@@ -569,7 +569,11 @@ export async function committedSoftFeedLinks(): Promise<{
569
569
  )
570
570
  }
571
571
 
572
- const streetType = link("street-type-lexicon-v3.json", "the street_type channel will resolve OFF in this worktree.")
572
+ const streetTypeName = config.softFeed?.streetTypeLexicon
573
+ ? basename(config.softFeed.streetTypeLexicon)
574
+ : "street-type-lexicon-v3.json"
575
+
576
+ const streetType = link(streetTypeName, "the street_type channel will resolve OFF in this worktree.")
573
577
 
574
578
  // The base graph's confidence calibration tables, committed in en-us and shipped by both Latin bases.
575
579
  const calibration = ["calibration.json", "calibration-per-locale.json"].map((name) => ({