Skip to content

common_sqlite

SQLite utility functions that are independent of API version.

DatabaseError

Bases: Exception

General LUTE database error.

Source code in lute/io/_db/common_sqlite.py
13
14
15
16
class DatabaseError(Exception):
    """General LUTE database error."""

    ...

compare_cols(cols1, cols2)

Compare whether two sets of columns are identical.

The comparison is unidirectional - This function tests for columns present in cols2 which are not present in cols1, but NOT vice versa. Switch the order of the arguments in order to retrieve the other comparison.

Parameters:

Name Type Description Default
cols1 Dict[str, str]

Dictionary of first set of column names and types.

required
cols2 Dict[str, str]

Dictionary of second set of column names and types.

required

Returns:

Name Type Description
diff Dict[str, str] | None

Any columns present in cols2 which are not present in cols1. If cols2 has no entries which are not present in cols1, returns None.

Source code in lute/io/_db/common_sqlite.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def compare_cols(
    cols1: Dict[str, str], cols2: Dict[str, str]
) -> Optional[Dict[str, str]]:
    """Compare whether two sets of columns are identical.

    The comparison is unidirectional - This function tests for columns present
    in `cols2` which are not present in `cols1`, but NOT vice versa. Switch the
    order of the arguments in order to retrieve the other comparison.

    Args:
        cols1 (Dict[str, str]): Dictionary of first set of column names and
            types.

        cols2 (Dict[str, str]): Dictionary of second set of column names and
            types.

    Returns:
        diff (Dict[str, str] | None): Any columns present in `cols2` which
            are not present in `cols1`. If `cols2` has no entries which are
            not present in `cols1`, returns `None`.
    """
    diff: Dict[str, str] = {}

    for col_name in cols2.keys():
        if col_name not in cols1.keys():
            diff[col_name] = cols2[col_name]

    return diff if diff else None

does_table_exist(con, table_name)

Check whether a table exists.

Parameters:

Name Type Description Default
con Connection

Database connection.

required
table_name str

The table to check for.

required

Returns:

Name Type Description
does_exist bool

Whether the table exists.

Source code in lute/io/_db/common_sqlite.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def does_table_exist(con: sqlite3.Connection, table_name: str) -> bool:
    """Check whether a table exists.

    Args:
        con (sqlite3.Connection): Database connection.

        table_name (str): The table to check for.

    Returns:
        does_exist (bool): Whether the table exists.
    """
    res: sqlite3.Cursor = con.execute(
        f"SELECT name FROM sqlite_master WHERE name='{table_name}'"
    )
    if res.fetchone() is None:
        return False
    else:
        return True

execute_in_transaction(con, script)

Execute a multi-statement SQL script without committing.

sqlite3.Connection.executescript always commits any pending transaction first, so it cannot be used inside a migration. This splits the script into complete statements (TRIGGER bodies included) and executes them one by one.

Parameters:

Name Type Description Default
con Connection

Database connection.

required
script str

The SQL statements to execute.

required

Raises:

Type Description
DatabaseError

If the script ends with an incomplete statement.

Source code in lute/io/_db/common_sqlite.py
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def execute_in_transaction(con: sqlite3.Connection, script: str) -> None:
    """Execute a multi-statement SQL script without committing.

    `sqlite3.Connection.executescript` always commits any pending transaction
    first, so it cannot be used inside a migration. This splits the script into
    complete statements (TRIGGER bodies included) and executes them one by one.

    Args:
        con (sqlite3.Connection): Database connection.

        script (str): The SQL statements to execute.

    Raises:
        DatabaseError: If the script ends with an incomplete statement.
    """
    statement: str = ""
    for line in script.splitlines(keepends=True):
        statement += line
        if sqlite3.complete_statement(statement):
            con.execute(statement)
            statement = ""
    if statement.strip():
        raise DatabaseError(f"Incomplete SQL statement: {statement.strip()}")

get_all_rows_for_table(con, table_name)

Return all rows for a requested table.

Parameters:

Name Type Description Default
con Connection

Database connection.

required
table_name str

The table's name.

required

Returns:

Name Type Description
rows List[Tuple[Any, ...]]

ALL rows for a table.

Source code in lute/io/_db/common_sqlite.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def get_all_rows_for_table(
    con: sqlite3.Connection, table_name: str
) -> List[Tuple[Any, ...]]:
    """Return all rows for a requested table.

    Args:
        con (sqlite3.Connection): Database connection.

        table_name (str): The table's name.

    Returns:
        rows (List[Tuple[Any, ...]]): ALL rows for a table.
    """
    sql: str = f'SELECT * FROM "{table_name}"'
    with con:
        res: sqlite3.Cursor = con.execute(sql)

    rows: List[Tuple[Any, ...]] = res.fetchall()
    return rows

