]> git.openstreetmap.org Git - nominatim.git/blob - test/python/tools/test_database_import.py
Merge pull request #3991 from lonvia/interpolation-on-addresses
[nominatim.git] / test / python / tools / test_database_import.py
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2026 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Tests for functions to import a new database.
9 """
10 from pathlib import Path
11
12 import pytest
13 import pytest_asyncio  # noqa
14 import psycopg
15 from psycopg import sql as pysql
16
17 from nominatim_db.tools import database_import
18 from nominatim_db.errors import UsageError
19
20
21 class TestDatabaseSetup:
22     DBNAME = 'test_nominatim_python_unittest'
23
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))
30
31             yield True
32
33             with conn.cursor() as cur:
34                 cur.execute(pysql.SQL('DROP DATABASE IF EXISTS ')
35                             + pysql.Identifier(self.DBNAME))
36
37     @pytest.fixture
38     def cursor(self):
39         with psycopg.connect(dbname=self.DBNAME) as conn:
40             with conn.cursor() as cur:
41                 yield cur
42
43     def conn(self):
44         return psycopg.connect(dbname=self.DBNAME)
45
46     def test_setup_skeleton(self):
47         database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
48
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))')
53
54     def test_unsupported_pg_version(self, monkeypatch):
55         monkeypatch.setattr(database_import, 'POSTGRESQL_REQUIRED_VERSION', (100, 4))
56
57         with pytest.raises(UsageError, match='PostgreSQL server is too old.'):
58             database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
59
60     def test_create_db_explicit_ro_user(self):
61         database_import.setup_database_skeleton(f'dbname={self.DBNAME}',
62                                                 rouser='postgres')
63
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')
68
69     def test_setup_extensions_old_postgis(self, monkeypatch):
70         monkeypatch.setattr(database_import, 'POSTGIS_REQUIRED_VERSION', (50, 50))
71
72         with pytest.raises(UsageError, match='PostGIS is too old.'):
73             database_import.setup_database_skeleton(f'dbname={self.DBNAME}')
74
75
76 def test_setup_skeleton_already_exists(temp_db):
77     with pytest.raises(UsageError):
78         database_import.setup_database_skeleton(f'dbname={temp_db}')
79
80
81 def test_import_osm_data_simple(place_row, osm2pgsql_options, capfd):
82     place_row()
83
84     database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options)
85     captured = capfd.readouterr()
86
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
93
94
95 def test_import_osm_data_multifile(place_row, tmp_path, osm2pgsql_options, capfd):
96     place_row()
97     osm2pgsql_options['osm2pgsql_cache'] = 0
98
99     files = [tmp_path / 'file1.osm', tmp_path / 'file2.osm']
100     for f in files:
101         f.write_text('test', encoding='utf-8')
102
103     database_import.import_osm_data(files, osm2pgsql_options)
104     captured = capfd.readouterr()
105
106     assert 'file1.osm' in captured.out
107     assert 'file2.osm' in captured.out
108
109
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)
113
114
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,
117                                     ignore_errors=True)
118
119
120 def test_import_osm_data_drop(place_row, table_factory, temp_db_cursor,
121                               tmp_path, osm2pgsql_options):
122     place_row()
123     table_factory('planet_osm_nodes')
124
125     flatfile = tmp_path / 'flatfile'
126     flatfile.write_text('touch', encoding='utf-8')
127
128     osm2pgsql_options['flatnode_file'] = str(flatfile.resolve())
129
130     database_import.import_osm_data(Path('file.pbf'), osm2pgsql_options, drop=True)
131
132     assert not flatfile.exists()
133     assert not temp_db_cursor.table_exists('planet_osm_nodes')
134
135
136 def test_import_osm_data_default_cache(place_row, osm2pgsql_options, capfd):
137     place_row()
138
139     osm2pgsql_options['osm2pgsql_cache'] = 0
140
141     database_import.import_osm_data(Path(__file__), osm2pgsql_options)
142     captured = capfd.readouterr()
143
144     assert f'--cache {osm2pgsql_options["osm2pgsql_cache"]}' in captured.out
145
146
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']
153     if with_search:
154         tables.append('search_name')
155
156     for table in tables:
157         table_factory(table, content=((1, ), (2, ), (3, )))
158         assert temp_db_cursor.table_rows(table) == 3
159
160     database_import.truncate_data_tables(temp_db_conn)
161
162     for table in tables:
163         assert temp_db_cursor.table_rows(table) == 0
164
165
166 @pytest.mark.parametrize("threads", (1, 5))
167 @pytest.mark.asyncio
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)')
174
175     temp_db_cursor.execute("""
176         CREATE OR REPLACE FUNCTION placex_insert() RETURNS TRIGGER AS $$
177         BEGIN
178           NEW.place_id := nextval('seq_place');
179           NEW.indexed_status := 1;
180           NEW.centroid := ST_Centroid(NEW.geometry);
181           NEW.partition := 0;
182           NEW.geometry_sector := 2424;
183           NEW.rank_address := 30;
184           NEW.rank_search := 30;
185         RETURN NEW;
186         END; $$ LANGUAGE plpgsql STABLE PARALLEL SAFE;
187
188         CREATE OR REPLACE FUNCTION osmline_insert() RETURNS TRIGGER AS $$
189         BEGIN
190           NEW.place_id := nextval('seq_place');
191           IF NEW.indexed_status IS NULL THEN
192             NEW.indexed_status := 1;
193             NEW.partition := 0;
194             NEW.geometry_sector := 2424;
195           END IF;
196         RETURN NEW;
197         END; $$ LANGUAGE plpgsql STABLE PARALLEL SAFE;
198
199         CREATE TRIGGER placex_before_insert BEFORE INSERT ON placex
200         FOR EACH ROW EXECUTE PROCEDURE placex_insert();
201
202         CREATE TRIGGER osmline_before_insert BEFORE INSERT ON location_property_osmline
203         FOR EACH ROW EXECUTE PROCEDURE osmline_insert();
204     """)
205
206     await database_import.load_data(dsn, threads)
207
208     assert temp_db_cursor.table_rows('placex') == 30
209     assert temp_db_cursor.table_rows('location_property_osmline') == 1
210
211
212 class TestSetupSQL:
213
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
218         place_row()
219         table_factory('osm2pgsql_properties', 'property TEXT, value TEXT',
220                       (('db_format', 2),))
221
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;
229             """)
230
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')
234
235         database_import.create_tables(temp_db_conn, self.config, reverse)
236
237         assert temp_db_cursor.table_exists('placex')
238         assert not reverse == temp_db_cursor.table_exists('search_name')
239
240     def test_create_table_triggers(self, temp_db_conn, placex_table, osmline_table,
241                                    postcode_table, load_sql):
242         load_sql('functions.sql')
243
244         database_import.create_table_triggers(temp_db_conn, self.config)
245
246     def test_create_partition_tables(self, country_row, temp_db_conn, temp_db_cursor, load_sql):
247         for i in range(3):
248             country_row(partition=i)
249         load_sql('tables/location_area.sql')
250
251         database_import.create_partition_tables(temp_db_conn, self.config)
252
253         for i in range(3):
254             assert temp_db_cursor.table_exists(f"location_area_large_{i}")
255             assert temp_db_cursor.table_exists(f"search_name_{i}")
256
257     @pytest.mark.parametrize("drop", [True, False])
258     @pytest.mark.asyncio
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)
262
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')