2 Functions for importing tiger data and handling tarbar and directory files
9 from ..db.connection import connect
10 from ..db.async_connection import DBConnection
11 from ..db.sql_preprocessor import SQLPreprocessor
14 LOG = logging.getLogger()
17 def handle_tarfile_or_directory(data_dir):
18 """ Handles tarfile or directory for importing tiger data
22 if data_dir.endswith('.tar.gz'):
23 tar = tarfile.open(data_dir)
24 sql_files = [i for i in tar.getmembers() if i.name.endswith('.sql')]
25 LOG.warning("Found %d SQL files in tarfile with path %s", len(sql_files), data_dir)
27 LOG.warning("Tiger data import selected but no files in tarfile's path %s", data_dir)
30 files = os.listdir(data_dir)
31 sql_files = [os.path.join(data_dir, i) for i in files if i.endswith('.sql')]
32 LOG.warning("Found %d SQL files in path %s", len(sql_files), data_dir)
34 LOG.warning("Tiger data import selected but no files found in path %s", data_dir)
40 def handle_threaded_sql_statements(sel, file):
41 """ Handles sql statement with multiplexing
46 # Using pool of database connections to execute sql statements
50 for key, _ in sel.select(1):
54 sql_query = file.readline()
59 conn.perform(sql_query)
61 print('. ', end='', flush=True)
63 except Exception as exc: # pylint: disable=broad-except
64 LOG.error('Wrong SQL statement: %s', exc)
67 def add_tiger_data(dsn, data_dir, threads, config, sqllib_dir):
68 """ Import tiger data from directory or tar file
71 sql_files, tar = handle_tarfile_or_directory(data_dir)
76 with connect(dsn) as conn:
77 sql = SQLPreprocessor(conn, config, sqllib_dir)
78 sql.run_sql_file(conn, 'tiger_import_start.sql')
80 # Reading sql_files and then for each file line handling
81 # sql_query in <threads - 1> chunks.
82 sel = selectors.DefaultSelector()
83 place_threads = max(1, threads - 1)
85 # Creates a pool of database connections
86 for _ in range(place_threads):
87 conn = DBConnection(dsn)
89 sel.register(conn, selectors.EVENT_WRITE, conn)
91 for sql_file in sql_files:
95 file = tar.extractfile(sql_file)
97 handle_threaded_sql_statements(sel, file)
99 # Unregistering pool of database connections
100 while place_threads > 0:
101 for key, _ in sel.select(1):
111 LOG.warning("Creating indexes on Tiger data")
112 with connect(dsn) as conn:
113 sql = SQLPreprocessor(conn, config, sqllib_dir)
114 sql.run_sql_file(conn, 'tiger_import_finish.sql')