2 Functions for importing tiger data and handling tarbar and directory files
10 from nominatim.db.connection import connect
11 from nominatim.db.async_connection import WorkerPool
12 from nominatim.db.sql_preprocessor import SQLPreprocessor
13 from nominatim.errors import UsageError
14 from nominatim.indexer.place_info import PlaceInfo
16 LOG = logging.getLogger()
19 def handle_tarfile_or_directory(data_dir):
20 """ Handles tarfile or directory for importing tiger data
24 if data_dir.endswith('.tar.gz'):
26 tar = tarfile.open(data_dir)
27 except tarfile.ReadError as err:
28 LOG.fatal("Cannot open '%s'. Is this a tar file?", data_dir)
29 raise UsageError("Cannot open Tiger data file.") from err
31 csv_files = [i for i in tar.getmembers() if i.name.endswith('.csv')]
32 LOG.warning("Found %d CSV files in tarfile with path %s", len(csv_files), data_dir)
34 LOG.warning("Tiger data import selected but no files in tarfile's path %s", data_dir)
37 files = os.listdir(data_dir)
38 csv_files = [os.path.join(data_dir, i) for i in files if i.endswith('.csv')]
39 LOG.warning("Found %d CSV files in path %s", len(csv_files), data_dir)
41 LOG.warning("Tiger data import selected but no files found in path %s", data_dir)
47 def handle_threaded_sql_statements(pool, fd, analyzer):
48 """ Handles sql statement with multiplexing
51 # Using pool of database connections to execute sql statements
53 sql = "SELECT tiger_line_import(%s, %s, %s, %s, %s, %s)"
55 for row in csv.DictReader(fd, delimiter=';'):
57 address = dict(street=row['street'], postcode=row['postcode'])
58 args = ('SRID=4326;' + row['geometry'],
59 int(row['from']), int(row['to']), row['interpolation'],
60 PlaceInfo({'address': address}).analyze(analyzer),
61 analyzer.normalize_postcode(row['postcode']))
64 pool.next_free_worker().perform(sql, args=args)
68 print('.', end='', flush=True)
72 def add_tiger_data(data_dir, config, threads, tokenizer):
73 """ Import tiger data from directory or tar file `data dir`.
75 dsn = config.get_libpq_dsn()
76 files, tar = handle_tarfile_or_directory(data_dir)
81 with connect(dsn) as conn:
82 sql = SQLPreprocessor(conn, config)
83 sql.run_sql_file(conn, 'tiger_import_start.sql')
85 # Reading files and then for each file line handling
86 # sql_query in <threads - 1> chunks.
87 place_threads = max(1, threads - 1)
89 with WorkerPool(dsn, place_threads, ignore_sql_errors=True) as pool:
90 with tokenizer.name_analyzer() as analyzer:
95 fd = io.TextIOWrapper(tar.extractfile(fname))
97 handle_threaded_sql_statements(pool, fd, analyzer)
104 LOG.warning("Creating indexes on Tiger data")
105 with connect(dsn) as conn:
106 sql = SQLPreprocessor(conn, config)
107 sql.run_sql_file(conn, 'tiger_import_finish.sql')