Database
An SQLite connection.
final class Database
You don’t create Database
instances directly. Instead, you connect to a database with one of the Database Connections, and you use a database access method. For example:
let dbQueue = try DatabaseQueue()
try dbQueue.write { (db: Database) in
try Player(name: "Arthur").insert(db)
}
Database
methods that modify, query, or validate the database schema are listed in The Database Schema.
Database Information
var changesCount: Int
The number of rows modified, inserted or deleted by the most recent successful INSERT, UPDATE or DELETE statement.
let configuration: Configuration
The database configuration.
var debugDescription: String
let description: String
A description of this database connection.
var lastErrorCode: ResultCode
The last error code.
var lastErrorMessage: String?
The last error message.
var lastInsertedRowID: Int64
The rowID of the most recently inserted row.
var maximumStatementArgumentCount: Int
The maximum number of arguments accepted by an SQLite statement.
var sqliteConnection: SQLiteConnection?
The raw SQLite connection, suitable for the SQLite C API.
var totalChangesCount: Int
The total number of rows modified, inserted or deleted by all successful INSERT, UPDATE or DELETE statements since the database connection was opened.
typealias SQLiteConnection
A raw SQLite connection, suitable for the SQLite C API.
Database Statements
func allStatements(literal: SQL
) throws -> SQLStatementCursor Returns a cursor of prepared statements.
func allStatements(sql: String, arguments: StatementArguments?
) throws -> SQLStatementCursor Returns a cursor of prepared statements.
func cachedStatement(literal: SQL
) throws -> Statement Returns a prepared statement that can be reused.
func cachedStatement(sql: String
) throws -> Statement Returns a prepared statement that can be reused.
func execute(literal: SQL
) throws Executes one or several SQL statements.
func execute(sql: String, arguments: StatementArguments
) throws Executes one or several SQL statements.
func makeStatement(literal: SQL
) throws -> Statement Returns a new prepared statement that can be reused.
func makeStatement(sql: String
) throws -> Statement Returns a new prepared statement that can be reused.
class SQLStatementCursor
A cursor over all statements in an SQL string.
Database Transactions
func beginTransaction(TransactionKind?
) throws Begins a database transaction.
func commit(
) throws Commits a database transaction.
func inSavepoint(() throws -> TransactionCompletion
) throws Wraps database operations inside a savepoint.
func inTransaction(TransactionKind?, () throws -> TransactionCompletion
) throws Wraps database operations inside a database transaction.
var isInsideTransaction: Bool
A Boolean value indicating whether the database connection is currently inside a transaction.
func readOnly<T>(() throws -> T
) throws -> T Executes read-only database operations, and returns their result after they have finished executing.
func rollback(
) throws Rollbacks a database transaction.
var transactionDate: Date
The date of the current transaction.
enum TransactionCompletion
A transaction commit, or rollback.
enum TransactionKind
A transaction kind.
Printing Database Content
func dumpContent(format: some DumpFormat, to: (any TextOutputStream)?
) throws Prints the contents of the database.
func dumpRequest(some FetchRequest, format: some DumpFormat, to: (any TextOutputStream)?
) throws Prints the results of a request.
func dumpSchema(to: (any TextOutputStream)?
) throws Prints the schema of the database.
func dumpSQL(SQL, format: some DumpFormat, to: (any TextOutputStream)?
) throws Prints the results of all statements in the provided SQL.
func dumpTables([String], format: some DumpFormat, tableHeader: DumpTableHeaderOptions, stableOrder: Bool, to: (any TextOutputStream)?
) throws Prints the contents of the provided tables and views.
protocol DumpFormat
A type that prints database rows.
enum DumpTableHeaderOptions
Options for printing table names.
Database Observation
func add(transactionObserver: some TransactionObserver, extent: TransactionObservationExtent
) Adds a transaction observer on the database connection, so that it gets notified of database changes and transactions.
func remove(transactionObserver: some TransactionObserver
) Removes a transaction observer from the database connection.
func afterNextTransaction(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void
) Registers closures to be executed after the next or current transaction completes.
func notifyChanges(in: some DatabaseRegionConvertible
) throws Notifies that some changes were performed in the provided database region.
func registerAccess(to: @autoclosure () -> some DatabaseRegionConvertible
) throws Reports the database region to
ValueObservation
.
Collations
func add(collation: DatabaseCollation
) Adds or redefines a collation.
func reindex(collation: Database.CollationName
) throws Deletes and recreates from scratch all indices that use this collation.
func reindex(collation: DatabaseCollation
) throws Deletes and recreates from scratch all indices that use this collation.
func remove(collation: DatabaseCollation
) Removes a collation.
struct CollationName
The name of a string comparison function used by SQLite.
class DatabaseCollation
DatabaseCollation
is a custom string comparison function used by SQLite.
SQL Functions
func add(function: DatabaseFunction
) Adds or redefines a custom SQL function.
func remove(function: DatabaseFunction
) Removes a custom SQL function.
class DatabaseFunction
A custom SQL function or aggregate.
Notifications
static let resumeNotification: Notification.Name
When this notification is posted, databases which were opened with the
observesSuspensionNotifications
configuration flag are resumed.static let suspendNotification: Notification.Name
When this notification is posted, databases which were opened with the
observesSuspensionNotifications
configuration flag are suspended.
Other Database Operations
func add(tokenizer: (some FTS5CustomTokenizer).Type
) Add a custom FTS5 tokenizer.
func backup(to: Database, pagesPerStep: CInt, progress: ((DatabaseBackupProgress) throws -> Void)?
) throws Copies the database contents into another database.
func checkpoint(Database.CheckpointMode, on: String?
) throws -> (walFrameCount: Int, checkpointedFrameCount: Int) Runs a WAL checkpoint.
func clearSchemaCache(
) Clears the database schema cache.
nonisolated(unsafe) static var logError: LogErrorFunction?
The error logging function.
func releaseMemory(
) Frees as much memory as possible.
static var sqliteLibVersionNumber: CInt
An integer equal to
SQLITE_VERSION_NUMBER
.func trace(options: TracingOptions, ((TraceEvent) -> Void)?
) Registers a tracing function.
Supporting Types
typealias BusyCallback
See
BusyMode
and https://www.sqlite.org/c3ref/busy_handler.htmlenum BusyMode
When there are several connections to a database, a connection may try to access the database while it is locked by another connection.
enum CheckpointMode
The available checkpoint modes.
struct DatabaseBackupProgress
Describe the progress of a database backup.
typealias LogErrorFunction
An error log function that takes an error code and message.
struct StorageClass
An SQLite storage class.
enum TraceEvent
A trace event.
struct TracingOptions
An option for the SQLite tracing feature.