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) throws
Parameters
inMemory
Whether 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) throws
Parameters
url
The 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) throws
Parameters
url
The location of the SQLite database
create
Whether 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 ofdb
is undefined.Declaration
Swift
public init(rawSQLiteDatabase db: SQLiteDatabaseConnection)
Parameters
db
An
sqlite3 *
database connection handle -
true
if this database is read only,false
otherwiseDeclaration
Swift
public lazy var isReadOnly: Bool { get set }
-
The rowid of the most recent successful
INSERT
into 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
,UPDATE
orDELETE
statementDeclaration
Swift
public var changes: Int { get }
-
The total number of rows inserted, modified or deleted by all
INSERT
,UPDATE
orDELETE
statementsDeclaration
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
name
is a temporary or in-memory databaseDeclaration
Swift
public func url(forDatabase name: String = "main") throws -> URL
Parameters
name
The 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
block
Declaration
Swift
public func withUnsafeRawSQLiteDatabase<T>(block: (_ db: SQLiteDatabaseConnection) throws -> (T)) rethrows -> T
Parameters
block
The closure performing the database operation
db
The raw
sqlite3 *
database connection handleReturn Value
The value returned by
block
-
A comparator for
String
objects.Declaration
Swift
public typealias StringComparator = (_ lhs: String, _ rhs: String) -> ComparisonResult
Parameters
lhs
The left-hand operand
rhs
The right-hand operand
Return Value
The result of comparing
lhs
torhs
-
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) throws
Parameters
name
The name of the custom collation sequence
block
A 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) throws
Parameters
name
The 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 : FTS5Tokenizer
Parameters
name
The name of the tokenizer
type
The class implementing the tokenizer
-
A hook called when a database transaction is committed.
Declaration
Swift
public typealias CommitHook = () -> Bool
Return Value
true
if the commit operation is allowed to proceed,false
otherwise -
Sets the hook called when a database transaction is committed.
Declaration
Swift
public func setCommitHook(_ block: @escaping CommitHook)
Parameters
commitHook
A 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
rollbackHook
A 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) -> Int32
Parameters
databaseName
The name of the database that was written to
pageCount
The 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
commitHook
A 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) -> Void
Parameters
change
The type of change triggering the hook
database
The name of the database containing the affected row
table
The name of the table containing the affected row
rowid
The
rowid
of 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
updateHook
A 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) -> Bool
Parameters
attempts
The number of times the busy handler has been called for the same event
Return Value
true
if the attempts to access the database should stop,false
to 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) throws
Parameters
busyHandler
A 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) throws
Parameters
ms
The minimum time in milliseconds to sleep
-
A custom SQL function.
Throws
Declaration
Swift
public typealias SQLFunction = (_ values: [DatabaseValue]) throws -> DatabaseValue
Parameters
values
The 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) throws
Parameters
name
The name of the function
arity
The number of arguments the function accepts
flags
Flags affecting the function’s use by SQLite
block
A 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) throws
Parameters
name
The name of the aggregate function
arity
The number of arguments the function accepts
flags
Flags affecting the function’s use by SQLite
aggregateFunction
An 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) throws
Parameters
name
The name of the aggregate window function
arity
The number of arguments the function accepts
flags
Flags affecting the function’s use by SQLite
aggregateWindowFunction
An 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) throws
Parameters
name
The name of the custom SQL function
arity
The 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 : VirtualTableModule
Parameters
name
The name of the virtual table module
type
The 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 TABLE
statement 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 : EponymousVirtualTableModule
Parameters
name
The name of the virtual table module
type
The class implementing the virtual table module
-
Returns a compiled SQL statement.
Throws
An error if
sql
could not be compiledDeclaration
Swift
public func prepare(sql: String) throws -> Statement
Parameters
sql
The SQL statement to compile
Return Value
A compiled SQL statement
-
Executes an SQL statement.
This is a shortcut for
prepare(sql: sql).execute()
.Requires
sql
does not return any result rowsThrows
An error if
sql
returned any result rows or could not be compiled or executedDeclaration
Swift
public func execute(sql: String) throws
Parameters
sql
The SQL statement to execute
-
Executes an SQL statement and applies
block
to each result row.This is a shortcut for
prepare(sql: sql).results(block)
.Throws
An error if
sql
could not be compiled or executedDeclaration
Swift
public func results(sql: String, _ block: ((_ row: Row) throws -> ())) throws
Parameters
sql
The SQL statement to execute
block
A closure applied to each result row
row
A result row of returned data
-
Executes one or more SQL statements and optionally applies
block
to each result row.Multiple SQL statements are separated with a semicolon (
;
)Throws
An error if
sql
could not be compiled or executedDeclaration
Swift
public func batch(sql: String, _ block: ((_ row: [String : String]) -> Void)? = nil) throws
Parameters
sql
The SQL statement or statements to execute
block
An optional closure applied to each result row
row
A 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) throws
Parameters
type
The 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
-
true
if this database is in autocommit mode,false
otherwiseSeealso
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 -> TransactionCompletion
Parameters
database
A
Database
used for database access within the blockReturn Value
.commit
if the transaction should be committed or.rollback
if the transaction should be rolled back -
Performs a transaction on the database.
Throws
Any error thrown in
block
or an error if the transaction could not be started, rolled back, or committedNote
If
block
throws 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) throws
Parameters
type
The type of transaction to perform
block
A 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) throws
Parameters
name
The 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) throws
Parameters
name
The 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) throws
Parameters
name
The 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 -> SavepointCompletion
Parameters
database
A
Database
used for database access within the blockReturn Value
.release
if the savepoint should be released or.rollback
if the savepoint should be rolled back -
Performs a savepoint transaction on the database.
Throws
Any error thrown in
block
or an error if the savepoint could not be started, rolled back, or releasedNote
If
block
throws 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) throws
Parameters
block
A 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) throws
Parameters
type
The type of checkpoint to perform
-
Compiles and stores an SQL statement for later use.
Throws
An error if
sql
could not be compiledDeclaration
Swift
public func prepareStatement(sql: String, forKey key: AnyHashable) throws
Parameters
sql
The SQL statement to prepare
key
A 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
key
The key used to identify the statement
Return Value
A compiled SQL statement or
nil
if 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
statement
A compiled SQL statement
key
A key used to identify the statement
-
Removes a compiled SQL statement.
Declaration
Swift
public func removePreparedStatement(forKey key: AnyHashable) -> Statement?
Parameters
key
The key used to identify the statement
Return Value
The statement that was removed, or
nil
if the key was not present -
Executes the compiled SQL statement for
key
and 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 -> T
Parameters
key
The key used to identify the statement
block
A closure performing the statement operation
statement
A
Statement
used for statement access withinblock
Return 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
key
The 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) -> Void
Parameters
remaining
The number of database pages left to copy
total
The 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) throws
Parameters
url
The destination for the backup.
callback
An 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
parameter
The desired database parameter
resetHighwater
If
true
the 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
sql
with the n parameters invalues
bound to the first n SQL parameters ofsql
and appliesblock
to each result row.Throws
Any error thrown in
block
or an error ifsql
couldn’t be compiled,values
couldn’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 : ParameterBindable
Parameters
sql
The SQL statement to execute
values
A collection of values to bind to SQL parameters
block
A closure called for each result row
row
A result row of returned data
-
Executes
sql
with value bound to SQL parameter name for each (name, value) inparameters
and appliesblock
to each result row.Throws
Any error thrown in
block
or an error ifsql
couldn’t be compiled,parameters
couldn’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
sql
The SQL statement to execute
parameters
A collection of name and value pairs to bind to SQL parameters
block
A closure called for each result row
row
A result row of returned data
-
Executes
sql
with the n parameters invalues
bound to the first n SQL parameters ofsql
and appliesblock
to each result row.Throws
Any error thrown in
block
or an error ifsql
couldn’t be compiled,values
couldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute(sql: String, parameterValues values: [ParameterBindable?], _ block: ((_ row: Row) throws -> ())? = nil) throws
Parameters
sql
The SQL statement to execute
values
A series of values to bind to SQL parameters
block
A closure called for each result row
row
A result row of returned data
-
Executes
sql
with value bound to SQL parameter name for each (name, value) inparameters
and appliesblock
to each result row.Throws
Any error thrown in
block
or an error ifsql
couldn’t be compiled,parameters
couldn’t be bound, or the statement couldn’t be executedDeclaration
Swift
public func execute(sql: String, parameters: [String : ParameterBindable?], _ block: ((_ row: Row) throws -> ())? = nil) throws
Parameters
sql
The SQL statement to execute
parameters
A dictionary of names and values to bind to SQL parameters
block
A closure called for each result row
row
A 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 -> Snapshot
Parameters
schema
The 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") throws
Parameters
snapshot
The desired historical snapshot
schema
The desired database schema