Table
public struct Table<RowDecoder>
Table can build query interface requests.
// SELECT * FROM player WHERE score >= 1000
let table = Table("player")
let rows: [Row] = try dbQueue.read { db in
table.all()
.filter(Column("score") >= 1000)
.fetchAll(db)
}
-
The table name
Declaration
Swift
public var tableName: String -
Create a
Tablelet table = Table<Row>("player") let table = Table<Player>("player")Declaration
Swift
public init(_ tableName: String)
-
Creates a request for all rows of the table.
// Fetch all players let table = Table<Player>("player") let request = table.all() let players: [Player] = try request.fetchAll(db)Declaration
Swift
public func all() -> QueryInterfaceRequest<RowDecoder> -
Creates a request which fetches no row.
// Fetch no players let table = Table<Player>("player") let request = table.none() let players: [Player] = try request.fetchAll(db) // Empty arrayDeclaration
Swift
public func none() -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects selection.
// SELECT id, email FROM player let table = Table("player") let request = table.select(Column("id"), Column("email"))Declaration
Swift
public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects selection.
// SELECT id, email FROM player let table = Table("player") let request = table.select([Column("id"), Column("email")])Declaration
Swift
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects sql.
// SELECT id, email FROM player let table = Table("player") let request = table.select(sql: "id, email")Declaration
Swift
public func select( sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects an SQL literal.
Literals allow you to safely embed raw values in your SQL, without any risk of syntax errors or SQL injection:
// SELECT id, email, score + 1000 FROM player let table = Table("player") let bonus = 1000 let request = table.select(literal: """ id, email, score + \(bonus) """)Declaration
Swift
public func select(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects selection, and fetches values of type type.
try dbQueue.read { db in // SELECT max(score) FROM player let table = Table("player") let request = table.select([max(Column("score"))], as: Int.self) let maxScore: Int? = try request.fetchOne(db) }Declaration
Swift
public func select<RowDecoder>( _ selection: [SQLSelectable], as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects selection, and fetches values of type type.
try dbQueue.read { db in // SELECT max(score) FROM player let table = Table("player") let request = table.select(max(Column("score")), as: Int.self) let maxScore: Int? = try request.fetchOne(db) }Declaration
Swift
public func select<RowDecoder>( _ selection: SQLSelectable..., as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects sql, and fetches values of type type.
try dbQueue.read { db in // SELECT max(score) FROM player let table = Table("player") let request = table.select(sql: "max(score)", as: Int.self) let maxScore: Int? = try request.fetchOne(db) }Declaration
Swift
public func select<RowDecoder>( sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which selects an SQL literal, and fetches values of type type.
Literals allow you to safely embed raw values in your SQL, without any risk of syntax errors or SQL injection:
// SELECT IFNULL(name, 'Anonymous') FROM player let table = Table("player") let defaultName = "Anonymous" let request = table.select( literal: "IFNULL(name, \(defaultName))", as: String.self) let name: String? = try request.fetchOne(db)Declaration
Swift
public func select<RowDecoder>( literal sqlLiteral: SQL, as type: RowDecoder.Type = RowDecoder.self) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which appends selection.
// SELECT id, email, name FROM player let table = Table("player") let request = table .select([Column("id"), Column("email")]) .annotated(with: [Column("name")])Declaration
Swift
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which appends selection.
// SELECT id, email, name FROM player let table = Table("player") let request = table .select([Column("id"), Column("email")]) .annotated(with: Column("name"))Declaration
Swift
public func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided predicate.
// SELECT * FROM player WHERE email = 'arthur@example.com' let table = Table<Player>("player") let request = table.filter(Column("email") == "arthur@example.com")Declaration
Swift
public func filter(_ predicate: SQLSpecificExpressible) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided primary key predicate.
// SELECT * FROM player WHERE id = 1 let table = Table<Player>("player") let request = table.filter(key: 1)Declaration
Swift
public func filter<PrimaryKeyType>(key: PrimaryKeyType?) -> QueryInterfaceRequest<RowDecoder> where PrimaryKeyType: DatabaseValueConvertible -
Creates a request with the provided primary key predicate.
// SELECT * FROM player WHERE id IN (1, 2, 3) let table = Table<Player>("player") let request = table.filter(keys: [1, 2, 3])Declaration
Swift
public func filter<Sequence>(keys: Sequence) -> QueryInterfaceRequest<RowDecoder> where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible -
Creates a request with the provided primary key predicate.
// SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' let table = Table<Passport>("passport") let request = table.filter(key: ["personId": 1, "countryCode": "FR"])When executed, this request raises a fatal error if there is no unique index on the key columns.
Declaration
Swift
public func filter(key: [String : DatabaseValueConvertible?]?) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided primary key predicate.
// SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... let table = Table<Passport>("passport") let request = table.filter(keys: [["personId": 1, "countryCode": "FR"], ...])When executed, this request raises a fatal error if there is no unique index on the key columns.
Declaration
Swift
public func filter(keys: [[String : DatabaseValueConvertible?]]) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided predicate.
// SELECT * FROM player WHERE email = 'arthur@example.com' let table = Table<Player>("player") let request = table.filter(sql: "email = ?", arguments: ["arthur@example.com"])Declaration
Swift
public func filter( sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided predicate added to the eventual set of already applied predicates.
Literals allow you to safely embed raw values in your SQL, without any risk of syntax errors or SQL injection:
// SELECT * FROM player WHERE name = 'O''Brien' let table = Table<Player>("player") let name = "O'Brien" let request = table.filter(literal: "email = \(email)")Declaration
Swift
public func filter(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> -
Creates a request sorted according to the provided orderings.
// SELECT * FROM player ORDER BY name let table = Table<Player>("player") let request = table.order(Column("name"))Declaration
Swift
public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest<RowDecoder> -
Creates a request sorted according to the provided orderings.
// SELECT * FROM player ORDER BY name let table = Table<Player>("player") let request = table.order([Column("name")])Declaration
Swift
public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest<RowDecoder> -
Creates a request sorted by primary key.
// SELECT * FROM player ORDER BY id let table = Table<Player>("player") let request = table.orderByPrimaryKey() // SELECT * FROM country ORDER BY code let request = Country.orderByPrimaryKey()Declaration
Swift
public func orderByPrimaryKey() -> QueryInterfaceRequest<RowDecoder> -
Creates a request sorted according to sql.
// SELECT * FROM player ORDER BY name let table = Table<Player>("player") let request = table.order(sql: "name")Declaration
Swift
public func order( sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<RowDecoder> -
Creates a request sorted according to an SQL literal.
// SELECT * FROM player ORDER BY name let table = Table<Player>("player") let request = table.order(literal: "name")Declaration
Swift
public func order(literal sqlLiteral: SQL) -> QueryInterfaceRequest<RowDecoder> -
Creates a request which fetches limit rows, starting at offset.
// SELECT * FROM player LIMIT 1 let table = Table<Player>("player") let request = table.limit(1)Declaration
Swift
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest<RowDecoder> -
Creates a request that allows you to define expressions that target a specific database table.
See
TableRecord.aliased(_:)for more information.Declaration
Swift
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<RowDecoder> -
Returns a request which embeds the common table expression.
See
TableRecord.with(_:)for more information.Declaration
Swift
public func with<T>(_ cte: CommonTableExpression<T>) -> QueryInterfaceRequest<RowDecoder>Parameters
cteA common table expression.
Return Value
A request.
-
The number of rows.
Declaration
Swift
public func fetchCount(_ db: Database) throws -> IntParameters
dbA database connection.
-
Creates a “Belongs To” association between Self and the destination type, based on a database foreign key.
For more information, see
TableRecord.belongsTo(_:key:using:).Declaration
Swift
public func belongsTo<Destination>( _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> BelongsToAssociation<RowDecoder, Destination> where Destination: TableRecordParameters
destinationThe record type at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.databaseTableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key to the destination table, or when the schema defines several foreign keys to the destination table.
-
Creates a “Has many” association between Self and the destination type, based on a database foreign key.
For more information, see
TableRecord.hasMany(_:key:using:).Declaration
Swift
public func hasMany<Destination>( _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation<RowDecoder, Destination> where Destination: TableRecordParameters
destinationThe record type at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.databaseTableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key from the destination table, or when the schema defines several foreign keys from the destination table.
-
Creates a “Has one” association between Self and the destination type, based on a database foreign key.
For more information, see
TableRecord.hasOne(_:key:using:).Declaration
Swift
public func hasOne<Destination>( _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasOneAssociation<RowDecoder, Destination> where Destination: TableRecordParameters
destinationThe record type at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.databaseTableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key from the destination table, or when the schema defines several foreign keys from the destination table.
-
Creates a “Belongs To” association between Self and the destination table, based on a database foreign key.
For more information, see
TableRecord.belongsTo(_:key:using:).Declaration
Swift
public func belongsTo<Destination>( _ destination: Table<Destination>, key: String? = nil, using foreignKey: ForeignKey? = nil) -> BelongsToAssociation<RowDecoder, Destination>Parameters
destinationThe table at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.tableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key to the destination table, or when the schema defines several foreign keys to the destination table.
-
Creates a “Has many” association between Self and the destination table, based on a database foreign key.
For more information, see
TableRecord.hasMany(_:key:using:).Declaration
Swift
public func hasMany<Destination>( _ destination: Table<Destination>, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation<RowDecoder, Destination>Parameters
destinationThe table at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.tableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key from the destination table, or when the schema defines several foreign keys from the destination table.
-
Creates a “Has one” association between Self and the destination table, based on a database foreign key.
For more information, see
TableRecord.hasOne(_:key:using:).Declaration
Swift
public func hasOne<Destination>( _ destination: Table<Destination>, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasOneAssociation<RowDecoder, Destination>Parameters
destinationThe table at the other side of the association.
keyAn eventual decoding key for the association. By default, it is
destination.databaseTableName.foreignKeyAn eventual foreign key. You need to provide an explicit foreign key when GRDB can’t infer one from the database schema. This happens when the schema does not define any foreign key from the destination table, or when the schema defines several foreign keys from the destination table.
-
Creates an association to a common table expression that you can join or include in another request.
For more information, see
TableRecord.association(to:on:).Declaration
Swift
public func association<Destination>( to cte: CommonTableExpression<Destination>, on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible) -> JoinAssociation<RowDecoder, Destination>Parameters
cteA common table expression.
conditionA function that returns the joining clause.
leftA
TableAliasfor the left table.rightA
TableAliasfor the right table.Return Value
An association to the common table expression.
-
Creates an association to a common table expression that you can join or include in another request.
The key of the returned association is the table name of the common table expression.
Declaration
Swift
public func association<Destination>( to cte: CommonTableExpression<Destination>) -> JoinAssociation<RowDecoder, Destination>Parameters
cteA common table expression.
Return Value
An association to the common table expression.
-
Creates a “Has Many Through” association between Self and the destination type.
For more information, see
TableRecord.hasMany(_:through:using:key:).Declaration
Swift
public func hasMany<Pivot, Target>( _ destination: Target.RowDecoder.Type, through pivot: Pivot, using target: Target, key: String? = nil) -> HasManyThroughAssociation<RowDecoder, Target.RowDecoder> where Pivot: Association, Target: Association, Pivot.OriginRowDecoder == RowDecoder, Pivot.RowDecoder == Target.OriginRowDecoderParameters
destinationThe record type at the other side of the association.
pivotAn association from Self to the intermediate type.
targetA target association from the intermediate type to the destination type.
keyAn eventual decoding key for the association. By default, it is the same key as the target.
-
Creates a “Has One Through” association between Self and the destination type.
For more information, see
TableRecord.hasOne(_:through:using:key:).Declaration
Swift
public func hasOne<Pivot, Target>( _ destination: Target.RowDecoder.Type, through pivot: Pivot, using target: Target, key: String? = nil) -> HasOneThroughAssociation<RowDecoder, Target.RowDecoder> where Pivot: AssociationToOne, Target: AssociationToOne, Pivot.OriginRowDecoder == RowDecoder, Pivot.RowDecoder == Target.OriginRowDecoderParameters
destinationThe record type at the other side of the association.
pivotAn association from Self to the intermediate type.
targetA target association from the intermediate type to the destination type.
keyAn eventual decoding key for the association. By default, it is the same key as the target.
-
Creates a request that prefetches an association.
Declaration
Swift
public func including<A: AssociationToMany>(all association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder -
Creates a request that includes an association. The columns of the associated record are selected. The returned association does not require that the associated database table contains a matching row.
Declaration
Swift
public func including<A: Association>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder -
Creates a request that includes an association. The columns of the associated record are selected. The returned association requires that the associated database table contains a matching row.
Declaration
Swift
public func including<A: Association>(required association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder -
Creates a request that includes an association. The columns of the associated record are not selected. The returned association does not require that the associated database table contains a matching row.
Declaration
Swift
public func joining<A: Association>(optional association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder -
Creates a request that includes an association. The columns of the associated record are not selected. The returned association requires that the associated database table contains a matching row.
Declaration
Swift
public func joining<A: Association>(required association: A) -> QueryInterfaceRequest<RowDecoder> where A.OriginRowDecoder == RowDecoder
-
Creates a request with aggregates appended to the selection.
// SELECT player.*, COUNT(DISTINCT book.id) AS bookCount // FROM player LEFT JOIN book ... let table = Table<Player>("player") let request = table.annotated(with: Player.books.count)Declaration
Swift
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with aggregates appended to the selection.
// SELECT player.*, COUNT(DISTINCT book.id) AS bookCount // FROM player LEFT JOIN book ... let table = Table<Player>("player") let request = table.annotated(with: [Player.books.count])Declaration
Swift
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest<RowDecoder> -
Creates a request with the provided aggregate predicate.
// SELECT player.* // FROM player LEFT JOIN book ... // HAVING COUNT(DISTINCT book.id) = 0 let table = Table<Player>("player") var request = table.all() request = request.having(Player.books.isEmpty)The selection defaults to all columns. This default can be changed for all requests by the
TableRecord.databaseSelectionproperty, or for individual requests with theTableRecord.selectmethod.Declaration
Swift
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest<RowDecoder>
-
Deletes all rows; returns the number of deleted rows.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
@discardableResult public func deleteAll(_ db: Database) throws -> IntParameters
dbA database connection.
Return Value
The number of deleted rows
-
Delete rows identified by their primary keys; returns the number of deleted rows.
// DELETE FROM player WHERE id IN (1, 2, 3) try Table("player").deleteAll(db, keys: [1, 2, 3]) // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') try Table("country").deleteAll(db, keys: ["FR", "US", "DE"])When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid IN (1, 2, 3) try Table("document").deleteAll(db, keys: [1, 2, 3])Declaration
Swift
@discardableResult public func deleteAll<Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertibleParameters
dbA database connection.
keysA sequence of primary keys.
Return Value
The number of deleted rows
-
Delete a row, identified by its primary key; returns whether a database row was deleted.
// DELETE FROM player WHERE id = 123 try Table("player").deleteOne(db, key: 123) // DELETE FROM country WHERE code = 'FR' try Table("country").deleteOne(db, key: "FR")When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid = 1 try Table("document").deleteOne(db, key: 1)Declaration
Swift
@discardableResult public func deleteOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Bool where PrimaryKeyType: DatabaseValueConvertibleParameters
dbA database connection.
keyA primary key value.
Return Value
Whether a database row was deleted.
-
Delete rows identified by the provided unique keys (primary key or any key with a unique index on it); returns the number of deleted rows.
try Table("player").deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])Declaration
Swift
@discardableResult public func deleteAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> IntParameters
dbA database connection.
keysAn array of key dictionaries.
Return Value
The number of deleted rows
-
Delete a row, identified by a unique key (the primary key or any key with a unique index on it); returns whether a database row was deleted.
Table("player").deleteOne(db, key: ["name": Arthur"])Declaration
Swift
@discardableResult public func deleteOne(_ db: Database, key: [String : DatabaseValueConvertible?]) throws -> BoolParameters
dbA database connection.
keyA dictionary of values.
Return Value
Whether a database row was deleted.
-
Updates all rows; returns the number of updated rows.
For example:
try dbQueue.write { db in // UPDATE player SET score = 0 try Table("player").updateAll(db, [Column("score").set(to: 0)]) }Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
@discardableResult public func updateAll( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignments: [ColumnAssignment]) throws -> IntParameters
dbA database connection.
conflictResolutionA policy for conflict resolution.
assignmentsAn array of column assignments.
Return Value
The number of updated rows.
-
Updates all rows; returns the number of updated rows.
For example:
try dbQueue.write { db in // UPDATE player SET score = 0 try Table("player").updateAll(db, Column("score").set(to: 0)) }Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
@discardableResult public func updateAll( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, _ assignment: ColumnAssignment, _ otherAssignments: ColumnAssignment...) throws -> IntParameters
dbA database connection.
conflictResolutionA policy for conflict resolution.
assignmentA column assignment.
otherAssignmentsEventual other column assignments.
Return Value
The number of updated rows.
-
Create a
TableofRow.let table = Table("player") // Table<Row>Declaration
Swift
public init(_ tableName: String)
-
Creates a request filtered by primary key.
// SELECT * FROM player WHERE id = 1 let table = Table<Player>("player") let request = table.filter(id: 1)Declaration
Swift
public func filter(id: RowDecoder.ID) -> QueryInterfaceRequest<RowDecoder>Parameters
idA primary key
-
Creates a request filtered by primary key.
// SELECT * FROM player WHERE id IN (1, 2, 3) let table = Table<Player>("player") let request = table.filter(ids: [1, 2, 3])Declaration
Swift
public func filter<Collection>(ids: Collection) -> QueryInterfaceRequest<RowDecoder> where Collection: Swift.Collection, Collection.Element == RowDecoder.IDParameters
idsA collection of primary keys
-
Creates a request which selects the primary key.
// SELECT id FROM player let table = Table("player") let request = try table.selectID()Declaration
Swift
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
Available where RowDecoder: Identifiable, RowDecoder.ID: _OptionalProtocol, RowDecoder.ID.Wrapped: DatabaseValueConvertible
-
Creates a request filtered by primary key.
// SELECT * FROM player WHERE id = 1 let table = Table<Player>("player") let request = table.filter(id: 1)Declaration
Swift
public func filter(id: RowDecoder.ID.Wrapped) -> QueryInterfaceRequest<RowDecoder>Parameters
idA primary key
-
Creates a request filtered by primary key.
// SELECT * FROM player WHERE id IN (1, 2, 3) let table = Table<Player>("player") let request = table.filter(ids: [1, 2, 3])Declaration
Swift
public func filter<Collection>(ids: Collection) -> QueryInterfaceRequest<RowDecoder> where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.WrappedParameters
idsA collection of primary keys
-
Creates a request which selects the primary key.
// SELECT id FROM player let table = Table("player") let request = try table.selectID()Declaration
Swift
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID.Wrapped>
-
A cursor over all records fetched from the database.
// SELECT * FROM player let table = Table<Player>("player") let players = try table.fetchCursor(db) // Cursor of Player while let player = try players.next() { // Player ... }Records are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all records fetched from the database.
// SELECT * FROM player let table = Table<Player>("player") let players = try table.fetchAll(db) // [Player]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchAll(_ db: Database) throws -> [RowDecoder]Parameters
dbA database connection.
-
The first found record.
// SELECT * FROM player LIMIT 1 let table = Table<Player>("player") let player = try table.fetchOne(db) // Player?Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchOne(_ db: Database) throws -> RowDecoder?Parameters
dbA database connection.
-
A set of all records fetched from the database.
// SELECT * FROM player let table = Table<Player>("player") let players = try table.fetchSet(db) // Set<Player>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchSet(_ db: Database) throws -> Set<RowDecoder>Parameters
dbA database connection.
-
A cursor over all rows fetched from the database.
// SELECT * FROM player let table = Table("player") let rows = try table.fetchCursor(db) // Cursor of Row while let row = try rows.next() { // Row ... }Rows are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all rows fetched from the database.
// SELECT * FROM player let table = Table("player") let players = try table.fetchAll(db) // [Row]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Parameters
dbA database connection.
-
The first found row.
// SELECT * FROM player LIMIT 1 let table = Table("player") let row = try table.fetchOne(db) // Row?Throws
A DatabaseError is thrown whenever an SQLite error occurs.Parameters
dbA database connection.
-
A set of all rows fetched from the database.
// SELECT * FROM player let table = Table("player") let rows = try table.fetchSet(db) // Set<Row>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Parameters
dbA database connection.
-
A cursor over all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchCursor(db) // Cursor of String while let name = try names.next() { // String ... }Values are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchAll(db) // [String]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchAll(_ db: Database) throws -> [RowDecoder]Parameters
dbA database connection.
-
The value from the leftmost column of the first row.
// SELECT * FROM name LIMIT 1 let table = Table<String>("name") let name = try table.fetchOne(db) // String?Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchOne(_ db: Database) throws -> RowDecoder?Parameters
dbA database connection.
-
A set of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchSet(db) // Set<String>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchSet(_ db: Database) throws -> Set<RowDecoder>Parameters
dbA database connection.
-
A cursor over all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchCursor(db) // Cursor of String? while let name = try names.next() { // String? ... }Values are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder.Wrapped>Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchAll(db) // [String?]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?]Parameters
dbA database connection.
-
The value from the leftmost column of the first row.
// SELECT * FROM name LIMIT 1 let table = Table<String?>("name") let name = try table.fetchOne(db) // String?The result is nil if the query returns no row, or if no value can be extracted from the first row.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped?Parameters
dbA database connection.
Available where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & Hashable
-
A set of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchSet(db) // Set<String?>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchSet(_ db: Database) throws -> Set<RowDecoder.Wrapped?>Parameters
dbA database connection.
-
A cursor over all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchCursor(db) // Cursor of String while let name = try names.next() { // String ... }Values are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder>Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchAll(db) // [String]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchAll(_ db: Database) throws -> [RowDecoder]Parameters
dbA database connection.
-
The value from the leftmost column of the first row.
// SELECT * FROM name LIMIT 1 let table = Table<String>("name") let name = try table.fetchOne(db) // String?Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchOne(_ db: Database) throws -> RowDecoder?Parameters
dbA database connection.
-
A set of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String>("name") let names = try table.fetchSet(db) // Set<String>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchSet(_ db: Database) throws -> Set<RowDecoder>Parameters
dbA database connection.
Available where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible
-
A cursor over all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchCursor(db) // Cursor of String? while let name = try names.next() { // String? ... }Values are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder.Wrapped>Parameters
dbA database connection.
Return Value
A cursor over fetched records.
-
An array of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchAll(db) // [String?]Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?]Parameters
dbA database connection.
-
The value from the leftmost column of the first row.
// SELECT * FROM name LIMIT 1 let table = Table<String?>("name") let name = try table.fetchOne(db) // String?The result is nil if the query returns no row, or if no value can be extracted from the first row.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped?Parameters
dbA database connection.
Available where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable
-
A set of all values fetched from the leftmost column.
// SELECT * FROM name let table = Table<String?>("name") let names = try table.fetchSet(db) // Set<String?>Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public func fetchSet(_ db: Database) throws -> Set<RowDecoder.Wrapped?>Parameters
dbA database connection.
-
Delete rows identified by their primary keys; returns the number of deleted rows.
// DELETE FROM player WHERE id IN (1, 2, 3) try Table<Player>("player").deleteAll(db, ids: [1, 2, 3]) // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') try Table<Country>("country").deleteAll(db, ids: ["FR", "US", "DE"])When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid IN (1, 2, 3) try Table<Document>("document").deleteAll(db, ids: [1, 2, 3])Declaration
Swift
@discardableResult public func deleteAll<Collection>(_ db: Database, ids: Collection) throws -> Int where Collection: Swift.Collection, Collection.Element == RowDecoder.IDParameters
dbA database connection.
idsA collection of primary keys.
Return Value
The number of deleted rows
-
Delete a row, identified by its primary key; returns whether a database row was deleted.
// DELETE FROM player WHERE id = 123 try Player.deleteOne(db, id: 123) // DELETE FROM country WHERE code = 'FR' try Country.deleteOne(db, id: "FR")When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid = 1 try Document.deleteOne(db, id: 1)Declaration
Swift
@discardableResult public func deleteOne(_ db: Database, id: RowDecoder.ID) throws -> BoolParameters
dbA database connection.
idA primary key value.
Return Value
Whether a database row was deleted.
Available where RowDecoder: Identifiable, RowDecoder.ID: _OptionalProtocol, RowDecoder.ID.Wrapped: DatabaseValueConvertible
-
Delete rows identified by their primary keys; returns the number of deleted rows.
// DELETE FROM player WHERE id IN (1, 2, 3) try Table<Player>("player").deleteAll(db, ids: [1, 2, 3]) // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') try Table<Country>("country").deleteAll(db, ids: ["FR", "US", "DE"])When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid IN (1, 2, 3) try Table<Document>("document").deleteAll(db, ids: [1, 2, 3])Declaration
Swift
@discardableResult public func deleteAll<Collection>(_ db: Database, ids: Collection) throws -> Int where Collection: Swift.Collection, Collection.Element == RowDecoder.ID.WrappedParameters
dbA database connection.
idsA collection of primary keys.
Return Value
The number of deleted rows
-
Delete a row, identified by its primary key; returns whether a database row was deleted.
// DELETE FROM player WHERE id = 123 try Table<Player>("player").deleteOne(db, id: 123) // DELETE FROM country WHERE code = 'FR' try Table<Country>("country").deleteOne(db, id: "FR")When the table has no explicit primary key, GRDB uses the hidden “rowid” column:
// DELETE FROM document WHERE rowid = 1 try Table<Document>("document").deleteOne(db, id: 1)Declaration
Swift
@discardableResult public func deleteOne(_ db: Database, id: RowDecoder.ID.Wrapped) throws -> BoolParameters
dbA database connection.
idA primary key value.
Return Value
Whether a database row was deleted.
View on GitHub
Install in Dash
Table Structure Reference