Coverage for src/pyensae/sql/database_helper.py: 87%
15 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-03 02:16 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-03 02:16 +0200
1"""
2@file
3@brief Contains functions to import a text file into a database (SQLite).
4"""
6import os
7from .database_main import Database
10def import_flatfile_into_database(filedb, filetext, table=None, header=True,
11 columns=None, engine='SQLite', host='localhost', add_key=None,
12 encoding="utf-8", fLOG=print):
13 """
15 Function which imports a file into a database.
16 It the table exists, it removes it first. There is no addition.
18 @param filedb something.db3
19 @param filetext something.txt or .tsv
20 @param table table name (in the database), if None, the database name will be the filename without extension
21 @param columns if header is False, this must be specified. It should be a list of column names.
22 @param header boolean (does it have a header or not)
23 @param engine engine to use when using a SQL server (SQLite or ODBCMSSQL)
24 @param host host (server)
25 @param fLOG logging function (will display information through the command line)
26 @param add_key name of a key to add (or None if nothing to add)
27 @param encoding encoding
28 @return table name
30 .. exref::
31 :title: Import a flat file into a SQLite database
32 :tag: SQL
34 ::
36 from pyensae import import_flatfile_into_database
37 dbf = "database.db3"
38 file = "textfile.txt"
39 import_flatfile_into_database(dbf, file)
41 On Windows, `SQLiteSpy <http://www.yunqa.de/delphi/doku.php/products/sqlitespy/index>`_ is a free tool
42 very useful to run SQL queries against a sqlite3 database.
43 """
44 # connection
45 db = Database(filedb, engine=engine, host=host, LOG=fLOG)
46 db.connect()
48 if table is None:
49 table = os.path.splitext(
50 os.path.split(filetext)[-1])[0].replace(".", "").replace(",", "")
52 if db.has_table(table):
53 fLOG("remove ", table)
54 db.remove_table(table)
56 if header:
57 columns = None
59 db.import_table_from_flat_file(filetext, table, columns=columns,
60 header=header, add_key=add_key,
61 encoding=encoding)
63 db.close()
64 return table