1 # SPDX-License-Identifier: GPL-3.0-or-later
3 # This file is part of Nominatim. (https://nominatim.org)
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
9 from pathlib import Path
12 from psycopg import sql as pysql
15 # always test against the source
16 SRC_DIR = (Path(__file__) / '..' / '..' / '..').resolve()
17 sys.path.insert(0, str(SRC_DIR / 'src'))
19 from nominatim_db.config import Configuration
20 from nominatim_db.db import connection, properties
21 from nominatim_db.db.sql_preprocessor import SQLPreprocessor
22 import nominatim_db.tokenizer.factory
24 import dummy_tokenizer
25 from cursor import CursorForTesting
28 def _with_srid(geom, default=None):
30 return None if default is None else f"SRID=4326;{default}"
32 return f"SRID=4326;{geom}"
41 def temp_db(monkeypatch):
42 """ Create an empty database for the test. The database name is also
43 exported into NOMINATIM_DATABASE_DSN.
45 name = 'test_nominatim_python_unittest'
47 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
48 with conn.cursor() as cur:
49 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
50 cur.execute(pysql.SQL('CREATE DATABASE') + pysql.Identifier(name))
52 monkeypatch.setenv('NOMINATIM_DATABASE_DSN', 'dbname=' + name)
54 with psycopg.connect(dbname=name) as conn:
55 with conn.cursor() as cur:
56 cur.execute('CREATE EXTENSION hstore')
60 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
61 with conn.cursor() as cur:
62 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS') + pysql.Identifier(name))
67 return 'dbname=' + temp_db
71 def temp_db_with_extensions(temp_db):
72 with psycopg.connect(dbname=temp_db) as conn:
73 with conn.cursor() as cur:
74 cur.execute('CREATE EXTENSION postgis')
80 def temp_db_conn(temp_db):
81 """ Connection to the test database.
83 with connection.connect('', autocommit=True, dbname=temp_db) as conn:
84 connection.register_hstore(conn)
89 def temp_db_cursor(temp_db):
90 """ Connection and cursor towards the test database. The connection will
91 be in auto-commit mode.
93 with psycopg.connect(dbname=temp_db, autocommit=True, cursor_factory=CursorForTesting) as conn:
94 connection.register_hstore(conn)
95 with conn.cursor() as cur:
100 def table_factory(temp_db_conn):
101 """ A fixture that creates new SQL tables, potentially filled with
104 def mk_table(name, definition='id INT', content=None):
105 with psycopg.ClientCursor(temp_db_conn) as cur:
106 cur.execute(pysql.SQL("CREATE TABLE {} ({})")
107 .format(pysql.Identifier(name),
108 pysql.SQL(definition)))
110 sql = pysql.SQL("INSERT INTO {} VALUES ({})")\
111 .format(pysql.Identifier(name),
112 pysql.SQL(',').join([pysql.Placeholder()
113 for _ in range(len(content[0]))]))
114 cur.executemany(sql, content)
121 cfg = Configuration(None)
126 def project_env(tmp_path):
127 projdir = tmp_path / 'project'
129 cfg = Configuration(projdir)
134 def country_table(table_factory):
135 table_factory('country_name', 'partition INT, country_code varchar(2), name hstore')
139 def country_row(country_table, temp_db_cursor):
140 def _add(partition=None, country=None, names=None):
141 temp_db_cursor.insert_row('country_name', partition=partition,
142 country_code=country, name=names)
148 def load_sql(temp_db_conn, country_table):
149 conf = Configuration(None)
151 def _run(*filename, **kwargs):
153 SQLPreprocessor(temp_db_conn, conf).run_sql_file(temp_db_conn, fn, **kwargs)
159 def property_table(load_sql, temp_db_conn):
160 load_sql('tables/nominatim_properties.sql')
163 def set(self, name, value):
164 properties.set_property(temp_db_conn, name, value)
167 return properties.get_property(temp_db_conn, name)
173 def status_table(load_sql):
174 """ Create an empty version of the status table and
175 the status logging table.
177 load_sql('tables/status.sql')
181 def place_table(temp_db_with_extensions, table_factory):
182 """ Create an empty version of the place table.
184 table_factory('place',
185 """osm_id int8 NOT NULL,
186 osm_type char(1) NOT NULL,
190 admin_level smallint,
193 geometry Geometry(Geometry,4326) NOT NULL""")
197 def place_row(place_table, temp_db_cursor):
198 """ A factory for rows in the place table. The table is created as a
199 prerequisite to the fixture.
201 idseq = itertools.count(1001)
203 def _insert(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
204 admin_level=None, address=None, extratags=None, geom='POINT(0 0)'):
205 args = {'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
206 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
207 'address': address, 'extratags': extratags,
208 'geometry': _with_srid(geom)}
209 temp_db_cursor.insert_row('place', **args)
215 def place_postcode_table(temp_db_with_extensions, table_factory):
216 """ Create an empty version of the place_postcode table.
218 table_factory('place_postcode',
219 """osm_type char(1) NOT NULL,
220 osm_id bigint NOT NULL,
221 postcode text NOT NULL,
223 centroid Geometry(Point, 4326) NOT NULL,
224 geometry Geometry(Geometry, 4326)""")
228 def place_postcode_row(place_postcode_table, temp_db_cursor):
229 """ A factory for rows in the place_postcode table. The table is created as a
230 prerequisite to the fixture.
232 idseq = itertools.count(5001)
234 def _insert(osm_type='N', osm_id=None, postcode=None, country=None,
235 centroid='POINT(12.0 4.0)', geom=None):
236 temp_db_cursor.insert_row('place_postcode',
237 osm_type=osm_type, osm_id=osm_id or next(idseq),
238 postcode=postcode, country_code=country,
239 centroid=_with_srid(centroid),
240 geometry=_with_srid(geom))
246 def placex_table(temp_db_with_extensions, temp_db_conn, load_sql, place_table):
247 """ Create an empty version of the placex table.
249 load_sql('tables/placex.sql')
250 temp_db_conn.execute("CREATE SEQUENCE IF NOT EXISTS seq_place START 1")
254 def placex_row(placex_table, temp_db_cursor):
255 """ A factory for rows in the placex table. The table is created as a
256 prerequisite to the fixture.
258 idseq = itertools.count(1001)
260 def _add(osm_type='N', osm_id=None, cls='amenity', typ='cafe', names=None,
261 admin_level=None, address=None, extratags=None, geom='POINT(10 4)',
262 country=None, housenumber=None, rank_search=30, rank_address=30,
263 centroid='POINT(10 4)', indexed_status=0, indexed_date=None):
264 args = {'place_id': pysql.SQL("nextval('seq_place')"),
265 'osm_type': osm_type, 'osm_id': osm_id or next(idseq),
266 'class': cls, 'type': typ, 'name': names, 'admin_level': admin_level,
267 'address': address, 'housenumber': housenumber,
268 'rank_search': rank_search, 'rank_address': rank_address,
269 'extratags': extratags,
270 'centroid': _with_srid(centroid), 'geometry': _with_srid(geom),
271 'country_code': country,
272 'indexed_status': indexed_status, 'indexed_date': indexed_date,
273 'partition': pysql.Literal(0), 'geometry_sector': pysql.Literal(1)}
274 return temp_db_cursor.insert_row('placex', **args)
280 def osmline_table(temp_db_with_extensions, load_sql):
281 load_sql('tables/interpolation.sql')
285 def osmline_row(osmline_table, temp_db_cursor):
286 idseq = itertools.count(20001)
288 def _add(osm_id=None, geom='LINESTRING(12.0 11.0, 12.003 11.0)'):
289 return temp_db_cursor.insert_row(
290 'location_property_osmline',
291 place_id=pysql.SQL("nextval('seq_place')"),
292 osm_id=osm_id or next(idseq),
293 geometry_sector=pysql.Literal(20),
294 partition=pysql.Literal(0),
296 linegeo=_with_srid(geom))
302 def postcode_table(temp_db_with_extensions, load_sql):
303 load_sql('tables/postcodes.sql')
307 def postcode_row(postcode_table, temp_db_cursor):
308 def _add(country, postcode, x=34.5, y=-9.33):
309 geom = _with_srid(f"POINT({x} {y})")
310 return temp_db_cursor.insert_row(
311 'location_postcodes',
312 place_id=pysql.SQL("nextval('seq_place')"),
313 indexed_status=pysql.Literal(1),
314 country_code=country, postcode=postcode,
316 rank_search=pysql.Literal(16),
317 geometry=('ST_Expand(%s::geometry, 0.005)', geom))
323 def sql_preprocessor_cfg(tmp_path, table_factory, temp_db_with_extensions, country_row):
324 for part in range(3):
325 country_row(partition=part)
327 cfg = Configuration(None)
328 cfg.set_libdirs(sql=tmp_path)
333 def sql_preprocessor(sql_preprocessor_cfg, temp_db_conn):
334 return SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg)
338 def tokenizer_mock(monkeypatch, property_table):
339 """ Sets up the configuration so that the test dummy tokenizer will be
340 loaded when the tokenizer factory is used. Also returns a factory
341 with which a new dummy tokenizer may be created.
343 monkeypatch.setenv('NOMINATIM_TOKENIZER', 'dummy')
345 def _import_dummy(*args, **kwargs):
346 return dummy_tokenizer
348 monkeypatch.setattr(nominatim_db.tokenizer.factory,
349 "_import_tokenizer", _import_dummy)
350 property_table.set('tokenizer', 'dummy')
352 def _create_tokenizer():
353 return dummy_tokenizer.DummyTokenizer(None)
355 return _create_tokenizer