get_table_cols(con, table_name)

Retrieve the columns currently present in a table.

Parameters:

Name Type Description Default
con Connection

Database connection.

required
table_name str

The table's name.

required

Returns:

Name Type Description
cols Dict[str, str]

A dictionary of column names and types.

Source code in lute/io/_db/common_sqlite.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def get_table_cols(con: sqlite3.Connection, table_name: str) -> Dict[str, str]:
    """Retrieve the columns currently present in a table.

    Args:
        con (sqlite3.Connection): Database connection.

        table_name (str): The table's name.

    Returns:
        cols (Dict[str, str]): A dictionary of column names and types.
    """
    res: sqlite3.Cursor = con.execute(f"PRAGMA table_info({table_name})")
    # Retrieves: list = [col_id, col_name, col_type, -, default_val, -]
    table_info: List[Tuple[int, str, str, int, str, int]] = res.fetchall()

    cols: Dict[str, str] = {col[1]: col[2] for col in table_info}
    return cols

get_tables(con)

Retrieve a list of all tables in a database.

Parameters:

Name Type Description Default
con Connection

Database connection.

required

Returns:

Name Type Description
tables List[str]

A list of database tables.

Source code in lute/io/_db/common_sqlite.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def get_tables(con: sqlite3.Connection) -> List[str]:
    """Retrieve a list of all tables in a database.

    Args:
        con (sqlite3.Connection): Database connection.

    Returns:
        tables (List[str]): A list of database tables.
    """
    # sql: str = "SELECT name FROM sqlite_schema"
    sql: str = (
        "SELECT name FROM sqlite_schema "
        "WHERE type = 'table' "
        "AND name NOT LIKE 'sqlite_%'"
    )
    with con:
        res: sqlite3.Cursor = con.execute(sql)

    tables: List[str] = [table[0] for table in res.fetchall()]
    return tables

get_user_version(con)

Retrieve the schema version stored in the database file.

Parameters:

Name Type Description Default
con Connection

Database connection.

required

Returns:

Name Type Description
user_version int

The value of PRAGMA user_version. 0 if never set.

Source code in lute/io/_db/common_sqlite.py
136
137
138
139
140
141
142
143
144
145
def get_user_version(con: sqlite3.Connection) -> int:
    """Retrieve the schema version stored in the database file.

    Args:
        con (sqlite3.Connection): Database connection.

    Returns:
        user_version (int): The value of `PRAGMA user_version`. 0 if never set.
    """
    return con.execute("PRAGMA user_version").fetchone()[0]

set_user_version(con, user_version)

Set the schema version stored in the database file.

This is transactional: it is undone if the enclosing transaction is rolled back.

Parameters:

Name Type Description Default
con Connection

Database connection.

required
user_version int

The new value of PRAGMA user_version.

required
Source code in lute/io/_db/common_sqlite.py
148
149
150
151
152
153
154
155
156
157
158
159
160
def set_user_version(con: sqlite3.Connection, user_version: int) -> None:
    """Set the schema version stored in the database file.

    This is transactional: it is undone if the enclosing transaction is rolled
    back.

    Args:
        con (sqlite3.Connection): Database connection.

        user_version (int): The new value of `PRAGMA user_version`.
    """
    # PRAGMA does not accept bound parameters
    con.execute(f"PRAGMA user_version = {int(user_version)}")

write_transaction(con)

Run a block of writes as one transaction.

The write lock is taken at the start (BEGIN IMMEDIATE), so concurrent writers wait for each other instead of interleaving. The block is committed if it completes, and rolled back entirely on any exception, which is then re-raised.

Parameters:

Name Type Description Default
con Connection

Database connection, not in a transaction.

required

Yields:

Name Type Description
con Connection

The same connection.

Source code in lute/io/_db/common_sqlite.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@contextmanager
def write_transaction(con: sqlite3.Connection) -> Iterator[sqlite3.Connection]:
    """Run a block of writes as one transaction.

    The write lock is taken at the start (`BEGIN IMMEDIATE`), so concurrent
    writers wait for each other instead of interleaving. The block is committed
    if it completes, and rolled back entirely on any exception, which is then
    re-raised.

    Args:
        con (sqlite3.Connection): Database connection, not in a transaction.

    Yields:
        con (sqlite3.Connection): The same connection.
    """
    con.execute("BEGIN IMMEDIATE")
    try:
        yield con
    except BaseException:
        con.rollback()
        raise
    con.commit()