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.
8 Tests for functions to import a new database.
10 from pathlib import Path
13 import pytest_asyncio # noqa
15 from psycopg import sql as pysql
17 from nominatim_db.tools import database_import
18 from nominatim_db.errors import UsageError
21 class TestDatabaseSetup:
22 DBNAME = 'test_nominatim_python_unittest'
24 @pytest.fixture(autouse=True)
25 def setup_nonexistant_db(self):
26 with psycopg.connect(dbname='postgres', autocommit=True) as conn:
27 with conn.cursor() as cur:
28 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS ')
29 + pysql.Identifier(self.DBNAME))
33 with conn.cursor() as cur:
34 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS ')
35 + pysql.Identifier(self.DBNAME))
39 with psycopg.connect(dbname=self.DBNAME) as conn:
40 with conn.cursor() as cur:
44 return psycopg.connect(dbname=self.DBNAME)
46 def test_setup_skeleton(self):
47 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
49 # Check that all extensions are set up.
50 with self.conn() as conn:
51 with conn.cursor() as cur:
52 cur.execute('CREATE TABLE t (h HSTORE, geom GEOMETRY(Geometry, 4326))')
54 def test_unsupported_pg_version(self, monkeypatch):
55 monkeypatch.setattr(database_import, 'POSTGRESQL_REQUIRED_VERSION', (100, 4))
57 with pytest.raises(UsageError, match='PostgreSQL server is too old.'):
58 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
60 def test_create_db_explicit_ro_user(self):
61 database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
64 def test_create_db_missing_ro_user(self):
65 with pytest.raises(UsageError, match='Missing read-only user.'):
66 database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
67 rouser='sdfwkjkjgdugu2jgsafkljas')
69 def test_setup_extensions_old_postgis(self, monkeypatch):
70 monkeypatch.setattr(database_import, 'POSTGIS_REQUIRED_VERSION', (50, 50))
72 with pytest.raises(UsageError, match='PostGIS is too old.'):
73 database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
76 def test_setup_skeleton_already_exists(temp_db):
77 with pytest.raises(UsageError):
78 database_import.setup_database_skeleton(f'dbname={temp_db}')
81 def test_import_osm_data_simple(place_row, osm2pgsql_options, capfd):
84 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
85 captured = capfd.readouterr()
87 assert '--create' in captured.out
88 assert '--output flex' in captured.out
89 assert f'--style {osm2pgsql_options["osm2pgsql_style"]}' in captured.out
90 assert f'--number-processes {osm2pgsql_options["threads"]}' in captured.out
91 assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
92 assert 'file.pbf' in captured.out
95 def test_import_osm_data_multifile(place_row, tmp_path, osm2pgsql_options, capfd):
97 osm2pgsql_options['osm2pgsql_cache'] = 0
99 files = [tmp_path / 'file1.osm', tmp_path / 'file2.osm']
101 f.write_text('test', encoding='utf-8')
103 database_import.import_osm_data(files, osm2pgsql_options)
104 captured = capfd.readouterr()
106 assert 'file1.osm' in captured.out
107 assert 'file2.osm' in captured.out
110 def test_import_osm_data_simple_no_data(place_row, osm2pgsql_options):
111 with pytest.raises(UsageError, match='No data imported'):
112 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
115 def test_import_osm_data_simple_ignore_no_data(place_table, osm2pgsql_options):
116 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options,
120 def test_import_osm_data_drop(place_row, table_factory, temp_db_cursor,
121 tmp_path, osm2pgsql_options):
123 table_factory('planet_osm_nodes')
125 flatfile = tmp_path / 'flatfile'
126 flatfile.write_text('touch', encoding='utf-8')
128 osm2pgsql_options['flatnode_file'] = str(flatfile.resolve())
130 database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options, drop=True)
132 assert not flatfile.exists()
133 assert not temp_db_cursor.table_exists('planet_osm_nodes')
136 def test_import_osm_data_default_cache(place_row, osm2pgsql_options, capfd):
139 osm2pgsql_options['osm2pgsql_cache'] = 0
141 database_import.import_osm_data(Path(__file__), osm2pgsql_options)
142 captured = capfd.readouterr()
144 assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
147 @pytest.mark.parametrize("with_search", (True, False))
148 def test_truncate_database_tables(temp_db_conn, temp_db_cursor, table_factory, with_search):
149 tables = ['placex', 'place_addressline', 'location_area',
150 'location_area_country',
151 'location_property_tiger', 'location_property_osmline',
152 'location_postcodes', 'location_road_23']
154 tables.append('search_name')
157 table_factory(table, content=((1, ), (2, ), (3, )))
158 assert temp_db_cursor.table_rows(table) == 3
160 database_import.truncate_data_tables(temp_db_conn)
163 assert temp_db_cursor.table_rows(table) == 0
166 @pytest.mark.parametrize("threads", (1, 5))
168 async def test_load_data(dsn, place_row, placex_table, osmline_table,
169 temp_db_cursor, threads):
170 for oid in range(100, 130):
171 place_row(osm_id=oid)
172 place_row(osm_type='W', osm_id=342, cls='place', typ='houses',
173 geom='LINESTRING(0 0, 10 10)')
175 temp_db_cursor.execute("""
176 CREATE OR REPLACE FUNCTION placex_insert() RETURNS TRIGGER AS $$
178 NEW.place_id := nextval('seq_place');
179 NEW.indexed_status := 1;
180 NEW.centroid := ST_Centroid(NEW.geometry);
182 NEW.geometry_sector := 2424;
183 NEW.rank_address := 30;
184 NEW.rank_search := 30;
186 END; $$ LANGUAGE plpgsql STABLE PARALLEL SAFE;
188 CREATE OR REPLACE FUNCTION osmline_insert() RETURNS TRIGGER AS $$
190 NEW.place_id := nextval('seq_place');
191 IF NEW.indexed_status IS NULL THEN
192 NEW.indexed_status := 1;
194 NEW.geometry_sector := 2424;
197 END; $$ LANGUAGE plpgsql STABLE PARALLEL SAFE;
199 CREATE TRIGGER placex_before_insert BEFORE INSERT ON placex
200 FOR EACH ROW EXECUTE PROCEDURE placex_insert();
202 CREATE TRIGGER osmline_before_insert BEFORE INSERT ON location_property_osmline
203 FOR EACH ROW EXECUTE PROCEDURE osmline_insert();
206 await database_import.load_data(dsn, threads)
208 assert temp_db_cursor.table_rows('placex') == 30
209 assert temp_db_cursor.table_rows('location_property_osmline') == 1
214 @pytest.fixture(autouse=True)
215 def osm2ppsql_skel(self, def_config, temp_db_with_extensions, place_row,
216 country_table, table_factory, temp_db_conn):
217 self.config = def_config
219 table_factory('osm2pgsql_properties', 'property TEXT, value TEXT',
222 table_factory('planet_osm_rels', 'id BIGINT, members JSONB, tags JSONB')
223 temp_db_conn.execute("""
224 CREATE OR REPLACE FUNCTION planet_osm_member_ids(jsonb, character)
225 RETURNS bigint[] AS $$
226 SELECT array_agg((el->>'ref')::int8)
227 FROM jsonb_array_elements($1) AS el WHERE el->>'type' = $2
228 $$ LANGUAGE sql IMMUTABLE;
231 @pytest.mark.parametrize("reverse", [True, False])
232 def test_create_tables(self, table_factory, temp_db_conn, temp_db_cursor, reverse):
233 table_factory('country_osm_grid')
235 database_import.create_tables(temp_db_conn, self.config, reverse)
237 assert temp_db_cursor.table_exists('placex')
238 assert not reverse == temp_db_cursor.table_exists('search_name')
240 def test_create_table_triggers(self, temp_db_conn, placex_table, osmline_table,
241 postcode_table, load_sql):
242 load_sql('functions.sql')
244 database_import.create_table_triggers(temp_db_conn, self.config)
246 def test_create_partition_tables(self, country_row, temp_db_conn, temp_db_cursor, load_sql):
248 country_row(partition=i)
249 load_sql('tables/location_area.sql')
251 database_import.create_partition_tables(temp_db_conn, self.config)
254 assert temp_db_cursor.table_exists(f"location_area_large_{i}")
255 assert temp_db_cursor.table_exists(f"search_name_{i}")
257 @pytest.mark.parametrize("drop", [True, False])
259 async def test_create_search_indices(self, temp_db_conn, temp_db_cursor, drop, load_sql):
260 load_sql('tables.sql', 'functions/ranking.sql')
261 await database_import.create_search_indices(temp_db_conn, self.config, drop)
263 assert temp_db_cursor.index_exists('placex', 'idx_placex_geometry')
264 assert not drop == temp_db_cursor.index_exists('placex', 'idx_placex_geometry_buildings')