2 Functions for bringing auxiliary data in the database up-to-date.
6 from psycopg2.extras import execute_values
8 from ..db.utils import execute_file
10 def update_postcodes(conn, datadir):
11 """ Recalculate postcode centroids and add, remove and update entries in the
12 location_postcode table. `conn` is an opne connection to the database.
14 execute_file(conn, datadir / 'sql' / 'update-postcodes.sql')
17 def recompute_word_counts(conn, datadir):
18 """ Compute the frequency of full-word search terms.
20 execute_file(conn, datadir / 'sql' / 'words_from_search_name.sql')
23 def _add_address_level_rows_from_entry(rows, entry):
24 """ Converts a single entry from the JSON format for address rank
25 descriptions into a flat format suitable for inserting into a
26 PostgreSQL table and adds these lines to `rows`.
28 countries = entry.get('countries') or (None, )
29 for key, values in entry['tags'].items():
30 for value, ranks in values.items():
31 if isinstance(ranks, list):
32 rank_search, rank_address = ranks
34 rank_search = rank_address = ranks
37 for country in countries:
38 rows.append((country, key, value, rank_search, rank_address))
40 def load_address_levels(conn, table, levels):
41 """ Replace the `address_levels` table with the contents of `levels'.
43 A new table is created any previously existing table is dropped.
44 The table has the following columns:
45 country, class, type, rank_search, rank_address
49 _add_address_level_rows_from_entry(rows, entry)
51 with conn.cursor() as cur:
52 cur.execute('DROP TABLE IF EXISTS {}'.format(table))
54 cur.execute("""CREATE TABLE {} (country_code varchar(2),
58 rank_address SMALLINT)""".format(table))
60 execute_values(cur, "INSERT INTO {} VALUES %s".format(table), rows)
62 cur.execute('CREATE UNIQUE INDEX ON {} (country_code, class, type)'.format(table))
66 def load_address_levels_from_file(conn, config_file):
67 """ Replace the `address_levels` table with the contents of the config
70 with config_file.open('r') as fdesc:
71 load_address_levels(conn, 'address_levels', json.load(fdesc))