2 Preprocessing of SQL files.
 
   7 def _get_partitions(conn):
 
   8     """ Get the set of partitions currently in use.
 
  10     with conn.cursor() as cur:
 
  11         cur.execute('SELECT DISTINCT partition FROM country_name')
 
  14             partitions.add(row[0])
 
  19 def _get_tables(conn):
 
  20     """ Return the set of tables currently in use.
 
  21         Only includes non-partitioned
 
  23     with conn.cursor() as cur:
 
  24         cur.execute("SELECT tablename FROM pg_tables WHERE schemaname = 'public'")
 
  26         return set((row[0] for row in list(cur)))
 
  29 def _setup_tablespace_sql(config):
 
  30     """ Returns a dict with tablespace expressions for the different tablespace
 
  31         kinds depending on whether a tablespace is configured or not.
 
  34     for subset in ('ADDRESS', 'SEARCH', 'AUX'):
 
  35         for kind in ('DATA', 'INDEX'):
 
  36             tspace = getattr(config, 'TABLESPACE_{}_{}'.format(subset, kind))
 
  38                 tspace = 'TABLESPACE "{}"'.format(tspace)
 
  39             out['{}_{}'.format(subset.lower, kind.lower())] = tspace
 
  44 def _setup_postgresql_features(conn):
 
  45     """ Set up a dictionary with various optional Postgresql/Postgis features that
 
  46         depend on the database version.
 
  48     pg_version = conn.server_version_tuple()
 
  50         'has_index_non_key_column': pg_version >= (11, 0, 0)
 
  53 class SQLPreprocessor:
 
  54     """ A environment for preprocessing SQL files from the
 
  57         The preprocessor provides a number of default filters and variables.
 
  58         The variables may be overwritten when rendering an SQL file.
 
  60         The preprocessing is currently based on the jinja2 templating library
 
  61         and follows its syntax.
 
  64     def __init__(self, conn, config):
 
  65         self.env = jinja2.Environment(autoescape=False,
 
  66                                       loader=jinja2.FileSystemLoader(str(config.lib_dir.sql)))
 
  69         db_info['partitions'] = _get_partitions(conn)
 
  70         db_info['tables'] = _get_tables(conn)
 
  71         db_info['reverse_only'] = 'search_name' not in db_info['tables']
 
  72         db_info['tablespace'] = _setup_tablespace_sql(config)
 
  74         self.env.globals['config'] = config
 
  75         self.env.globals['db'] = db_info
 
  76         self.env.globals['postgres'] = _setup_postgresql_features(conn)
 
  79     def run_sql_file(self, conn, name, **kwargs):
 
  80         """ Execute the given SQL file on the connection. The keyword arguments
 
  81             may supply additional parameters for preprocessing.
 
  83         sql = self.env.get_template(name).render(**kwargs)
 
  85         with conn.cursor() as cur: