1 # SPDX-License-Identifier: GPL-2.0-only
 
   3 # This file is part of Nominatim. (https://nominatim.org)
 
   5 # Copyright (C) 2022 by the Nominatim developer community.
 
   6 # For a full list of authors see the git log.
 
   8 Tests for SQL preprocessing.
 
  12 from nominatim.db.sql_preprocessor import SQLPreprocessor
 
  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
 
  23           $$ LANGUAGE plpgsql IMMUTABLE;""".format(sql_body))
 
  28 @pytest.mark.parametrize("expr,ret", [
 
  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"')
 
  38 def test_load_file_simple(sql_preprocessor_cfg, sql_factory,
 
  39                           temp_db_conn, temp_db_cursor, monkeypatch,
 
  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))
 
  46     SQLPreprocessor(temp_db_conn, sql_preprocessor_cfg).run_sql_file(temp_db_conn, sqlfile)
 
  48     assert temp_db_cursor.scalar('SELECT test()') == ret
 
  51 def test_load_file_with_params(sql_preprocessor, sql_factory, temp_db_conn, temp_db_cursor):
 
  52     sqlfile = sql_factory("RETURN '{{ foo }} {{ bar }}';")
 
  54     sql_preprocessor.run_sql_file(temp_db_conn, sqlfile, bar='XX', foo='ZZ')
 
  56     assert temp_db_cursor.scalar('SELECT test()') == 'ZZ XX'