Database
public final class Database
An SQLite database.
A database supports SQL statement execution, transactions and savepoints, custom collation sequences, and custom SQL functions.
let db = try Database()
try db.execute(sql: "create table t1(a);")
try db.execute(sql: "insert into t1 default values;")
let rowCount: Int = db.prepare(sql: "select count(*) from t1;").front()
print("t1 has \(rowCount) rows")
-
Creates a temporary database.
Throws
An error if the database could not be created
Declaration
Swift
public init(inMemory: Bool = true) throwsParameters
inMemoryWhether the temporary database should be created in-memory or on-disk
-
Creates a read-only database from a file.
Throws
An error if the database could not be opened
Declaration
Swift
public init(readingFrom url: URL) throwsParameters
urlThe location of the SQLite database
-
Creates a read-write database from a file.
Throws
An error if the database could not be opened
Declaration
Swift
public init(url: URL, create: Bool = true) throwsParameters
urlThe location of the SQLite database
createWhether to create the database if it doesn’t exist
-
Creates a database from an existing
sqlite3 *database connection handle.Attention
The database takes ownership of
db. The result of further use ofdbis undefined.Declaration
Swift
public init(rawSQLiteDatabase db: SQLiteDatabaseConnection)Parameters
dbAn
sqlite3 *database connection handle -
trueif this database is read only,falseotherwiseDeclaration
Swift
public lazy var isReadOnly: Bool { get set } -
The rowid of the most recent successful
INSERTinto a rowid table or virtual tableDeclaration
Swift
public var lastInsertRowid: Int64? { get } -
The number of rows modified, inserted or deleted by the most recently completed
INSERT,UPDATEorDELETEstatementDeclaration
Swift
public var changes: Int { get } -
The total number of rows inserted, modified or deleted by all
INSERT,UPDATEorDELETEstatementsDeclaration
Swift
public var totalChanges: Int { get } -
Interrupts a long-running query.
Declaration
Swift
public func interrupt() -
Returns the location of the file associated with database
name.Note
The main database file has the name main
Throws
An error if there is no attached database with the specified name, or if
nameis a temporary or in-memory databaseDeclaration
Swift
public func url(forDatabase name: String = "main") throws -> URLParameters
nameThe name of the attached database whose location is desired
Return Value
The URL for the file associated with database
name -
Performs a low-level SQLite database operation.
Use of this function should be avoided whenever possible
Throws
Any error thrown in
blockDeclaration
Swift
public func withUnsafeRawSQLiteDatabase<T>(block: (_ db: SQLiteDatabaseConnection) throws -> (T)) rethrows -> TParameters
blockThe closure performing the database operation
dbThe raw
sqlite3 *database connection handleReturn Value
The value returned by
block -
A comparator for
Stringobjects.Declaration
Swift
public typealias StringComparator = (_ lhs: String, _ rhs: String) -> ComparisonResultParameters
lhsThe left-hand operand
rhsThe right-hand operand
Return Value
The result of comparing
lhstorhs -
Adds a custom collation function.
try db.addCollation("localizedCompare", { (lhs, rhs) -> ComparisonResult in return lhs.localizedCompare(rhs) })Throws
An error if the collation function couldn’t be added
Declaration
Swift
public func addCollation(_ name: String, _ block: @escaping StringComparator) throwsParameters
nameThe name of the custom collation sequence
blockA string comparison function
-
Removes a custom collation function.
Throws
An error if the collation function couldn’t be removed
Declaration
Swift
public func removeCollation(_ name: String) throwsParameters
nameThe name of the custom collation sequence
-
The reasons FTS5 will request tokenization
See moreDeclaration
Swift
public enum FTS5TokenizationReason -
Adds a custom FTS5 tokenizer.
For example, a word tokenizer using CFStringTokenizer could be implemented as:
class WordTokenizer: FTS5Tokenizer { var tokenizer: CFStringTokenizer! var text: CFString! required init(arguments: [String]) { // Arguments not used } func set(text: String, reason: Database.FTS5TokenizationReason) { // Reason not used self.text = text as CFString tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, self.text, CFRangeMake(0, CFStringGetLength(self.text)), kCFStringTokenizerUnitWord, nil) } func advance() -> Bool { let nextToken = CFStringTokenizerAdvanceToNextToken(tokenizer) guard nextToken != CFStringTokenizerTokenType(rawValue: 0) else { return false } return true } func currentToken() -> String? { let tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer) guard tokenRange.location != kCFNotFound /*|| tokenRange.length != 0*/ else { return nil } return CFStringCreateWithSubstring(kCFAllocatorDefault, text, tokenRange) as String } func copyCurrentToken(to buffer: UnsafeMutablePointer<UInt8>, capacity: Int) throws -> Int { let tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer) var bytesConverted = 0 let charsConverted = CFStringGetBytes(text, tokenRange, CFStringBuiltInEncodings.UTF8.rawValue, 0, false, buffer, capacity, &bytesConverted) guard charsConverted > 0 else { throw DatabaseError("Insufficient buffer size") } return bytesConverted } }Throws
An error if the tokenizer can’t be added
Seealso
Declaration
Swift
public func addTokenizer<T>(_ name: String, type: T.Type) throws where T : FTS5TokenizerParameters
nameThe name of the tokenizer
typeThe class implementing the tokenizer
-
A hook called when a database transaction is committed.
Declaration
Swift
public typealias CommitHook = () -> BoolReturn Value
trueif the commit operation is allowed to proceed,falseotherwise -
Sets the hook called when a database transaction is committed.
Declaration
Swift
public func setCommitHook(_ block: @escaping CommitHook)Parameters
commitHookA closure called when a transaction is committed
-
Removes the commit hook.
Declaration
Swift
public func removeCommitHook() -
A hook called when a database transaction is rolled back.
Declaration
Swift
public typealias RollbackHook = () -> Void -
Sets the hook called when a database transaction is rolled back.
Declaration
Swift
public func setRollbackHook(_ block: @escaping RollbackHook)Parameters
rollbackHookA closure called when a transaction is rolled back
-
Removes the rollback hook.
Declaration
Swift
public func removeRollbackHook() -
A hook called when a database transaction is committed in write-ahead log mode.
Seealso
Declaration
Swift
public typealias WALCommitHook = (_ databaseName: String, _ pageCount: Int) -> Int32Parameters
databaseNameThe name of the database that was written to
pageCountThe number of pages in the write-ahead log file
Return Value
Normally
SQLITE_OK -
Sets the hook called when a database transaction is committed in write-ahead log mode.
Declaration
Swift
public func setWALCommitHook(_ block: @escaping WALCommitHook)Parameters
commitHookA closure called when a transaction is committed
-
Removes the write-ahead log commit hook.
Declaration
Swift
public func removeWALCommitHook() -
Possible types of database row changes.
See moreDeclaration
Swift
public enum RowChangeType -
A hook called when a row is inserted, deleted, or updated in a rowid table.
Seealso
Declaration
Swift
public typealias UpdateHook = (_ change: RowChangeType, _ database: String, _ table: String, _ rowid: Int64) -> VoidParameters
changeThe type of change triggering the hook
databaseThe name of the database containing the affected row
tableThe name of the table containing the affected row
rowidThe
rowidof the affected row -
Sets the hook called when a row is inserted, deleted, or updated in a rowid table.
Declaration
Swift
public func setUpdateHook(_ block: @escaping UpdateHook)Parameters
updateHookA closure called when a row is inserted, deleted, or updated
-
Removes the update hook.
Declaration
Swift
public func removeUpdateHook() -
A hook that may be called when an attempt is made to access a locked database table.
Declaration
Swift
public typealias BusyHandler = (_ attempts: Int) -> BoolParameters
attemptsThe number of times the busy handler has been called for the same event
Return Value
trueif the attempts to access the database should stop,falseto continue -
Sets a callback that may be invoked when an attempt is made to access a locked database table.
Throws
An error if the busy handler couldn’t be set
Declaration
Swift
public func setBusyHandler(_ block: @escaping BusyHandler) throwsParameters
busyHandlerA closure called when an attempt is made to access a locked database table
-
Removes the busy handler.
Throws
An error if the busy handler couldn’t be removedDeclaration
Swift
public func removeBusyHandler() throws -
Sets a busy handler that sleeps when an attempt is made to access a locked database table.
Throws
An error if the busy timeout couldn’t be set
Seealso
Declaration
Swift
public func setBusyTimeout(_ ms: Int) throwsParameters
msThe minimum time in milliseconds to sleep
-
A custom SQL function.
Throws
Declaration
Swift
public typealias SQLFunction = (_ values: [DatabaseValue]) throws -> DatabaseValueParameters
valuesThe SQL function parameters
Return Value
The result of applying the function to
values -
Declaration
Swift
public struct SQLFunctionFlags : OptionSet -
Adds a custom SQL scalar function.
For example, a localized uppercase scalar function could be implemented as:
try db.addFunction("localizedUppercase", arity: 1) { values in let value = values.first.unsafelyUnwrapped switch value { case .text(let s): return .text(s.localizedUppercase()) default: return value } }Throws
An error if the SQL scalar function couldn’t be added
Seealso
Declaration
Swift
public func addFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ block: @escaping SQLFunction) throwsParameters
nameThe name of the function
arityThe number of arguments the function accepts
flagsFlags affecting the function’s use by SQLite
blockA closure that returns the result of applying the function to the supplied arguments
-
Adds a custom SQL aggregate function.
For example, an integer sum aggregate function could be implemented as:
class IntegerSumAggregateFunction: SQLAggregateFunction { func step(_ values: [DatabaseValue]) throws { let value = values.first.unsafelyUnwrapped switch value { case .integer(let i): sum += i default: throw DatabaseError("Only integer values supported") } } func final() throws -> DatabaseValue { defer { sum = 0 } return DatabaseValue(sum) } var sum: Int64 = 0 }Throws
An error if the SQL aggregate function can’t be added
Seealso
Declaration
Swift
public func addAggregateFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ function: SQLAggregateFunction) throwsParameters
nameThe name of the aggregate function
arityThe number of arguments the function accepts
flagsFlags affecting the function’s use by SQLite
aggregateFunctionAn object defining the aggregate function
-
Adds a custom SQL aggregate window function.
For example, an integer sum aggregate window function could be implemented as:
class IntegerSumAggregateWindowFunction: SQLAggregateWindowFunction { func step(_ values: [DatabaseValue]) throws { let value = values.first.unsafelyUnwrapped switch value { case .integer(let i): sum += i default: throw DatabaseError("Only integer values supported") } } func inverse(_ values: [DatabaseValue]) throws { let value = values.first.unsafelyUnwrapped switch value { case .integer(let i): sum -= i default: throw DatabaseError("Only integer values supported") } } func value() throws -> DatabaseValue { return DatabaseValue(sum) } func final() throws -> DatabaseValue { defer { sum = 0 } return DatabaseValue(sum) } var sum: Int64 = 0 }Throws
An error if the SQL aggregate window function can’t be added
Declaration
Swift
public func addAggregateWindowFunction(_ name: String, arity: Int = -1, flags: SQLFunctionFlags = [.deterministic, .directOnly], _ function: SQLAggregateWindowFunction) throwsParameters
nameThe name of the aggregate window function
arityThe number of arguments the function accepts
flagsFlags affecting the function’s use by SQLite
aggregateWindowFunctionAn object defining the aggregate window function
-
Removes a custom SQL scalar, aggregate, or window function.
Throws
An error if the SQL function couldn’t be removed
Declaration
Swift
public func removeFunction(_ name: String, arity: Int = -1) throwsParameters
nameThe name of the custom SQL function
arityThe number of arguments the custom SQL function accepts
-
Declaration
Swift
public struct VirtualTableModuleOptions : OptionSet -
Adds a virtual table module to the database.
Throws
An error if the virtual table module can’t be registered
Declaration
Swift
public func addModule<T>(_ name: String, type: T.Type) throws where T : VirtualTableModuleParameters
nameThe name of the virtual table module
typeThe class implementing the virtual table module
-
Adds an eponymous virtual table module to the database.
An eponymous virtual table module presents a virtual table with the same name as the module and does not require a
CREATE VIRTUAL TABLEstatement to be available.For example, an eponymous virtual table module returning the natural numbers could be implemented as:
class NaturalNumbersModule: EponymousVirtualTableModule { class Cursor: VirtualTableCursor { var _rowid: Int64 = 0 func column(_ index: Int32) -> DatabaseValue { .integer(_rowid) } func next() { _rowid += 1 } func rowid() -> Int64 { _rowid } func filter(_ arguments: [DatabaseValue], indexNumber: Int32, indexName: String?) { _rowid = 1 } var eof: Bool { _rowid > 2147483647 } } required init(database: Database, arguments: [String]) { // database and arguments not used } var declaration: String { "CREATE TABLE x(value)" } var options: Database.VirtualTableModuleOptions { [.innocuous] } func bestIndex(_ indexInfo: inout sqlite3_index_info) -> VirtualTableModuleBestIndexResult { .ok } func openCursor() -> VirtualTableCursor { Cursor() } }Throws
An error if the virtual table module can’t be registered
Declaration
Swift
public func addModule<T>(_ name: String, type: T.Type) throws where T : EponymousVirtualTableModuleParameters
nameThe name of the virtual table module
typeThe class implementing the virtual table module
-
Returns a compiled SQL statement.
Throws
An error if
sqlcould not be compiledDeclaration
Swift
public func prepare(sql: String) throws -> StatementParameters
sqlThe SQL statement to compile
Return Value
A compiled SQL statement
-
Executes an SQL statement.
This is a shortcut for
prepare(sql: sql).execute().Requires
sqldoes not return any result rowsThrows
An error if
sqlreturned any result rows or could not be compiled or executedDeclaration
Swift
public func execute(sql: String) throwsParameters
sqlThe SQL statement to execute
-
Executes an SQL statement and applies
blockto each result row.This is a shortcut for
prepare(sql: sql).results(block).Throws
An error if
sqlcould not be compiled or executedDeclaration
Swift
public func results(sql: String, _ block: ((_ row: Row) throws -> ())) throwsParameters
sqlThe SQL statement to execute
blockA closure applied to each result row
rowA result row of returned data
-
Executes one or more SQL statements and optionally applies
blockto each result row.Multiple SQL statements are separated with a semicolon (
;)Throws
An error if
sqlcould not be compiled or executedDeclaration
Swift
public func batch(sql: String, _ block: ((_ row: [String : String]) -> Void)? = nil) throwsParameters
sqlThe SQL statement or statements to execute
blockAn optional closure applied to each result row
rowA dictionary of returned data keyed by column name
-
Declaration
Swift
public enum TransactionType -
Begins a database transaction.
Note
Database transactions may not be nested.
Throws
An error if the transaction couldn’t be started
Seealso
Declaration
Swift
public func begin(type: TransactionType = .deferred) throwsParameters
typeThe type of transaction to initiate
-
Rolls back the active database transaction.
Throws
An error if the transaction couldn’t be rolled back or there is no active transactionDeclaration
Swift
public func rollback() throws -
Commits the active database transaction.
Throws
An error if the transaction couldn’t be committed or there is no active transactionDeclaration
Swift
public func commit() throws -
trueif this database is in autocommit mode,falseotherwiseSeealso
Test For Auto-Commit ModeDeclaration
Swift
public var isInAutocommitMode: Bool { get } -
Possible ways to complete a transaction
See moreDeclaration
Swift
public enum TransactionCompletion -
A series of database actions grouped into a transaction
Declaration
Swift
public typealias TransactionBlock = (_ database: Database) throws -> TransactionCompletionParameters
databaseA
Databaseused for database access within the blockReturn Value
.commitif the transaction should be committed or.rollbackif the transaction should be rolled back -
Performs a transaction on the database.
Throws
Any error thrown in
blockor an error if the transaction could not be started, rolled back, or committedNote
If
blockthrows an error the transaction will be rolled back and the error will be re-thrownNote
If an error occurs committing the transaction a rollback will be attempted and the error will be re-thrown
Declaration
Swift
public func transaction(type: Database.TransactionType = .deferred, _ block: TransactionBlock) throwsParameters
typeThe type of transaction to perform
blockA closure performing the database operation
-
Begins a database savepoint transaction.
Note
Savepoint transactions may be nested.
Throws
An error if the savepoint transaction couldn’t be started
Seealso
Declaration
Swift
public func begin(savepoint name: String) throwsParameters
nameThe name of the savepoint transaction
-
Rolls back a database savepoint transaction.
Throws
An error if the savepoint transaction couldn’t be rolled back or doesn’t exist
Declaration
Swift
public func rollback(to name: String) throwsParameters
nameThe name of the savepoint transaction
-
Releases (commits) a database savepoint transaction.
Note
Changes are not saved until the outermost transaction is released or committed.
Throws
An error if the savepoint transaction couldn’t be committed or doesn’t exist
Declaration
Swift
public func release(savepoint name: String) throwsParameters
nameThe name of the savepoint transaction
-
Possible ways to complete a savepoint
See moreDeclaration
Swift
public enum SavepointCompletion -
A series of database actions grouped into a savepoint transaction
Declaration
Swift
public typealias SavepointBlock = (_ database: Database) throws -> SavepointCompletionParameters
databaseA
Databaseused for database access within the blockReturn Value
.releaseif the savepoint should be released or.rollbackif the savepoint should be rolled back -
Performs a savepoint transaction on the database.
Throws
Any error thrown in
blockor an error if the savepoint could not be started, rolled back, or releasedNote
If
blockthrows an error the savepoint will be rolled back and the error will be re-thrownNote
If an error occurs releasing the savepoint a rollback will be attempted and the error will be re-thrown
Declaration
Swift
public func savepoint(block: SavepointBlock) throwsParameters
blockA closure performing the database operation
-
Declaration
Swift
public enum WALCheckpointType -
Perform a write-ahead log checkpoint on the database.
Note
Checkpoints are only valid for databases using write-ahead logging (WAL) mode.
Throws
An error if the checkpoint failed or if the database isn’t in WAL mode
Seealso
Seealso
Declaration
Swift
public func walCheckpoint(type: WALCheckpointType = .passive) throwsParameters
typeThe type of checkpoint to perform
-
Compiles and stores an SQL statement for later use.
Throws
An error if
sqlcould not be compiledDeclaration
Swift
public func prepareStatement(sql: String, forKey key: AnyHashable) throwsParameters
sqlThe SQL statement to prepare
keyA key used to identify the statement
Return Value
A compiled SQL statement
-
Returns the compiled SQL statement for
key.Declaration
Swift
public func preparedStatement(forKey key: AnyHashable) -> Statement?Parameters
keyThe key used to identify the statement
Return Value
A compiled SQL statement or
nilif no statement for the specified key was found -
Stores a compiled SQL statement for later use.
Declaration
Swift
public func setPreparedStatement(_ statement: Statement, forKey key: AnyHashable)Parameters
statementA compiled SQL statement
keyA key used to identify the statement
-
Removes a compiled SQL statement.
Declaration
Swift
public func removePreparedStatement(forKey key: AnyHashable) -> Statement?Parameters
keyThe key used to identify the statement
Return Value
The statement that was removed, or
nilif the key was not present -
Executes the compiled SQL statement for
keyand after execution resets the statement.This method does not clear bound host parameters.
Throws
An error if no statement for the specified key was found, any error thrown by
block, or an error if the statement couldn’t be resetDeclaration
Swift
public func withPreparedStatement<T>(forKey key: AnyHashable, _ block: (_ statement: Statement) throws -> T) throws -> TParameters
keyThe key used to identify the statement
blockA closure performing the statement operation
statementA
Statementused for statement access withinblockReturn Value
The value returned by
block -
Returns or stores the compiled SQL statement for
key.Declaration
Swift
public subscript(key: AnyHashable) -> Statement? { get set }Parameters
keyThe key used to identify the statement
-
A callback for reporting the progress of a database backup.
Declaration
Swift
public typealias BackupProgress = (_ remaining: Int, _ total: Int) -> VoidParameters
remainingThe number of database pages left to copy
totalThe total number of database pages
-
Backs up the database to the specified URL.
Throws
An error if the backup could not be completed
Seealso
Declaration
Swift
public func backup(to url: URL, progress callback: BackupProgress? = nil) throwsParameters
urlThe destination for the backup.
callbackAn optional closure to receive progress information
-
Declaration
Swift
public enum StatusParameter -
Returns status information on the current and highwater values of a database parameter.
Not all parameters support both current and highwater values.
Seealso
Declaration
Swift
public func status(ofParameter parameter: StatusParameter, resetHighwater: Bool = false) throws -> (Int, Int)Parameters
parameterThe desired database parameter
resetHighwaterIf
truethe highwater mark, if applicable, is reset to the current valueReturn Value
A tuple containing the current and highwater values of the requested parameter, as applicable
-
Begins a long-running read transaction on the database.
This is equivalent to the SQL
BEGIN DEFERRED TRANSACTION;Throws
An error if the transaction could not be startedDeclaration
Swift
public func beginReadTransaction() throws -
Ends a long-running read transaction on the database.
This is equivalent to the SQL
ROLLBACK;Throws
An error if the transaction could not be rolled backDeclaration
Swift
public func endReadTransaction() throws -
Updates a long-running read transaction to make the latest database changes visible.
If there is an active read transaction it is ended before beginning a new read transaction.
Throws
An error if the transaction could not be startedDeclaration
Swift
public func updateReadTransaction() throws -
Executes
sqlwith the n parameters invaluesbound to the first n SQL parameters ofsqland appliesblockto each result row.Throws
Any error thrown in
blockor an error ifsqlcouldn’t be compiled,valuescouldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute<C>(sql: String, parameterValues values: C, _ block: ((_ row: Row) throws -> ())? = nil) throws where C : Collection, C.Element : ParameterBindableParameters
sqlThe SQL statement to execute
valuesA collection of values to bind to SQL parameters
blockA closure called for each result row
rowA result row of returned data
-
Executes
sqlwith value bound to SQL parameter name for each (name, value) inparametersand appliesblockto each result row.Throws
Any error thrown in
blockor an error ifsqlcouldn’t be compiled,parameterscouldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute<C>(sql: String, parameters: C, _ block: ((_ row: Row) throws -> ())? = nil) throws where C : Collection, C.Element == (String, V: ParameterBindable)Parameters
sqlThe SQL statement to execute
parametersA collection of name and value pairs to bind to SQL parameters
blockA closure called for each result row
rowA result row of returned data
-
Executes
sqlwith the n parameters invaluesbound to the first n SQL parameters ofsqland appliesblockto each result row.Throws
Any error thrown in
blockor an error ifsqlcouldn’t be compiled,valuescouldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute(sql: String, parameterValues values: [ParameterBindable?], _ block: ((_ row: Row) throws -> ())? = nil) throwsParameters
sqlThe SQL statement to execute
valuesA series of values to bind to SQL parameters
blockA closure called for each result row
rowA result row of returned data
-
Executes
sqlwith value bound to SQL parameter name for each (name, value) inparametersand appliesblockto each result row.Throws
Any error thrown in
blockor an error ifsqlcouldn’t be compiled,parameterscouldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute(sql: String, parameters: [String : ParameterBindable?], _ block: ((_ row: Row) throws -> ())? = nil) throwsParameters
sqlThe SQL statement to execute
parametersA dictionary of names and values to bind to SQL parameters
blockA closure called for each result row
rowA result row of returned data
-
Records a snapshot of the current state of a database schema.
Throws
An error if the snapshot could not be recorded
Seealso
Declaration
Swift
public func takeSnapshot(schema: String = "main") throws -> SnapshotParameters
schemaThe database schema to snapshot
-
Starts or upgrades a read transaction for a database schema to a specific snapshot.
Throws
An error if the snapshot could not be opened
Declaration
Swift
public func openSnapshot(_ snapshot: Snapshot, schema: String = "main") throwsParameters
snapshotThe desired historical snapshot
schemaThe desired database schema
View on GitHub
Database Class Reference