2 Functions for importing tiger data and handling tarbar and directory files
10 import psycopg2.extras
12 from nominatim.db.connection import connect
13 from nominatim.db.async_connection import WorkerPool
14 from nominatim.db.sql_preprocessor import SQLPreprocessor
15 from nominatim.errors import UsageError
17 LOG = logging.getLogger()
20 def handle_tarfile_or_directory(data_dir):
21 """ Handles tarfile or directory for importing tiger data
25 if data_dir.endswith('.tar.gz'):
27 tar = tarfile.open(data_dir)
28 except tarfile.ReadError as err:
29 LOG.fatal("Cannot open '%s'. Is this a tar file?", data_dir)
30 raise UsageError("Cannot open Tiger data file.") from err
32 csv_files = [i for i in tar.getmembers() if i.name.endswith('.csv')]
33 LOG.warning("Found %d CSV files in tarfile with path %s", len(csv_files), data_dir)
35 LOG.warning("Tiger data import selected but no files in tarfile's path %s", data_dir)
38 files = os.listdir(data_dir)
39 csv_files = [os.path.join(data_dir, i) for i in files if i.endswith('.csv')]
40 LOG.warning("Found %d CSV files in path %s", len(csv_files), data_dir)
42 LOG.warning("Tiger data import selected but no files found in path %s", data_dir)
48 def handle_threaded_sql_statements(pool, fd, analyzer):
49 """ Handles sql statement with multiplexing
52 # Using pool of database connections to execute sql statements
54 sql = "SELECT tiger_line_import(%s, %s, %s, %s, %s, %s)"
56 for row in csv.DictReader(fd, delimiter=';'):
58 address = dict(street=row['street'], postcode=row['postcode'])
59 args = ('SRID=4326;' + row['geometry'],
60 int(row['from']), int(row['to']), row['interpolation'],
61 psycopg2.extras.Json(analyzer.process_place(dict(address=address))),
62 analyzer.normalize_postcode(row['postcode']))
65 pool.next_free_worker().perform(sql, args=args)
69 print('.', end='', flush=True)
73 def add_tiger_data(data_dir, config, threads, tokenizer):
74 """ Import tiger data from directory or tar file `data dir`.
76 dsn = config.get_libpq_dsn()
77 files, tar = handle_tarfile_or_directory(data_dir)
82 with connect(dsn) as conn:
83 sql = SQLPreprocessor(conn, config)
84 sql.run_sql_file(conn, 'tiger_import_start.sql')
86 # Reading files and then for each file line handling
87 # sql_query in <threads - 1> chunks.
88 place_threads = max(1, threads - 1)
90 with WorkerPool(dsn, place_threads, ignore_sql_errors=True) as pool:
91 with tokenizer.name_analyzer() as analyzer:
96 fd = io.TextIOWrapper(tar.extractfile(fname))
98 handle_threaded_sql_statements(pool, fd, analyzer)
105 LOG.warning("Creating indexes on Tiger data")
106 with connect(dsn) as conn:
107 sql = SQLPreprocessor(conn, config)
108 sql.run_sql_file(conn, 'tiger_import_finish.sql')