15 from basf2
import B2DEBUG
21 database_path (pathlib.Path): The path to the database file we want to create/connect to.
24 schema (dict): Database table schema for the DB of the form:
25 {"tablename": ["columnname1 text primary key",
28 read_only (bool): Should the connection be treated as a read-only connection (no update/insert calls)
29 timeout (float): What timeout value should the connection have. How long to wait for other changes to commit.
30 isolation_level (str): How should the connection behave when making transactions?
31 Choices are [None, "DEFERRED", "IMMEDIATE", "EXCLUSIVE"] where None is autocommit behaviour.
34 def __init__(self, database_path, schema=None, read_only=False, timeout=5.0, isolation_level=None):
44 raise ValueError(
"The requested database did not exist, "
45 "but you didn't provide a schema to create the tables.")
49 elif not self.
database_pathdatabase_path.exists()
and read_only:
50 raise ValueError(
"The requested database did not exist, "
51 "but you specified that this was a read_only connection.")
54 except AttributeError
as err:
55 if not isinstance(self.
database_pathdatabase_path, pathlib.Path):
56 raise TypeError(
"You did not use a pathlib.Path object as the database_path.")
63 def __exit__(self, type, value, traceback):
69 B2DEBUG(29, f
"Committing changes and closing Connection for database {self.database_path}.")
70 self.
connconn.commit()
74 B2DEBUG(29, f
"Opening Connection for database {self.database_path}. Readonly = {self.read_only}")
75 connection_uri = self.
get_uriget_uri()
76 self.
connconn = sqlite3.connect(connection_uri, uri=
True, timeout=self.
timeouttimeout, isolation_level=self.
isolation_levelisolation_level)
79 self.
connconn.commit()
81 def query(self, sql, parameters=tuple()):
82 cursor = self.
connconn.cursor()
83 B2DEBUG(29, f
"execute({sql}, {parameters}).")
84 return cursor.execute(sql, parameters)
86 def create_schema(self):
87 for table_name, fields
in self.
schemaschema.items():
88 columns =
",".join(fields)
89 sql = f
"CREATE TABLE {table_name} ({columns})"
91 self.
connconn.commit()
94 uri = f
"file:{self.database_path.as_posix()}"
103 database_path (pathlib.Path): The path to the database file we want to create/connect to.
106 read_only (bool): Should the connection be treated as a read-only connection (no update/insert calls)
107 timeout (float): What timeout value should the connection have. How long to wait for other changes to commit.
110 default_schema = {
"calibrations": [
"name text primary key",
115 def __init__(self, database_path, read_only=False, timeout=30.0, isolation_level=None):
116 super().__init__(database_path, self.
default_schemadefault_schema, read_only, timeout, isolation_level)
118 def insert_calibration(self, calibration_name, state="init", checkpoint="init", iteration=0):
119 self.
queryquery(
"INSERT INTO calibrations VALUES (?,?,?,?)", (calibration_name, state, checkpoint, iteration))
121 def update_calibration_value(self, calibration_name, column_name, new_value, attempts=3):
126 self.
queryquery(
"UPDATE calibrations SET {}=? WHERE name=?".format(column_name), (new_value, calibration_name))
128 except sqlite3.OperationalError
as e:
129 if attempt < attempts:
134 def get_calibration_value(self, calibration_name, column_name):
135 return self.
queryquery(
"SELECT {} FROM calibrations WHERE name=?".format(column_name), (calibration_name,)).fetchone()[0]
137 def output_calibration_table(self):
138 data = {
"name": [],
"state": [],
"checkpoint": [],
"iteration": []}
139 for row
in self.
queryquery(
"SELECT * FROM calibrations"):
140 data[
"name"].append(row[0])
141 data[
"state"].append(row[1])
142 data[
"checkpoint"].append(row[2])
143 data[
"iteration"].append(row[3])
145 table = pandas.DataFrame(data)
146 table_string = table.to_string()
148 line_len = len(table_string.split(
"\n")[1])
149 title =
" Calibrations Table ".center(line_len,
" ")
150 border = line_len *
"="
151 header =
"\n".join((border, title, border))
152 return "\n".join((header, table_string, border))
dictionary default_schema
def query(self, sql, parameters=tuple())