The sqlite::Connection
class handles most of the tasks related to connecting to the database and the associated locking/per-thread management.
Connection
The Connection class is the main entry point to anything related to the database. Anything that needs to execute a request will need a connection handle, which is a per-thread connection.
Under the hood, the connection is established the first time a thread connects to the database, and a cached handle is returned at later calls to Connection::handle()
During the initial connection by a new thread, the handle is configured (foreign keys are explicitely activated, recursive triggers are enabled, and a few per-platform other configurations) and hooks are installed.
On platforms that support non-trivial thread_local
object (at the time of writing that means all supported platforms except gcc based windows builds) the handle is automatically released when a thread terminates.
Contexts
The Connection
class allows the users to acquire read and write contexts in order to lock the database accordingly when writing.
Contexts cannot be acquired recursively, but some helpers can simplify the acquisition by checking if the current thread already owns a context. If that's already the case, a default constructed context will be used, which will perform no operation upon its destruction.
Otherwise, a context behaves like any RAII type object and will release itself when falling out of scope.
For more information regarding context, see https://code.videolan.org/videolan/medialibrary/-/wikis/doc/sqlite/Thread-model#contexts
Hooks
Hooks are used to notify the application of various events happening on the database, but are mostly aiming at notifying deletions.
Some entities are deleted through triggers, and many deletions can originate upon a single one (for instance, when a folder is deleted from the database, all its associated files will be deleted, which is likely to cause the media to be removed, which will again propagate to the albums/show/...). This means that it's hard (or rather costly) to know in advance what will be deleted based on a user request, while hooks guarantee us that we will get a notification when this happens.
As is the case for anything related to the database, the hooks are installed per-thread.
Integrity checks
The Connection
class wraps some sqlite features that allows one to perform some integrity checking, in addition to the per-entity model checks.
Those 2 features are
-
checkSchemaIntegrity
which executesPRAGMA integrity_check
-
checkForeignKeysIntegrity
which executes 'PRAGMA foreign_key_checks`
Those helpers are meant to be used after a migration to ensure the database is in a coherent state.