1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2023 by the Nominatim developer community.
6 # For a full list of authors see the git log.
8 Implementation of the acutal database accesses for forward search.
10 from typing import List, Tuple, AsyncIterator, Dict, Any, Callable
13 import sqlalchemy as sa
14 from sqlalchemy.dialects.postgresql import ARRAY, array_agg
16 from nominatim.typing import SaFromClause, SaScalarSelect, SaColumn, \
17 SaExpression, SaSelect, SaLambdaSelect, SaRow, SaBind
18 from nominatim.api.connection import SearchConnection
19 from nominatim.api.types import SearchDetails, DataLayer, GeometryFormat, Bbox
20 import nominatim.api.results as nres
21 from nominatim.api.search.db_search_fields import SearchData, WeightedCategories
22 from nominatim.db.sqlalchemy_types import Geometry
24 #pylint: disable=singleton-comparison,not-callable
25 #pylint: disable=too-many-branches,too-many-arguments,too-many-locals,too-many-statements
27 def _details_to_bind_params(details: SearchDetails) -> Dict[str, Any]:
28 """ Create a dictionary from search parameters that can be used
29 as bind parameter for SQL execute.
31 return {'limit': details.max_results,
32 'min_rank': details.min_rank,
33 'max_rank': details.max_rank,
34 'viewbox': details.viewbox,
35 'viewbox2': details.viewbox_x2,
37 'near_radius': details.near_radius,
38 'excluded': details.excluded,
39 'countries': details.countries}
42 LIMIT_PARAM: SaBind = sa.bindparam('limit')
43 MIN_RANK_PARAM: SaBind = sa.bindparam('min_rank')
44 MAX_RANK_PARAM: SaBind = sa.bindparam('max_rank')
45 VIEWBOX_PARAM: SaBind = sa.bindparam('viewbox', type_=Geometry)
46 VIEWBOX2_PARAM: SaBind = sa.bindparam('viewbox2', type_=Geometry)
47 NEAR_PARAM: SaBind = sa.bindparam('near', type_=Geometry)
48 NEAR_RADIUS_PARAM: SaBind = sa.bindparam('near_radius')
49 COUNTRIES_PARAM: SaBind = sa.bindparam('countries')
51 def _within_near(t: SaFromClause) -> Callable[[], SaExpression]:
52 return lambda: t.c.geometry.ST_DWithin(NEAR_PARAM, NEAR_RADIUS_PARAM)
54 def _exclude_places(t: SaFromClause) -> Callable[[], SaExpression]:
55 return lambda: t.c.place_id.not_in(sa.bindparam('excluded'))
57 def _select_placex(t: SaFromClause) -> SaSelect:
58 return sa.select(t.c.place_id, t.c.osm_type, t.c.osm_id, t.c.name,
60 t.c.address, t.c.extratags,
61 t.c.housenumber, t.c.postcode, t.c.country_code,
62 t.c.importance, t.c.wikipedia,
63 t.c.parent_place_id, t.c.rank_address, t.c.rank_search,
65 t.c.geometry.ST_Expand(0).label('bbox'))
68 def _add_geometry_columns(sql: SaLambdaSelect, col: SaColumn, details: SearchDetails) -> SaSelect:
71 if details.geometry_simplification > 0.0:
72 col = sa.func.ST_SimplifyPreserveTopology(col, details.geometry_simplification)
74 if details.geometry_output & GeometryFormat.GEOJSON:
75 out.append(sa.func.ST_AsGeoJSON(col).label('geometry_geojson'))
76 if details.geometry_output & GeometryFormat.TEXT:
77 out.append(sa.func.ST_AsText(col).label('geometry_text'))
78 if details.geometry_output & GeometryFormat.KML:
79 out.append(sa.func.ST_AsKML(col).label('geometry_kml'))
80 if details.geometry_output & GeometryFormat.SVG:
81 out.append(sa.func.ST_AsSVG(col).label('geometry_svg'))
83 return sql.add_columns(*out)
86 def _make_interpolation_subquery(table: SaFromClause, inner: SaFromClause,
87 numerals: List[int], details: SearchDetails) -> SaScalarSelect:
88 all_ids = array_agg(table.c.place_id) # type: ignore[no-untyped-call]
89 sql = sa.select(all_ids).where(table.c.parent_place_id == inner.c.place_id)
91 if len(numerals) == 1:
92 sql = sql.where(sa.between(numerals[0], table.c.startnumber, table.c.endnumber))\
93 .where((numerals[0] - table.c.startnumber) % table.c.step == 0)
95 sql = sql.where(sa.or_(
96 *(sa.and_(sa.between(n, table.c.startnumber, table.c.endnumber),
97 (n - table.c.startnumber) % table.c.step == 0)
101 sql = sql.where(_exclude_places(table))
103 return sql.scalar_subquery()
106 def _filter_by_layer(table: SaFromClause, layers: DataLayer) -> SaColumn:
107 orexpr: List[SaExpression] = []
108 if layers & DataLayer.ADDRESS and layers & DataLayer.POI:
109 orexpr.append(table.c.rank_address.between(1, 30))
110 elif layers & DataLayer.ADDRESS:
111 orexpr.append(table.c.rank_address.between(1, 29))
112 orexpr.append(sa.and_(table.c.rank_address == 30,
113 sa.or_(table.c.housenumber != None,
114 table.c.address.has_key('housename'))))
115 elif layers & DataLayer.POI:
116 orexpr.append(sa.and_(table.c.rank_address == 30,
117 table.c.class_.not_in(('place', 'building'))))
119 if layers & DataLayer.MANMADE:
121 if not layers & DataLayer.RAILWAY:
122 exclude.append('railway')
123 if not layers & DataLayer.NATURAL:
124 exclude.extend(('natural', 'water', 'waterway'))
125 orexpr.append(sa.and_(table.c.class_.not_in(tuple(exclude)),
126 table.c.rank_address == 0))
129 if layers & DataLayer.RAILWAY:
130 include.append('railway')
131 if layers & DataLayer.NATURAL:
132 include.extend(('natural', 'water', 'waterway'))
133 orexpr.append(sa.and_(table.c.class_.in_(tuple(include)),
134 table.c.rank_address == 0))
139 return sa.or_(*orexpr)
142 def _interpolated_position(table: SaFromClause, nr: SaColumn) -> SaColumn:
143 pos = sa.cast(nr - table.c.startnumber, sa.Float) / (table.c.endnumber - table.c.startnumber)
145 (table.c.endnumber == table.c.startnumber, table.c.linegeo.ST_Centroid()),
146 else_=table.c.linegeo.ST_LineInterpolatePoint(pos)).label('centroid')
149 async def _get_placex_housenumbers(conn: SearchConnection,
150 place_ids: List[int],
151 details: SearchDetails) -> AsyncIterator[nres.SearchResult]:
153 sql = _select_placex(t).where(t.c.place_id.in_(place_ids))
155 if details.geometry_output:
156 sql = _add_geometry_columns(sql, t.c.geometry, details)
158 for row in await conn.execute(sql):
159 result = nres.create_from_placex_row(row, nres.SearchResult)
161 result.bbox = Bbox.from_wkb(row.bbox)
165 async def _get_osmline(conn: SearchConnection, place_ids: List[int],
167 details: SearchDetails) -> AsyncIterator[nres.SearchResult]:
169 values = sa.values(sa.Column('nr', sa.Integer()), name='housenumber')\
170 .data([(n,) for n in numerals])
171 sql = sa.select(t.c.place_id, t.c.osm_id,
172 t.c.parent_place_id, t.c.address,
173 values.c.nr.label('housenumber'),
174 _interpolated_position(t, values.c.nr),
175 t.c.postcode, t.c.country_code)\
176 .where(t.c.place_id.in_(place_ids))\
177 .join(values, values.c.nr.between(t.c.startnumber, t.c.endnumber))
179 if details.geometry_output:
181 sql = _add_geometry_columns(sa.select(sub), sub.c.centroid, details)
183 for row in await conn.execute(sql):
184 result = nres.create_from_osmline_row(row, nres.SearchResult)
189 async def _get_tiger(conn: SearchConnection, place_ids: List[int],
190 numerals: List[int], osm_id: int,
191 details: SearchDetails) -> AsyncIterator[nres.SearchResult]:
193 values = sa.values(sa.Column('nr', sa.Integer()), name='housenumber')\
194 .data([(n,) for n in numerals])
195 sql = sa.select(t.c.place_id, t.c.parent_place_id,
196 sa.literal('W').label('osm_type'),
197 sa.literal(osm_id).label('osm_id'),
198 values.c.nr.label('housenumber'),
199 _interpolated_position(t, values.c.nr),
201 .where(t.c.place_id.in_(place_ids))\
202 .join(values, values.c.nr.between(t.c.startnumber, t.c.endnumber))
204 if details.geometry_output:
206 sql = _add_geometry_columns(sa.select(sub), sub.c.centroid, details)
208 for row in await conn.execute(sql):
209 result = nres.create_from_tiger_row(row, nres.SearchResult)
214 class AbstractSearch(abc.ABC):
215 """ Encapuslation of a single lookup in the database.
218 def __init__(self, penalty: float) -> None:
219 self.penalty = penalty
222 async def lookup(self, conn: SearchConnection,
223 details: SearchDetails) -> nres.SearchResults:
224 """ Find results for the search in the database.
228 class NearSearch(AbstractSearch):
229 """ Category search of a place type near the result of another search.
231 def __init__(self, penalty: float, categories: WeightedCategories,
232 search: AbstractSearch) -> None:
233 super().__init__(penalty)
235 self.categories = categories
238 async def lookup(self, conn: SearchConnection,
239 details: SearchDetails) -> nres.SearchResults:
240 """ Find results for the search in the database.
242 results = nres.SearchResults()
243 base = await self.search.lookup(conn, details)
248 base.sort(key=lambda r: (r.accuracy, r.rank_search))
249 max_accuracy = base[0].accuracy + 0.5
250 base = nres.SearchResults(r for r in base if r.source_table == nres.SourceTable.PLACEX
251 and r.accuracy <= max_accuracy
252 and r.bbox and r.bbox.area < 20)
255 baseids = [b.place_id for b in base[:5] if b.place_id]
257 for category, penalty in self.categories:
258 await self.lookup_category(results, conn, baseids, category, penalty, details)
259 if len(results) >= details.max_results:
265 async def lookup_category(self, results: nres.SearchResults,
266 conn: SearchConnection, ids: List[int],
267 category: Tuple[str, str], penalty: float,
268 details: SearchDetails) -> None:
269 """ Find places of the given category near the list of
270 place ids and add the results to 'results'.
272 table = await conn.get_class_table(*category)
274 t = conn.t.placex.alias('p')
275 tgeom = conn.t.placex.alias('pgeom')
277 sql = _select_placex(t).where(tgeom.c.place_id.in_(ids))\
278 .where(t.c.class_ == category[0])\
279 .where(t.c.type == category[1])
282 # No classtype table available, do a simplified lookup in placex.
283 sql = sql.join(tgeom, t.c.geometry.ST_DWithin(tgeom.c.centroid, 0.01))\
284 .order_by(tgeom.c.centroid.ST_Distance(t.c.centroid))
286 # Use classtype table. We can afford to use a larger
287 # radius for the lookup.
288 sql = sql.join(table, t.c.place_id == table.c.place_id)\
290 sa.case((sa.and_(tgeom.c.rank_address < 9,
291 tgeom.c.geometry.is_area()),
292 tgeom.c.geometry.ST_Contains(table.c.centroid)),
293 else_ = tgeom.c.centroid.ST_DWithin(table.c.centroid, 0.05)))\
294 .order_by(tgeom.c.centroid.ST_Distance(table.c.centroid))
296 sql = sql.where(t.c.rank_address.between(MIN_RANK_PARAM, MAX_RANK_PARAM))
297 if details.countries:
298 sql = sql.where(t.c.country_code.in_(COUNTRIES_PARAM))
300 sql = sql.where(_exclude_places(t))
301 if details.layers is not None:
302 sql = sql.where(_filter_by_layer(t, details.layers))
304 sql = sql.limit(LIMIT_PARAM)
305 for row in await conn.execute(sql, _details_to_bind_params(details)):
306 result = nres.create_from_placex_row(row, nres.SearchResult)
308 result.accuracy = self.penalty + penalty
309 result.bbox = Bbox.from_wkb(row.bbox)
310 results.append(result)
314 class PoiSearch(AbstractSearch):
315 """ Category search in a geographic area.
317 def __init__(self, sdata: SearchData) -> None:
318 super().__init__(sdata.penalty)
319 self.categories = sdata.qualifiers
320 self.countries = sdata.countries
323 async def lookup(self, conn: SearchConnection,
324 details: SearchDetails) -> nres.SearchResults:
325 """ Find results for the search in the database.
327 bind_params = _details_to_bind_params(details)
330 rows: List[SaRow] = []
332 if details.near and details.near_radius is not None and details.near_radius < 0.2:
333 # simply search in placex table
334 def _base_query() -> SaSelect:
335 return _select_placex(t) \
336 .where(t.c.linked_place_id == None) \
337 .where(t.c.geometry.ST_DWithin(NEAR_PARAM, NEAR_RADIUS_PARAM)) \
338 .order_by(t.c.centroid.ST_Distance(NEAR_PARAM)) \
341 classtype = self.categories.values
342 if len(classtype) == 1:
343 cclass, ctype = classtype[0]
344 sql: SaLambdaSelect = sa.lambda_stmt(lambda: _base_query()
345 .where(t.c.class_ == cclass)
346 .where(t.c.type == ctype))
348 sql = _base_query().where(sa.or_(*(sa.and_(t.c.class_ == cls, t.c.type == typ)
349 for cls, typ in classtype)))
352 sql = sql.where(t.c.country_code.in_(self.countries.values))
354 if details.viewbox is not None and details.bounded_viewbox:
355 sql = sql.where(t.c.geometry.intersects(VIEWBOX_PARAM))
357 rows.extend(await conn.execute(sql, bind_params))
359 # use the class type tables
360 for category in self.categories.values:
361 table = await conn.get_class_table(*category)
362 if table is not None:
363 sql = _select_placex(t)\
364 .join(table, t.c.place_id == table.c.place_id)\
365 .where(t.c.class_ == category[0])\
366 .where(t.c.type == category[1])
368 if details.viewbox is not None and details.bounded_viewbox:
369 sql = sql.where(table.c.centroid.intersects(VIEWBOX_PARAM))
371 if details.near and details.near_radius is not None:
372 sql = sql.order_by(table.c.centroid.ST_Distance(NEAR_PARAM))\
373 .where(table.c.centroid.ST_DWithin(NEAR_PARAM,
377 sql = sql.where(t.c.country_code.in_(self.countries.values))
379 sql = sql.limit(LIMIT_PARAM)
380 rows.extend(await conn.execute(sql, bind_params))
382 results = nres.SearchResults()
384 result = nres.create_from_placex_row(row, nres.SearchResult)
386 result.accuracy = self.penalty + self.categories.get_penalty((row.class_, row.type))
387 result.bbox = Bbox.from_wkb(row.bbox)
388 results.append(result)
393 class CountrySearch(AbstractSearch):
394 """ Search for a country name or country code.
396 def __init__(self, sdata: SearchData) -> None:
397 super().__init__(sdata.penalty)
398 self.countries = sdata.countries
401 async def lookup(self, conn: SearchConnection,
402 details: SearchDetails) -> nres.SearchResults:
403 """ Find results for the search in the database.
407 ccodes = self.countries.values
408 sql: SaLambdaSelect = sa.lambda_stmt(lambda: _select_placex(t)\
409 .where(t.c.country_code.in_(ccodes))\
410 .where(t.c.rank_address == 4))
412 if details.geometry_output:
413 sql = _add_geometry_columns(sql, t.c.geometry, details)
416 sql = sql.where(_exclude_places(t))
418 if details.viewbox is not None and details.bounded_viewbox:
419 sql = sql.where(lambda: t.c.geometry.intersects(VIEWBOX_PARAM))
421 if details.near is not None and details.near_radius is not None:
422 sql = sql.where(_within_near(t))
424 results = nres.SearchResults()
425 for row in await conn.execute(sql, _details_to_bind_params(details)):
426 result = nres.create_from_placex_row(row, nres.SearchResult)
428 result.accuracy = self.penalty + self.countries.get_penalty(row.country_code, 5.0)
429 results.append(result)
431 return results or await self.lookup_in_country_table(conn, details)
434 async def lookup_in_country_table(self, conn: SearchConnection,
435 details: SearchDetails) -> nres.SearchResults:
436 """ Look up the country in the fallback country tables.
438 # Avoid the fallback search when this is a more search. Country results
439 # usually are in the first batch of results and it is not possible
440 # to exclude these fallbacks.
442 return nres.SearchResults()
444 t = conn.t.country_name
445 tgrid = conn.t.country_grid
447 sql = sa.select(tgrid.c.country_code,
448 tgrid.c.geometry.ST_Centroid().ST_Collect().ST_Centroid()
450 .where(tgrid.c.country_code.in_(self.countries.values))\
451 .group_by(tgrid.c.country_code)
453 if details.viewbox is not None and details.bounded_viewbox:
454 sql = sql.where(tgrid.c.geometry.intersects(VIEWBOX_PARAM))
455 if details.near is not None and details.near_radius is not None:
456 sql = sql.where(_within_near(tgrid))
458 sub = sql.subquery('grid')
460 sql = sa.select(t.c.country_code,
462 + sa.func.coalesce(t.c.derived_name,
463 sa.cast('', type_=conn.t.types.Composite))
466 .join(sub, t.c.country_code == sub.c.country_code)
468 results = nres.SearchResults()
469 for row in await conn.execute(sql, _details_to_bind_params(details)):
470 result = nres.create_from_country_row(row, nres.SearchResult)
472 result.accuracy = self.penalty + self.countries.get_penalty(row.country_code, 5.0)
473 results.append(result)
479 class PostcodeSearch(AbstractSearch):
480 """ Search for a postcode.
482 def __init__(self, extra_penalty: float, sdata: SearchData) -> None:
483 super().__init__(sdata.penalty + extra_penalty)
484 self.countries = sdata.countries
485 self.postcodes = sdata.postcodes
486 self.lookups = sdata.lookups
487 self.rankings = sdata.rankings
490 async def lookup(self, conn: SearchConnection,
491 details: SearchDetails) -> nres.SearchResults:
492 """ Find results for the search in the database.
495 pcs = self.postcodes.values
497 sql: SaLambdaSelect = sa.lambda_stmt(lambda:
498 sa.select(t.c.place_id, t.c.parent_place_id,
499 t.c.rank_search, t.c.rank_address,
500 t.c.postcode, t.c.country_code,
501 t.c.geometry.label('centroid'))
502 .where(t.c.postcode.in_(pcs)))
504 if details.geometry_output:
505 sql = _add_geometry_columns(sql, t.c.geometry, details)
507 penalty: SaExpression = sa.literal(self.penalty)
509 if details.viewbox is not None:
510 if details.bounded_viewbox:
511 sql = sql.where(t.c.geometry.intersects(VIEWBOX_PARAM))
513 penalty += sa.case((t.c.geometry.intersects(VIEWBOX_PARAM), 0.0),
514 (t.c.geometry.intersects(VIEWBOX2_PARAM), 1.0),
517 if details.near is not None:
518 if details.near_radius is not None:
519 sql = sql.where(_within_near(t))
520 sql = sql.order_by(t.c.geometry.ST_Distance(NEAR_PARAM))
523 sql = sql.where(t.c.country_code.in_(self.countries.values))
526 sql = sql.where(_exclude_places(t))
529 assert len(self.lookups) == 1
530 assert self.lookups[0].lookup_type == 'restrict'
531 tsearch = conn.t.search_name
532 sql = sql.where(tsearch.c.place_id == t.c.parent_place_id)\
533 .where(sa.func.array_cat(tsearch.c.name_vector,
534 tsearch.c.nameaddress_vector,
535 type_=ARRAY(sa.Integer))
536 .contains(self.lookups[0].tokens))
538 for ranking in self.rankings:
539 penalty += ranking.sql_penalty(conn.t.search_name)
540 penalty += sa.case(*((t.c.postcode == v, p) for v, p in self.postcodes),
544 sql = sql.add_columns(penalty.label('accuracy'))
545 sql = sql.order_by('accuracy').limit(LIMIT_PARAM)
547 results = nres.SearchResults()
548 for row in await conn.execute(sql, _details_to_bind_params(details)):
549 result = nres.create_from_postcode_row(row, nres.SearchResult)
551 result.accuracy = row.accuracy
552 results.append(result)
558 class PlaceSearch(AbstractSearch):
559 """ Generic search for an address or named place.
561 def __init__(self, extra_penalty: float, sdata: SearchData, expected_count: int) -> None:
562 super().__init__(sdata.penalty + extra_penalty)
563 self.countries = sdata.countries
564 self.postcodes = sdata.postcodes
565 self.housenumbers = sdata.housenumbers
566 self.qualifiers = sdata.qualifiers
567 self.lookups = sdata.lookups
568 self.rankings = sdata.rankings
569 self.expected_count = expected_count
572 async def lookup(self, conn: SearchConnection,
573 details: SearchDetails) -> nres.SearchResults:
574 """ Find results for the search in the database.
577 tsearch = conn.t.search_name
579 sql: SaLambdaSelect = sa.lambda_stmt(lambda:
580 sa.select(t.c.place_id, t.c.osm_type, t.c.osm_id, t.c.name,
581 t.c.class_, t.c.type,
582 t.c.address, t.c.extratags,
583 t.c.housenumber, t.c.postcode, t.c.country_code,
585 t.c.parent_place_id, t.c.rank_address, t.c.rank_search,
587 t.c.geometry.ST_Expand(0).label('bbox'))
588 .where(t.c.place_id == tsearch.c.place_id))
591 if details.geometry_output:
592 sql = _add_geometry_columns(sql, t.c.geometry, details)
594 penalty: SaExpression = sa.literal(self.penalty)
595 for ranking in self.rankings:
596 penalty += ranking.sql_penalty(tsearch)
598 for lookup in self.lookups:
599 sql = sql.where(lookup.sql_condition(tsearch))
602 sql = sql.where(tsearch.c.country_code.in_(self.countries.values))
605 # if a postcode is given, don't search for state or country level objects
606 sql = sql.where(tsearch.c.address_rank > 9)
607 tpc = conn.t.postcode
608 pcs = self.postcodes.values
609 if self.expected_count > 1000:
610 # Many results expected. Restrict by postcode.
611 sql = sql.where(lambda: sa.select(tpc.c.postcode)
612 .where(tpc.c.postcode.in_(pcs))
613 .where(tsearch.c.centroid.ST_DWithin(tpc.c.geometry, 0.12))
616 # Less results, only have a preference for close postcodes
617 pc_near = sa.select(sa.func.min(tpc.c.geometry.ST_Distance(tsearch.c.centroid)))\
618 .where(tpc.c.postcode.in_(pcs))\
620 penalty += sa.case((t.c.postcode.in_(pcs), 0.0),
621 else_=sa.func.coalesce(pc_near, 2.0))
623 if details.viewbox is not None:
624 if details.bounded_viewbox:
625 sql = sql.where(tsearch.c.centroid.intersects(VIEWBOX_PARAM))
627 penalty += sa.case((t.c.geometry.intersects(VIEWBOX_PARAM), 0.0),
628 (t.c.geometry.intersects(VIEWBOX2_PARAM), 1.0),
631 if details.near is not None:
632 if details.near_radius is not None:
633 sql = sql.where(tsearch.c.centroid.ST_DWithin(NEAR_PARAM, NEAR_RADIUS_PARAM))
634 sql = sql.add_columns(-tsearch.c.centroid.ST_Distance(NEAR_PARAM)
635 .label('importance'))
636 sql = sql.order_by(sa.desc(sa.text('importance')))
638 sql = sql.order_by(penalty - sa.case((tsearch.c.importance > 0, tsearch.c.importance),
639 else_=0.75001-(sa.cast(tsearch.c.search_rank, sa.Float())/40)))
640 sql = sql.add_columns(t.c.importance)
643 sql = sql.add_columns(penalty.label('accuracy'))\
644 .order_by(sa.text('accuracy'))
646 if self.housenumbers:
647 hnr_regexp = f"\\m({'|'.join(self.housenumbers.values)})\\M"
648 sql = sql.where(tsearch.c.address_rank.between(16, 30))\
649 .where(sa.or_(tsearch.c.address_rank < 30,
650 t.c.housenumber.op('~*')(hnr_regexp)))
652 # Cross check for housenumbers, need to do that on a rather large
653 # set. Worst case there are 40.000 main streets in OSM.
654 inner = sql.limit(10000).subquery()
656 # Housenumbers from placex
657 thnr = conn.t.placex.alias('hnr')
658 pid_list = array_agg(thnr.c.place_id) # type: ignore[no-untyped-call]
659 place_sql = sa.select(pid_list)\
660 .where(thnr.c.parent_place_id == inner.c.place_id)\
661 .where(thnr.c.housenumber.op('~*')(hnr_regexp))\
662 .where(thnr.c.linked_place_id == None)\
663 .where(thnr.c.indexed_status == 0)
666 place_sql = place_sql.where(_exclude_places(thnr))
668 place_sql = place_sql.where(self.qualifiers.sql_restrict(thnr))
670 numerals = [int(n) for n in self.housenumbers.values if n.isdigit()]
671 interpol_sql: SaColumn
674 (not self.qualifiers or ('place', 'house') in self.qualifiers.values):
675 # Housenumbers from interpolations
676 interpol_sql = _make_interpolation_subquery(conn.t.osmline, inner,
678 # Housenumbers from Tiger
679 tiger_sql = sa.case((inner.c.country_code == 'us',
680 _make_interpolation_subquery(conn.t.tiger, inner,
684 interpol_sql = sa.null()
685 tiger_sql = sa.null()
687 unsort = sa.select(inner, place_sql.scalar_subquery().label('placex_hnr'),
688 interpol_sql.label('interpol_hnr'),
689 tiger_sql.label('tiger_hnr')).subquery('unsort')
690 sql = sa.select(unsort)\
691 .order_by(sa.case((unsort.c.placex_hnr != None, 1),
692 (unsort.c.interpol_hnr != None, 2),
693 (unsort.c.tiger_hnr != None, 3),
697 sql = sql.where(t.c.linked_place_id == None)\
698 .where(t.c.indexed_status == 0)
700 sql = sql.where(self.qualifiers.sql_restrict(t))
702 sql = sql.where(_exclude_places(tsearch))
703 if details.min_rank > 0:
704 sql = sql.where(sa.or_(tsearch.c.address_rank >= MIN_RANK_PARAM,
705 tsearch.c.search_rank >= MIN_RANK_PARAM))
706 if details.max_rank < 30:
707 sql = sql.where(sa.or_(tsearch.c.address_rank <= MAX_RANK_PARAM,
708 tsearch.c.search_rank <= MAX_RANK_PARAM))
709 if details.layers is not None:
710 sql = sql.where(_filter_by_layer(t, details.layers))
712 sql = sql.limit(LIMIT_PARAM)
714 results = nres.SearchResults()
715 for row in await conn.execute(sql, _details_to_bind_params(details)):
716 result = nres.create_from_placex_row(row, nres.SearchResult)
718 result.bbox = Bbox.from_wkb(row.bbox)
719 result.accuracy = row.accuracy
720 if not details.excluded or not result.place_id in details.excluded:
721 results.append(result)
723 if self.housenumbers and row.rank_address < 30:
725 subs = _get_placex_housenumbers(conn, row.placex_hnr, details)
726 elif row.interpol_hnr:
727 subs = _get_osmline(conn, row.interpol_hnr, numerals, details)
729 subs = _get_tiger(conn, row.tiger_hnr, numerals, row.osm_id, details)
734 async for sub in subs:
735 assert sub.housenumber
736 sub.accuracy = result.accuracy
737 if not any(nr in self.housenumbers.values
738 for nr in sub.housenumber.split(';')):
742 result.accuracy += 1.0 # penalty for missing housenumber