TracingOptions
An option for the SQLite tracing feature.
struct TracingOptions
You use TracingOptions
with the Database
trace(options:_:)
method.
Related SQLite documentation: https://www.sqlite.org/c3ref/c_trace.html
An option for the SQLite tracing feature.
struct TracingOptions
You use TracingOptions
with the Database
trace(options:_:)
method.
Related SQLite documentation: https://www.sqlite.org/c3ref/c_trace.html
import GRDB
A toolkit for SQLite databases, with a focus on application development
final class Database
An SQLite connection.
func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil)
Registers a tracing function.
typealias BusyCallback = (_ numberOfTries: Int) -> Bool
See BusyMode
and https://www.sqlite.org/c3ref/busy_handler.html
enum 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 = (_ resultCode: ResultCode, _ message: String) -> Void
An error log function that takes an error code and message.
struct StorageClass
An SQLite storage class.
enum TraceEvent
A trace event.
nonisolated(unsafe) static var logError: LogErrorFunction? { get set }
The error logging function.
static let resumeNotification: Notification.Name
When this notification is posted, databases which were opened with the observesSuspensionNotifications
configuration flag are resumed.
static var sqliteLibVersionNumber: CInt { get }
An integer equal to SQLITE_VERSION_NUMBER
.
static let suspendNotification: Notification.Name
When this notification is posted, databases which were opened with the observesSuspensionNotifications
configuration flag are suspended.
static func isGRDBInternalTable(_ tableName: String) -> Bool
Returns whether a table is an internal GRDB table.
static func isSQLiteInternalTable(_ tableName: String) -> Bool
Returns whether a table is an internal SQLite table.
static func json(_ value: some SQLExpressible) -> SQLExpression
Validates and minifies a JSON string, with the JSON
SQL function.
static func jsonArray(_ values: some Collection<some SQLExpressible>) -> SQLExpression
Creates a JSON array with the JSON_ARRAY
SQL function.
static func jsonArray(_ values: some Collection<any SQLExpressible>) -> SQLExpression
Creates a JSON array with the JSON_ARRAY
SQL function.
static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression
The number of elements in a JSON array, as returned by the JSON_ARRAY_LENGTH
SQL function.
static func jsonArrayLength(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The number of elements in a JSON array, as returned by the JSON_ARRAY_LENGTH
SQL function.
static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_EXTRACT
SQL function.
static func jsonExtract(_ value: some SQLExpressible, atPaths paths: some Collection<some SQLExpressible>) -> SQLExpression
The JSON_EXTRACT
SQL function.
static func jsonGroupArray(_ value: some SQLExpressible, filter: (any SQLSpecificExpressible)? = nil) -> SQLExpression
The JSON_GROUP_ARRAY
SQL function.
static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible, filter: (any SQLSpecificExpressible)? = nil) -> SQLExpression
The JSON_GROUP_OBJECT
SQL function.
static func jsonInsert(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_INSERT
SQL function.
static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression
The JSON_VALID
SQL function.
static func jsonObject(_ elements: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
Creates a JSON object with the JSON_OBJECT
SQL function. Pass key/value pairs with a Swift collection such as a Dictionary
.
static func jsonPatch(_ value: some SQLExpressible, with patch: some SQLExpressible) -> SQLExpression
The JSON_PATCH
SQL function.
static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression
Returns a valid JSON string with the JSON_QUOTE
SQL function.
static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_REMOVE
SQL function.
static func jsonRemove(_ value: some SQLExpressible, atPaths paths: some Collection<some SQLExpressible>) -> SQLExpression
The JSON_REMOVE
SQL function.
static func jsonReplace(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_REPLACE
SQL function.
static func jsonSet(_ value: some SQLExpressible, _ assignments: some Collection<(key: String, value: any SQLExpressible)>) -> SQLExpression
The JSON_SET
SQL function.
static func jsonType(_ value: some SQLExpressible) -> SQLExpression
The JSON_TYPE
SQL function.
static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression
The JSON_TYPE
SQL function.
var changesCount: Int { get }
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 { get }
let description: String
A description of this database connection.
var isInsideTransaction: Bool { get }
A Boolean value indicating whether the database connection is currently inside a transaction.
var lastErrorCode: ResultCode { get }
The last error code.
var lastErrorMessage: String? { get }
The last error message.
var lastInsertedRowID: Int64 { get }
The rowID of the most recently inserted row.
var maximumStatementArgumentCount: Int { get }
The maximum number of arguments accepted by an SQLite statement.
var sqliteConnection: SQLiteConnection? { get }
The raw SQLite connection, suitable for the SQLite C API.
var totalChangesCount: Int { get }
The total number of rows modified, inserted or deleted by all successful INSERT, UPDATE or DELETE statements since the database connection was opened.
var transactionDate: Date { get throws }
The date of the current transaction.
func add(collation: DatabaseCollation)
Adds or redefines a collation.
func add(function: DatabaseFunction)
Adds or redefines a custom SQL function.
func add(tokenizer: (some FTS5CustomTokenizer).Type)
Add a custom FTS5 tokenizer.
func add(transactionObserver: some TransactionObserver, extent: TransactionObservationExtent = .observerLifetime)
Adds a transaction observer on the database connection, so that it gets notified of database changes and transactions.
func afterNextTransaction(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void = { _ in })
Registers closures to be executed after the next or current transaction completes.
func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor
Returns a cursor of prepared statements.
func allStatements(sql: String, arguments: StatementArguments? = nil) throws -> SQLStatementCursor
Returns a cursor of prepared statements.
func alter(table name: String, body: (TableAlteration) -> Void) throws
Modifies a database table.
func backup(to destDb: Database, pagesPerStep: CInt = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws
Copies the database contents into another database.
func beginTransaction(_ kind: TransactionKind? = nil) throws
Begins a database transaction.
func cachedStatement(literal sqlLiteral: 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 checkForeignKeys() throws
Throws an error if there exists a foreign key violation in the database.
func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws
Throws an error if there exists a foreign key violation in the table.
@discardableResult func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws -> (walFrameCount: Int, checkpointedFrameCount: Int)
Runs a WAL checkpoint.
func clearSchemaCache()
Clears the database schema cache.
func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo]
Returns the columns in a table or a view.
func commit() throws
Commits a database transaction.
func create(index name: String, on table: String, columns: [String], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and columns.
func create(index name: String, on table: String, columns: [String], unique: Bool = false, ifNotExists: Bool = false, condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and columns.
func create(index name: String, on table: String, expressions: [any SQLExpressible], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index on the specified table and expressions.
func create(indexOn table: String, columns: [String], options: IndexOptions = [], condition: (any SQLExpressible)? = nil) throws
Creates an index with a default name on the specified table and columns.
func create(table name: String, options: TableOptions = [], body: (TableDefinition) throws -> Void) throws
Creates a database table.
func create(table name: String, temporary: Bool = false, ifNotExists: Bool = false, withoutRowID: Bool = false, body: (TableDefinition) throws -> Void) throws
Creates a database table.
func create(view name: String, options: ViewOptions = [], columns: [String]? = nil, as request: SQLSubqueryable) throws
Creates a database view.
func create(view name: String, options: ViewOptions = [], columns: [String]? = nil, asLiteral sqlLiteral: SQL) throws
Creates a database view.
func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws
Creates a virtual database table.
func create<Module>(virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws where Module : VirtualTableModule
Creates a virtual database table.
func create(virtualTable name: String, options: VirtualTableOptions = [], using module: String) throws
Creates a virtual database table.
func create<Module>(virtualTable tableName: String, options: VirtualTableOptions = [], using module: Module, _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws where Module : VirtualTableModule
Creates a virtual database table.
func drop(index name: String) throws
Deletes a database index.
func drop(indexOn table: String, columns: [String]) throws
Deletes the database index on the specified table and columns if exactly one such index exists.
func drop(table name: String) throws
Deletes a database table.
func drop(view name: String) throws
Deletes a database view.
func dropFTS4SynchronizationTriggers(forTable tableName: String) throws
Deletes the synchronization triggers for a synchronized FTS4 table.
func dropFTS5SynchronizationTriggers(forTable tableName: String) throws
Deletes the synchronization triggers for a synchronized FTS5 table.
func dumpContent(format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the contents of the database.
func dumpRequest(_ request: some FetchRequest, format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the results of a request.
func dumpSQL(_ sql: SQL, format: some DumpFormat = .debug(), to stream: (any TextOutputStream)? = nil) throws
Prints the results of all statements in the provided SQL.
func dumpSchema(to stream: (any TextOutputStream)? = nil) throws
Prints the schema of the database.
func dumpTables(_ tables: [String], format: some DumpFormat = .debug(), tableHeader: DumpTableHeaderOptions = .automatic, stableOrder: Bool = false, to stream: (any TextOutputStream)? = nil) throws
Prints the contents of the provided tables and views.
func execute(literal sqlLiteral: SQL) throws
Executes one or several SQL statements.
func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws
Executes one or several SQL statements.
func foreignKeyViolations() throws -> RecordCursor<ForeignKeyViolation>
Returns a cursor over foreign key violations in the database.
func foreignKeyViolations(in tableName: String, in schemaName: String? = nil) throws -> RecordCursor<ForeignKeyViolation>
Returns a cursor over foreign key violations in the table.
func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo]
Returns the foreign keys defined on table named tableName
.
func inSavepoint(_ operations: () throws -> TransactionCompletion) throws
Wraps database operations inside a savepoint.
func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws
Wraps database operations inside a database transaction.
func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo]
The indexes on table named tableName
.
func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern
Creates an FTS5 pattern from a raw pattern string.
func makeStatement(literal sqlLiteral: 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.
func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> any FTS5Tokenizer
Creates an FTS5 tokenizer, given its descriptor.
func notifyChanges(in region: some DatabaseRegionConvertible) throws
Notifies that some changes were performed in the provided database region.
func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo
The primary key for table named tableName
.
func readOnly<T>(_ value: () throws -> T) throws -> T
Executes read-only database operations, and returns their result after they have finished executing.
func registerAccess(to region: @autoclosure () -> some DatabaseRegionConvertible) throws
Reports the database region to ValueObservation
.
func reindex(collation: DatabaseCollation) throws
Deletes and recreates from scratch all indices that use this collation.
func reindex(collation: Database.CollationName) throws
Deletes and recreates from scratch all indices that use this collation.
func releaseMemory()
Frees as much memory as possible.
func remove(collation: DatabaseCollation)
Removes a collation.
func remove(function: DatabaseFunction)
Removes a custom SQL function.
func remove(transactionObserver: some TransactionObserver)
Removes a transaction observer from the database connection.
func rename(table name: String, to newName: String) throws
Renames a database table.
func rollback() throws
Rollbacks a database transaction.
func schemaVersion() throws -> Int32
Returns the current schema version (PRAGMA schema_version
).
func table(_ tableName: String, hasUniqueKey columns: some Collection<String>) throws -> Bool
Returns whether a sequence of columns uniquely identifies a row.
func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a table exists
func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a trigger exists, in the main or temp schema, or in an attached database.
func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool
Returns whether a view exists, in the main or temp schema, or in an attached database.
struct CollationName
The name of a string comparison function used by SQLite.
struct ColumnType
An SQL column type.
enum ConflictResolution
An SQLite conflict resolution.
enum ForeignKeyAction
A foreign key action.
@frozen enum TransactionCompletion
A transaction commit, or rollback.
enum TransactionKind
A transaction kind.
enum TransactionObservationExtent
The extent of the observation performed by a TransactionObserver
.
protocol Equatable
A type that can be compared for value equality.
protocol ExpressibleByArrayLiteral
A type that can be initialized using an array literal.
protocol OptionSet : RawRepresentable, SetAlgebra
A type that presents a mathematical set interface to a bit set.
protocol RawRepresentable<RawValue>
A type that can be converted to and from an associated raw value.
protocol Sendable
protocol SetAlgebra<Element> : Equatable, ExpressibleByArrayLiteral
A type that provides mathematical set operations.
init(rawValue: CInt)
Creates a TracingOptions
from a raw trace event code.
static let profile: Database.TracingOptions
The option that reports executed statements and the estimated duration that the statement took to run.
static let statement: Database.TracingOptions
The option that reports executed statements.
let rawValue: CInt
The raw trace event code.
init()
Creates an empty option set.
init<S>(_ sequence: S) where S : Sequence, Self.Element == S.Element
Creates a new set from a finite sequence of items.
init(arrayLiteral: Self.Element...)
Creates a set containing the elements of the given array literal.
var isEmpty: Bool { get }
A Boolean value that indicates whether the set has no elements.
static func != (lhs: Self, rhs: Self) -> Bool
Returns a Boolean value indicating whether two values are not equal.
func contains(_ member: Self) -> Bool
Returns a Boolean value that indicates whether a given element is a member of the option set.
mutating func formIntersection(_ other: Self)
Removes all elements of this option set that are not also present in the given set.
mutating func formSymmetricDifference(_ other: Self)
Replaces this set with a new set containing all elements contained in either this set or the given set, but not in both.
mutating func formUnion(_ other: Self)
Inserts the elements of another set into this option set.
@discardableResult mutating func insert(_ newMember: Self.Element) -> (inserted: Bool, memberAfterInsert: Self.Element)
Adds the given element to the option set if it is not already a member.
func intersection(_ other: Self) -> Self
Returns a new option set with only the elements contained in both this set and the given set.
func isDisjoint(with other: Self) -> Bool
Returns a Boolean value that indicates whether the set has no members in common with the given set.
func isStrictSubset(of other: Self) -> Bool
Returns a Boolean value that indicates whether this set is a strict subset of the given set.
func isStrictSuperset(of other: Self) -> Bool
Returns a Boolean value that indicates whether this set is a strict superset of the given set.
func isSubset(of other: Self) -> Bool
Returns a Boolean value that indicates whether the set is a subset of another set.
func isSuperset(of other: Self) -> Bool
Returns a Boolean value that indicates whether the set is a superset of the given set.
@discardableResult mutating func remove(_ member: Self.Element) -> Self.Element?
Removes the given element and all elements subsumed by it.
mutating func subtract(_ other: Self)
Removes the elements of the given set from this set.
func subtracting(_ other: Self) -> Self
Returns a new set containing the elements of this set that do not occur in the given set.
func symmetricDifference(_ other: Self) -> Self
Returns a new option set with the elements contained in this set or in the given set, but not in both.
func union(_ other: Self) -> Self
Returns a new option set of the elements contained in this set, in the given set, or in both.
@discardableResult mutating func update(with newMember: Self.Element) -> Self.Element?
Inserts the given element into the set.