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 Preprocessing of SQL files.
13 def _get_partitions(conn):
14 """ Get the set of partitions currently in use.
16 with conn.cursor() as cur:
17 cur.execute('SELECT DISTINCT partition FROM country_name')
20 partitions.add(row[0])
25 def _get_tables(conn):
26 """ Return the set of tables currently in use.
27 Only includes non-partitioned
29 with conn.cursor() as cur:
30 cur.execute("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
32 return set((row[0] for row in list(cur)))
35 def _setup_tablespace_sql(config):
36 """ Returns a dict with tablespace expressions for the different tablespace
37 kinds depending on whether a tablespace is configured or not.
40 for subset in ('ADDRESS', 'SEARCH', 'AUX'):
41 for kind in ('DATA', 'INDEX'):
42 tspace = getattr(config, 'TABLESPACE_{}_{}'.format(subset, kind))
44 tspace = 'TABLESPACE "{}"'.format(tspace)
45 out['{}_{}'.format(subset.lower(), kind.lower())] = tspace
50 def _setup_postgresql_features(conn):
51 """ Set up a dictionary with various optional Postgresql/Postgis features that
52 depend on the database version.
54 pg_version = conn.server_version_tuple()
55 postgis_version = conn.postgis_version_tuple()
57 'has_index_non_key_column': pg_version >= (11, 0, 0),
58 'spgist_geom' : 'SPGIST' if postgis_version >= (3, 0) else 'GIST'
61 class SQLPreprocessor:
62 """ A environment for preprocessing SQL files from the
65 The preprocessor provides a number of default filters and variables.
66 The variables may be overwritten when rendering an SQL file.
68 The preprocessing is currently based on the jinja2 templating library
69 and follows its syntax.
72 def __init__(self, conn, config):
73 self.env = jinja2.Environment(autoescape=False,
74 loader=jinja2.FileSystemLoader(str(config.lib_dir.sql)))
77 db_info['partitions'] = _get_partitions(conn)
78 db_info['tables'] = _get_tables(conn)
79 db_info['reverse_only'] = 'search_name' not in db_info['tables']
80 db_info['tablespace'] = _setup_tablespace_sql(config)
82 self.env.globals['config'] = config
83 self.env.globals['db'] = db_info
84 self.env.globals['postgres'] = _setup_postgresql_features(conn)
87 def run_sql_file(self, conn, name, **kwargs):
88 """ Execute the given SQL file on the connection. The keyword arguments
89 may supply additional parameters for preprocessing.
91 sql = self.env.get_template(name).render(**kwargs)
93 with conn.cursor() as cur: