]> git.openstreetmap.org Git - nominatim.git/blob - test/python/db/test_sql_preprocessor.py
Merge pull request #2772 from kianmeng/fix-typos
[nominatim.git] / test / python / db / test_sql_preprocessor.py
1 # SPDX-License-Identifier: GPL-2.0-only
2 #
3 # This file is part of Nominatim. (https://nominatim.org)
4 #
5 # Copyright (C) 2022 by the Nominatim developer community.
6 # For a full list of authors see the git log.
7 """
8 Tests for SQL preprocessing.
9 """
10 import pytest
11
12 from nominatim.db.sql_preprocessor import SQLPreprocessor
13
14 @pytest.fixture
15 def sql_factory(tmp_path):
16     def _mk_sql(sql_body):
17         (tmp_path / 'test.sql').write_text("""
18           CREATE OR REPLACE FUNCTION test() RETURNS TEXT
19           AS $$
20           BEGIN
21             {}
22           END;
23           $$ LANGUAGE plpgsql IMMUTABLE;""".format(sql_body))
24         return 'test.sql'
25
26     return _mk_sql
27
28 @pytest.mark.parametrize("expr,ret", [
29     ("'a'", 'a'),
30     ("'{{db.partitions|join}}'", '012'),
31     ("{% if 'country_name' in db.tables %}'yes'{% else %}'no'{% endif %}", "yes"),
32     ("{% if 'xxx' in db.tables %}'yes'{% else %}'no'{% endif %}", "no"),
33     ("'{{db.tablespace.address_data}}'", ""),
34     ("'{{db.tablespace.search_data}}'", 'TABLESPACE "dsearch"'),
35     ("'{{db.tablespace.address_index}}'", 'TABLESPACE "iaddress"'),
36     ("'{{db.tablespace.aux_data}}'", 'TABLESPACE "daux"')
37     ])
38 def test_load_file_simple(sql_preprocessor_cfg, sql_factory,
39                           temp_db_conn, temp_db_cursor, monkeypatch,
40                           expr, ret):
41     monkeypatch.setenv('NOMINATIM_TABLESPACE_SEARCH_DATA', 'dsearch')
42     monkeypatch.setenv('NOMINATIM_TABLESPACE_ADDRESS_INDEX', 'iaddress')
43     monkeypatch.setenv('NOMINATIM_TABLESPACE_AUX_DATA', 'daux')
44     sqlfile = sql_factory("RETURN {};".format(expr))
45
46     SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg).run_sql_file(temp_db_conn, sqlfile)
47
48     assert temp_db_cursor.scalar('SELECT test()') == ret
49
50
51 def test_load_file_with_params(sql_preprocessor, sql_factory, temp_db_conn, temp_db_cursor):
52     sqlfile = sql_factory("RETURN '{{ foo }} {{ bar }}';")
53
54     sql_preprocessor.run_sql_file(temp_db_conn, sqlfile, bar='XX', foo='ZZ')
55
56     assert temp_db_cursor.scalar('SELECT test()') == 'ZZ XX'