Skip to content

fix: Use one database connection rather than one per query #126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions things/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ class Database:
"""

debug = False
connection: sqlite3.Connection

# pylint: disable=R0913
def __init__(self, filepath=None, print_sql=False):
Expand All @@ -181,6 +182,11 @@ def __init__(self, filepath=None, print_sql=False):
if self.print_sql:
self.execute_query_count = 0

# "ro" means read-only
# See: https://sqlite.org/uri.html#recognized_query_parameters
uri = f"file:{self.filepath}?mode=ro"
self.connection = sqlite3.connect(uri, uri=True) # pylint: disable=E1101

# Test for migrated database in Things 3.15.16+
# --------------------------------
assert self.get_version() > 21, (
Expand Down Expand Up @@ -495,15 +501,14 @@ def execute_query(self, sql_query, parameters=(), row_factory=None):
print(prettify_sql(sql_query))
print()

# "ro" means read-only
# See: https://sqlite.org/uri.html#recognized_query_parameters
uri = f"file:{self.filepath}?mode=ro"
connection = sqlite3.connect(uri, uri=True) # pylint: disable=E1101
connection.row_factory = row_factory or dict_factory
cursor = connection.cursor()
cursor.execute(sql_query, parameters)
with self.connection:
# Using context manager to keep queries in separate transactions,
# see https://docs.python.org/3/library/sqlite3.html#sqlite3-connection-context-manager
self.connection.row_factory = row_factory or dict_factory
cursor = self.connection.cursor()
cursor.execute(sql_query, parameters)

return cursor.fetchall()
return cursor.fetchall()


# Helper functions
Expand Down
Loading