Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2020-01-08 08:25:30 +01:00
commit 183612a4e3
29 files changed
+860 -340

No files matched your search

+5
View File
@@ -1,6 +1,11 @@
# The OS X Build Environment
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
branches:
only:
- master
- development
language: objective-c
xcode_project: GRDB.xcodeproj
+10
View File
@@ -13,6 +13,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 4.x Releases
- `4.8.x` Releases - [4.7.0](#480)
- `4.7.x` Releases - [4.7.0](#470)
- `4.6.x` Releases - [4.6.0](#460) | [4.6.1](#461) | [4.6.2](#462)
- `4.5.x` Releases - [4.5.0](#450)
@@ -65,6 +66,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
-->
## 4.8.0
Released January 8, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.7.0...v4.8.0)
**New**
- [#676](https://github.com/groue/GRDB.swift/pull/676): More batch delete and update
## 4.7.0
Released December 18, 2019 • [diff](https://github.com/groue/GRDB.swift/compare/v4.6.2...v4.7.0)
+58 -4
View File
@@ -283,7 +283,7 @@ See [Convention for the HasOne Association] for some sample code that defines th
The **HasManyThrough** association is often used to set up a many-to-many connection with another record. This association indicates that the declaring record can be matched with zero or more instances of another record by proceeding through a third record. For example, consider the practice of passport delivery. The relevant association declarations could look like this:
```swift
struct Country: TableRecord, EncodableRecord {
struct Country: TableRecord {
static let passports = hasMany(Passport.self)
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
...
@@ -294,7 +294,7 @@ struct Passport: TableRecord {
static let citizen = belongsTo(Citizen.self)
}
struct Citizen: TableRecord, EncodableRecord {
struct Citizen: TableRecord {
static let passports = hasMany(Passport.self)
static let countries = hasMany(Country.self, through: passports, using: Passport.country)
...
@@ -342,9 +342,9 @@ See [Building Requests from Associations] in order to learn how to use the HasMa
A **HasOneThrough** association sets up a one-to-one connection with another record. This association indicates that the declaring record can be matched with one instance of another record by proceeding through a third record. For example, if each book belongs to a library, and each library has one address, then one knows where the book should be returned to:
```swift
struct Book: TableRecord, EncodableRecord {
struct Book: TableRecord {
static let library = belongsTo(Library.self)
static let returnAddress = hasOne(Address.self, through: library, using: library.address)
static let returnAddress = hasOne(Address.self, through: library, using: Library.address)
...
}
@@ -1374,6 +1374,60 @@ When you join or include an association several times, with the same **[associat
.including(optional: association.select(selection2))
```
**Those rules exist so that you can design fluent interfaces that build complex requests out of simple building blocks.**
For example, we can start by defining base requests as extensions to the [DerivableRequest Protocol]:
```swift
// Author requests
extension DerivableRequest where RowDecoder == Author {
/// Filters authors by country
func filter(country: String) -> Self {
return filter(Column("country") == country)
}
}
// Book requests
extension DerivableRequest where RowDecoder == Book {
/// Filters books by author country
func filter(authorCountry: String) -> Self {
return joining(required: Book.author.filter(country: country))
}
/// Order books by author name and then book title
func orderedByAuthorNameAndYear() -> Self {
let authorAlias = TableAlias()
return self
.joining(optional: Book.author.aliased(authorAlias))
.order(
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
Column("year"))
}
}
```
And then compose those in a fluent style:
```swift
struct BookInfo: FetchableRecord, Decodable {
var book: Book
var author: Author
}
// SELECT book.*, author.*
// FROM book
// JOIN author ON author.id = book.authorId AND author.country = 'FR'
// ORDER BY author.name COLLATE ..., book.year
let bookInfos = try Book.all()
.filter(authorCountry: "FR")
.orderedByAuthorNameAndYear()
.including(required: Book.author)
.asRequest(of: BookInfo.self)
.fetchAll(db)
```
Remember that those refinement rules only apply when an association is joined or included several times, with the same **[association key](#the-structure-of-a-joined-request)**. Changing this key stops merging associations together. See [Isolation of Multiple Aggregates] for a longer discussion.
Fetching Values from Associations
=================================
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '4.7.0'
s.version = '4.8.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+7 -1
View File
@@ -360,8 +360,14 @@ extension Database {
where T.Iterator.Element == String
{
// Check primaryKey first, so that we fail early if the table does not exist
let primaryKey = try self.primaryKey(tableName)
let lowercasedColumns = Set(columns.map { $0.lowercased() })
// Assume "rowid" is a primary key
if lowercasedColumns == ["rowid"] {
return ["rowid"]
}
let primaryKey = try self.primaryKey(tableName)
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
return primaryKey.columns
}
+3 -23
View File
@@ -570,29 +570,9 @@ public final class Database {
/// Grants read-only access, starting SQLite 3.8.0
func readOnly<T>(_ block: () throws -> T) throws -> T {
try beginReadOnly()
var result: T?
var thrownError: Error?
do {
result = try block()
} catch {
thrownError = error
}
do {
try endReadOnly()
} catch {
if thrownError == nil {
thrownError = error
}
}
if let error = thrownError {
throw error
}
return result!
return try throwingFirstError(
execute: block,
finally: endReadOnly)
}
// MARK: - Authorizer
+9 -5
View File
@@ -227,7 +227,7 @@ public final class DatabaseFunction: Hashable {
return { (sqliteContext, argc, argv) in
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
let aggregateContext = aggregateContextU.takeUnretainedValue()
assert(!aggregateContext.hasErrored)
assert(!aggregateContext.hasErrored) // assert SQLite behavior
do {
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
@@ -272,20 +272,24 @@ public final class DatabaseFunction: Hashable {
/// See https://sqlite.org/c3ref/context.html
/// See https://sqlite.org/c3ref/aggregate_context.html
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// The current aggregate buffer
// > The first time the sqlite3_aggregate_context(C,N) routine is called
// > for a particular aggregate function, SQLite allocates N of memory,
// > zeroes out that memory, and returns a pointer to the new memory.
// > On second and subsequent calls to sqlite3_aggregate_context() for
// > the same aggregate function instance, the same buffer is returned.
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
// Buffer contains non-null pointer: load aggregate context
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
// Buffer contains non-zero byte: load aggregate context
let aggregateContextP = aggregateContextBufferP
.baseAddress!
.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
} else {
// Buffer contains null pointer: create aggregate context...
// Buffer contains null pointer: create aggregate context.
let aggregate = Unmanaged<AggregateDefinition>.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
.makeAggregate()
+18 -22
View File
@@ -291,29 +291,25 @@ extension DatabaseWriter {
try db.execute(sql: "PRAGMA foreign_keys = OFF")
}
// Remove all database objects, one after the other
do {
try db.inTransaction {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(db, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
try throwingFirstError(
execute: {
// Remove all database objects, one after the other
try db.inTransaction {
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
while let row = try Row.fetchOne(db, sql: sql) {
let type: String = row["type"]
let name: String = row["name"]
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
return .commit
}
// Restore foreign keys if needed
if foreignKeysEnabled {
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
} catch {
// Restore foreign keys if needed
if foreignKeysEnabled {
try? db.execute(sql: "PRAGMA foreign_keys = ON")
}
throw error
}
},
finally: {
// Restore foreign keys if needed
if foreignKeysEnabled {
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
})
}
#else
try DatabaseQueue().backup(to: self)
+29 -26
View File
@@ -53,32 +53,35 @@ struct Migration {
// > PRAGMA foreign_keys=OFF.
try db.execute(sql: "PRAGMA foreign_keys = OFF")
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
// > 10. If foreign key constraints were originally enabled then run PRAGMA
// > foreign_key_check to verify that the schema change did not break any foreign key
// > constraints.
if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil {
// https://www.sqlite.org/pragma.html#pragma_foreign_key_check
//
// PRAGMA foreign_key_check does not return an error,
// but the list of violated foreign key constraints.
//
// Let's turn any violation into an SQLITE_CONSTRAINT
// error, and rollback the transaction.
throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
}
// > 11. Commit the transaction started in step 2.
return .commit
}
// TODO: we should restore foreign_keys in case of error as well
// > 12. If foreign keys constraints were originally enabled, reenable them now.
try db.execute(sql: "PRAGMA foreign_keys = ON")
try throwingFirstError(
execute: {
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
try migrate(db)
try insertAppliedIdentifier(db)
// > 10. If foreign key constraints were originally enabled then run PRAGMA
// > foreign_key_check to verify that the schema change did not break any foreign key
// > constraints.
if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil {
// https://www.sqlite.org/pragma.html#pragma_foreign_key_check
//
// PRAGMA foreign_key_check does not return an error,
// but the list of violated foreign key constraints.
//
// Let's turn any violation into an SQLITE_CONSTRAINT
// error, and rollback the transaction.
throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed")
}
// > 11. Commit the transaction started in step 2.
return .commit
}
},
finally: {
// > 12. If foreign keys constraints were originally enabled, reenable them now.
try db.execute(sql: "PRAGMA foreign_keys = ON")
})
}
private func insertAppliedIdentifier(_ db: Database) throws {
@@ -72,4 +72,31 @@ public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
init(
key: String?,
using foreignKey: ForeignKey?)
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: Origin.databaseTableName,
destinationTable: Destination.databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: true)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedSingular(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toOne)
}
}
@@ -72,4 +72,31 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
init(
key: String?,
using foreignKey: ForeignKey?)
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: Origin.databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedPlural(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toMany)
}
}
@@ -74,4 +74,31 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
init(
key: String?,
using foreignKey: ForeignKey?)
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: Origin.databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedSingular(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
sqlAssociation = SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toOne)
}
}
@@ -6,7 +6,7 @@
///
/// struct Book: TableRecord {
/// static let library = belongsTo(Library.self)
/// static let returnAddress = hasOne(Address.self, through: library, using: library.address)
/// static let returnAddress = hasOne(Address.self, through: library, using: Library.address)
/// ...
/// }
///
@@ -223,15 +223,6 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: [Column("name")])
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest {
// TODO: test consumption of
//
// let author = TableAlias()
// let request = Book
// .annotated(with: [author[Column("name")]])
// .joining(requireed: Book.author)
//
// The problem is the "author.name" column. Can we consume it as "name"?
// From raw rows? From copied rows?
return mapQuery { $0.annotated(with: selection) }
}
}
+1 -1
View File
@@ -65,7 +65,7 @@ public struct Column: ColumnExpression {
/// A qualified column in the database, as in `SELECT t.a FROM t`
struct QualifiedColumn: ColumnExpression {
var name: String
private let alias: TableAlias
let alias: TableAlias
/// Creates a column given its name.
init(_ name: String, alias: TableAlias) {
+2
View File
@@ -56,6 +56,8 @@ extension SQLQuery {
}
func qualified(with alias: TableAlias) -> SQLQuery {
// We do not need to qualify group and having clauses. They will be
// in SQLQueryGenerator.init()
return mapRelation { $0.qualified(with: alias) }
}
}
@@ -20,22 +20,10 @@ public struct SQLGenerationContext {
/// Used for SQLQuery.makeSelectStatement() and SQLQuery.makeDeleteStatement()
static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext {
// TODO: since 5d9fa76, in the lines below, we started uniquing aliases.
// Something tells me this is a wrong fix. We should try to investigate
// and maybe revert this change. I don't see why we'd really need to
// unique aliases, and I'm afraid we're hiding some latent bug
// somewhere else.
// Unique aliases, but with preserved ordering, so that we have stable SQL generation
let uniqueAliases = aliases.reduce(into: [TableAlias]()) {
if !$0.contains($1) {
$0.append($1)
}
}
return SQLGenerationContext(
arguments: [],
resolvedNames: uniqueAliases.resolvedNames,
qualifierNeeded: uniqueAliases.count > 1)
resolvedNames: aliases.resolvedNames,
qualifierNeeded: aliases.count > 1)
}
/// Used for TableRecord.selectionSQL
@@ -1,6 +1,6 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator {
fileprivate let relation: SQLQualifiedRelation
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressions: [SQLExpression]
@@ -35,7 +35,7 @@ struct SQLQueryGenerator {
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
let alias = relation.alias
groupPromise = query.groupPromise?.map { [alias] in $0.map { $0.qualifiedExpression(with: alias) } }
groupPromise = query.groupPromise?.map { $0.map { $0.qualifiedExpression(with: alias) } }
havingExpressions = query.havingExpressions.map { $0.qualifiedExpression(with: alias) }
// Preserve other flags
@@ -121,48 +121,69 @@ struct SQLQueryGenerator {
return databaseRegion
}
// Database regions are case-insensitive: use the canonical table name
// Database regions are case-sensitive: use the canonical table name
let canonicalTableName = try db.canonicalTableName(tableName)
return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds)
}
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
switch try grouping(db) {
case .none:
guard case .table = relation.source else {
// Programmer error
fatalError("Can't delete without any database table")
}
guard relation.joins.isEmpty else {
return try makeTrivialDeleteStatement(db)
}
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments!
return statement
case .unique:
return try makeTrivialDeleteStatement(db)
case .nonUnique:
// Programmer error
fatalError("Can't delete query with GROUP BY clause")
}
guard havingExpressions.isEmpty else {
// Programmer error
fatalError("Can't delete query with HAVING clause")
}
guard relation.joins.isEmpty else {
// Programmer error
fatalError("Can't delete query with JOIN clause")
}
guard case .table = relation.source else {
}
/// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard case let .table(tableName: tableName, alias: _) = relation.source else {
// Programmer error
fatalError("Can't delete without any database table")
}
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
// SELECT rowid FROM table ...
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
let selectSQL = try generator.sql(db, &context)
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments!
@@ -176,39 +197,104 @@ struct SQLQueryGenerator {
assignments: [ColumnAssignment])
throws -> UpdateStatement?
{
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
switch try grouping(db) {
case .none:
guard case .table = relation.source else {
// Programmer error
fatalError("Can't update without any database table")
}
guard relation.joins.isEmpty else {
return try makeTrivialUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments)
}
// Check for empty assignments after all programmer errors have
// been checked.
if assignments.isEmpty {
return nil
}
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
var sql = "UPDATE "
if conflictResolution != .abort {
sql += "OR \(conflictResolution.rawValue) "
}
sql += try relation.source.sql(db, &context)
let assignmentsSQL = assignments
.map({ assignment in
assignment.column.expressionSQL(&context, wrappedInParenthesis: false) +
" = " +
assignment.value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
})
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments!
return statement
case .unique:
return try makeTrivialUpdateStatement(db, conflictResolution: conflictResolution, assignments: assignments)
case .nonUnique:
// Programmer error
fatalError("Can't update query with GROUP BY clause")
}
guard havingExpressions.isEmpty else {
}
/// UPDATE table SET ... WHERE rowid IN (SELECT rowid FROM table ...)
/// Returns nil if assignments is empty
private func makeTrivialUpdateStatement(
_ db: Database,
conflictResolution: Database.ConflictResolution,
assignments: [ColumnAssignment])
throws -> UpdateStatement?
{
guard case let .table(tableName: tableName, alias: _) = relation.source else {
// Programmer error
fatalError("Can't update query with HAVING clause")
}
guard relation.joins.isEmpty else {
// Programmer error
fatalError("Can't update query with JOIN clause")
}
guard case .table = relation.source else {
// Programmer error
fatalError("Can't update without any database table")
fatalError("Can't delete without any database table")
}
// Check for empty assignments after all programmer errors have
// been checked.
if assignments.isEmpty {
return nil
}
var context = SQLGenerationContext.queryGenerationContext(aliases: relation.allAliases)
// SELECT rowid FROM table ...
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
let selectSQL = try generator.sql(db, &context)
var sql = "UPDATE "
if conflictResolution != .abort {
sql += "OR \(conflictResolution.rawValue) "
}
sql += try relation.source.sql(db, &context)
sql += tableName.quotedDatabaseIdentifier
let assignmentsSQL = assignments
.map({ assignment in
@@ -218,25 +304,13 @@ struct SQLQueryGenerator {
})
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
let filters = try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " WHERE " + SQLExpressionAnd(filters).expressionSQL(&context, wrappedInParenthesis: false)
}
if let limit = limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
}
sql += " LIMIT " + limit.sql
}
sql += " WHERE rowid IN (\(selectSQL))"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments!
return statement
}
/// Returns a select statement
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
// Build an SQK generation context with all aliases found in the query,
@@ -256,6 +330,56 @@ struct SQLQueryGenerator {
return statement
}
/// Informs about the query grouping
private enum GroupingInfo {
/// No grouping at all: SELECT ... FROM player
case none
/// Grouped by unique key: SELECT ... FROM player GROUP BY id
case unique
/// Grouped by some non-unique columnns: SELECT ... FROM player GROUP BY teamId
case nonUnique
}
/// Informs about the query grouping
private func grouping(_ db: Database) throws -> GroupingInfo {
// Empty group clause: no grouping
// SELECT * FROM player
guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
return .none
}
// Grouping by something which is not a column: assume non
// unique grouping.
// SELECT * FROM player GROUP BY (score + bonus)
let qualifiedColumns = groupExpressions.compactMap { $0 as? QualifiedColumn }
if qualifiedColumns.count != groupExpressions.count {
return .nonUnique
}
// Grouping something which is not a table: assume non unique grouping.
guard case let .table(tableName: tableName, alias: alias) = relation.source else {
return .nonUnique
}
// Grouping by some column(s) which do not come from the main table:
// assume non unique grouping.
// SELECT * FROM player JOIN team ... GROUP BY team.id
guard qualifiedColumns.allSatisfy({ $0.alias == alias }) else {
return .nonUnique
}
// Grouping by some column(s) which are unique
// SELECT * FROM player GROUP BY id
let columnNames = qualifiedColumns.map { $0.name }
if try db.table(tableName, hasUniqueKey: columnNames) {
return .unique
}
// Grouping by some column(s) which are not unique
// SELECT * FROM player GROUP BY score
return .nonUnique
}
/// Returns the row adapter which presents the fetched rows according to the
/// tree of joined relations.
///
@@ -288,80 +412,72 @@ struct SQLQueryGenerator {
/// A "qualified" relation, where all tables are identified with a table alias.
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// | | | | | |
/// | | | | | • ordering
/// | | | | • filterPromise
/// | | | • joins
/// | | • alias
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// | | | | |
/// | | | | • ordering
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • fullSelection
/// • selection
private struct SQLQualifiedRelation {
/// The alias for the relation
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • alias
let alias: TableAlias
/// The source alias
var alias: TableAlias { return source.alias }
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
var aliases = [alias]
for join in joins.values {
aliases.append(contentsOf: join.relation.allAliases)
return joins.reduce(into: source.allAliases) {
$0.append(contentsOf: $1.value.relation.allAliases)
}
aliases.append(contentsOf: source.allAliases)
return aliases
}
/// The source
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • source
let source: SQLQualifiedSource
/// The selection, not including selection of joined relations
private let ownSelection: [SQLSelectable]
/// The selection from source, not including selection of joined relations
private var sourceSelection: [SQLSelectable]
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • fullSelection
/// • selection
var selection: [SQLSelectable] {
return joins.reduce(into: ownSelection) {
return joins.reduce(into: sourceSelection) {
$0.append(contentsOf: $1.value.relation.selection)
}
}
/// The filtering clause
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • filtersPromise
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • filtersPromise
let filtersPromise: DatabasePromise<[SQLExpression]>
/// The ordering, not including ordering of joined relations
private let ownOrdering: SQLRelation.Ordering
/// The ordering of source, not including ordering of joined relations
private let sourceOrdering: SQLRelation.Ordering
/// The full ordering, including orderings of joined relations
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • ordering
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • ordering
var ordering: SQLRelation.Ordering {
return joins.reduce(ownOrdering) {
return joins.reduce(sourceOrdering) {
$0.appending($1.value.relation.ordering)
}
}
/// The joins
///
/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • joins
let joins: OrderedDictionary<String, SQLQualifiedJoin>
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • joins
private(set) var joins: OrderedDictionary<String, SQLQualifiedJoin>
init(_ relation: SQLRelation) {
// Qualify the source, so that it be disambiguated with an SQL alias
@@ -371,7 +487,6 @@ private struct SQLQualifiedRelation {
// this SQLQualifiedRelation generates SQL.
source = SQLQualifiedSource(relation.source)
let alias = source.alias
self.alias = alias
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
@@ -392,9 +507,9 @@ private struct SQLQualifiedRelation {
condition: child.condition,
relation: SQLQualifiedRelation(child.relation))
}
ownSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) }
filtersPromise = relation.filtersPromise.map { [alias] in $0.map { $0.qualifiedExpression(with: alias) } }
ownOrdering = relation.ordering.qualified(with: alias)
sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: alias) }
filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: alias) } }
sourceOrdering = relation.ordering.qualified(with: alias)
}
/// See SQLQueryGenerator.rowAdapter(_:)
@@ -413,15 +528,15 @@ private struct SQLQualifiedRelation {
return nil
}
// The number of columns in own selection. Columns selected by joined
// The number of columns in source selection. Columns selected by joined
// relations are appended after.
let selectionWidth = try ownSelection
.map { try $0.columnCount(db) }
.reduce(0, +)
let sourceSelectionWidth = try sourceSelection.reduce(0) {
try $0 + $1.columnCount(db)
}
// Recursively build adapters for each joined relation with a selection.
// Name them according to the join keys.
var endIndex = startIndex + selectionWidth
var endIndex = startIndex + sourceSelectionWidth
var scopes: [String: RowAdapter] = [:]
for (key, join) in joins {
if let (joinAdapter, joinEndIndex) = try join.relation.rowAdapter(db, fromIndex: endIndex) {
@@ -431,7 +546,7 @@ private struct SQLQualifiedRelation {
}
// (Root relation || empty selection) && no included relation => no need for any adapter
if (startIndex == 0 || selectionWidth == 0) && scopes.isEmpty {
if (startIndex == 0 || sourceSelectionWidth == 0) && scopes.isEmpty {
return nil
}
@@ -451,11 +566,19 @@ private struct SQLQualifiedRelation {
// row.scopes["author"] // [id:12, name:"Herman Melville"]
// let author: Author = row["author"]
// }
let rangeAdapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth))
let rangeAdapter = RangeRowAdapter(startIndex ..< (startIndex + sourceSelectionWidth))
let adapter = rangeAdapter.addingScopes(scopes)
return (adapter: adapter, endIndex: endIndex)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedRelation {
var relation = self
relation.sourceSelection = selection.map { $0.qualifiedSelectable(with: alias) }
relation.joins = relation.joins.mapValues { $0.selectOnly([]) }
return relation
}
}
/// A "qualified" source, where all tables are identified with a table alias.
@@ -520,6 +643,14 @@ private struct SQLQualifiedJoin {
return try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
return SQLQualifiedJoin(
kind: kind,
condition: condition,
relation: relation.selectOnly(selection))
}
private func sql(
_ db: Database,
_ context: inout SQLGenerationContext,
@@ -61,27 +61,7 @@ extension TableRecord {
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<Self, Destination>
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: databaseTableName,
destinationTable: Destination.databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: true)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedSingular(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
return BelongsToAssociation(sqlAssociation: SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toOne))
return BelongsToAssociation(key: key, using: foreignKey)
}
/// Creates a "Has many" association between Self and the
@@ -146,27 +126,7 @@ extension TableRecord {
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<Self, Destination>
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedPlural(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
return HasManyAssociation(sqlAssociation: SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toMany))
return HasManyAssociation(key: key, using: foreignKey)
}
/// Creates a "Has Many Through" association between Self and the
@@ -313,27 +273,7 @@ extension TableRecord {
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<Self, Destination>
{
let foreignKeyRequest = SQLForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: databaseTableName,
foreignKey: foreignKey)
let condition = SQLAssociationCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
let associationKey: SQLAssociationKey
if let key = key {
associationKey = .fixedSingular(key)
} else {
associationKey = .inflected(Destination.databaseTableName)
}
return HasOneAssociation(sqlAssociation: SQLAssociation(
key: associationKey,
condition: condition,
relation: Destination.all().relation,
cardinality: .toOne))
return HasOneAssociation(key: key, using: foreignKey)
}
/// Creates a "Has One Through" association between Self and the
@@ -341,7 +281,7 @@ extension TableRecord {
///
/// struct Book: TableRecord {
/// static let library = belongsTo(Library.self)
/// static let returnAddress = hasOne(Address.self, through: library, using: library.address)
/// static let returnAddress = hasOne(Address.self, through: library, using: Library.address)
/// }
///
/// struct Library: TableRecord {
@@ -11,16 +11,6 @@ extension TableRecord {
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func all() -> QueryInterfaceRequest<Self> {
// TODO: could we delay selection definition until we know what we are
// really fetching?
//
// Use case:
//
// // Would be nice if it would only fetch SubPlayer columns
// Player.all().asRequest(of: SubPlayer.self)
//
// // Would be nice if it would fetch extra ExtendedPlayer columns
// Player.all().asRequest(of: ExtendedPlayer.self)
let relation = SQLRelation(
source: .table(tableName: databaseTableName, alias: nil),
selection: databaseSelection)
+21
View File
@@ -122,3 +122,24 @@ extension Character {
}
}
#endif
/// Makes sure the `finally` function is executed even if `execute` throws, and
/// rethrows the eventual first thrown error.
///
/// Usage:
///
/// try setup()
/// try throwingFirstError(
/// execute: work,
/// finally: cleanup)
@inline(__always)
func throwingFirstError<T>(execute: () throws -> T, finally: () throws -> Void) throws -> T {
do {
let result = try execute()
try finally()
return result
} catch {
try? finally()
throw error
}
}
+4 -4
View File
@@ -459,12 +459,12 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.7.0 \
--module-version 4.7.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.8.0 \
--module-version 4.8.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/4.7/ \
--root-url http://groue.github.io/GRDB.swift/docs/4.8/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
--podspec GRDB.swift.podspec
else
@echo Jazzy must be installed for doc
@exit 1
+45 -23
View File
@@ -12,14 +12,14 @@
---
**Latest release**: December 18, 2019 • version 4.7.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Latest release**: January 8, 2020 • version 4.8.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 3 to GRDB 4](Documentation/GRDB3MigrationGuide.md)
**Requirements**: iOS 9.0+ / macOS 10.9+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 4.2+ / Xcode 10.0+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5** | **v4.7.0** |
| **Swift 4.2** | **v4.7.0** |
| **Swift 5** | **v4.8.0** |
| **Swift 4.2** | **v4.8.0** |
| Swift 4.1 | [v3.7.0](https://github.com/groue/GRDB.swift/tree/v3.7.0) |
| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) |
| Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) |
@@ -263,7 +263,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.7/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/4.8/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -477,7 +477,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.7/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) for more details.
## Database Pools
@@ -558,7 +558,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.7/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -618,7 +618,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
In Swift 5, you can embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -819,7 +819,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.7/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -901,7 +901,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1184,7 +1184,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1591,7 +1591,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.7/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/4.8/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1705,7 +1705,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1964,7 +1964,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.7/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2426,7 +2426,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2630,6 +2630,7 @@ try place.delete(db) // DELETE
try place.exists(db)
// Type methods
try Place.updateAll(db, ...) // UPDATE
try Place.deleteAll(db) // DELETE
try Place.deleteAll(db, keys:...) // DELETE
try Place.deleteOne(db, key:...) // DELETE
@@ -2641,6 +2642,8 @@ try Place.deleteOne(db, key:...) // DELETE
When saving an object that may or may not already exist in the database, prefer the `save` method:
- `updateAll` performs a batch update. See [Update Requests](#update-requests).
- `save` makes sure your values are stored in the database.
It performs an UPDATE if the record has a non-null primary key, and then, if no row was modified, an INSERT. It directly perfoms an INSERT if the record has no primary key, or a null primary key.
@@ -2804,7 +2807,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.7/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.7/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.7/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/4.8/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -3989,7 +3992,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.all()
```
The hidden `rowid` column can be selected as well [when you need it](#the-implicit-rowid-primary-key).
By default, all columns are selected. See [Columns Selected by a Request].
- `select(...)` and `select(..., as:)` define the selected columns. See [Columns Selected by a Request].
@@ -3998,7 +4001,26 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.select(nameColumn, as: String.self)
```
- `annotated(with: ...)` extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
- `annotated(with: expression...)` extends the selection.
```swift
// SELECT *, (score + bonus) AS total FROM player
Player.annotated(with: (scoreColumn + bonusColumn).forKey("total"))
```
Such annotations can help using [Associations]:
```swift
// SELECT player.*, team.name
// FROM player
// JOIN team ON team.id = player.teamId
let teamAlias = TableAlias()
let request = Player
.annotated(with: teamAlias[nameColumn])
.joining(required: Player.team.aliased(teamAlias))
```
- `annotated(with: aggregate)` extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
```swift
// SELECT team.*, COUNT(DISTINCT player.rowid) AS playerCount
@@ -4172,7 +4194,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.7/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/4.8/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4759,7 +4781,7 @@ let request = Player.all()
**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol.
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.7/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/4.8/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -4803,7 +4825,7 @@ let request = Player.all()
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.7/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/4.8/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request.
### Fetching From Custom Requests
@@ -6337,7 +6359,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.7/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/4.8/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -6347,7 +6369,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.7/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/4.8/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7451,7 +7473,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.7/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.7/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/4.8/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>4.7.0</string>
<string>4.8.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
-1
View File
@@ -20,7 +20,6 @@
## Features
- [ ] Measure the duration of transactions
- [ ] Make deleteAll and updateAll work even for complex queries, with `DELETE FROM xxx WHERE rowid IN (SELECT rowid ...)`
- [ ] Improve SQL generation for `Player.....fetchCount(db)`, especially with distinct. Try to avoid `SELECT COUNT(*) FROM (SELECT DISTINCT player.* ...)`
- [ ] Alternative technique for custom SQLite builds: see the Podfile at https://github.com/CocoaPods/CocoaPods/issues/9104, and https://github.com/clemensg/sqlite3pod
- [ ] Attach databases. Interesting question: what happens when one attaches a non-WAL db to a databasePool?
+3 -1
View File
@@ -56,14 +56,16 @@ class IndexInfoTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["rowid"]))
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["id"]))
try XCTAssertTrue(db.table("persons", hasUniqueKey: ["email"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: []))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["name"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"]))
try XCTAssertFalse(db.table("persons", hasUniqueKey: ["id", "email"])) // TODO: is it expected?
try db.execute(sql: "CREATE TABLE citizenships (year INTEGER, personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
try db.execute(sql: "CREATE INDEX citizenshipsOnYear ON citizenships(year)")
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["rowid"]))
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["personId", "countryIsoCode"]))
try XCTAssertTrue(db.table("citizenships", hasUniqueKey: ["countryIsoCode", "personId"]))
try XCTAssertFalse(db.table("citizenships", hasUniqueKey: []))
@@ -184,4 +184,120 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
}
}
}
func testJoinedRequestDelete() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
static let team = belongsTo(Team.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Team: MutablePersistableRecord {
static let players = hasMany(Player.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
}
do {
try Player.including(required: Player.team).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "player"."rowid" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
}
do {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "p"."rowid" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
}
do {
try Team.having(Team.players.isEmpty).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team" WHERE rowid IN (\
SELECT "team"."rowid" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = 0)
""")
}
do {
try Team.including(all: Team.players).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team"
""")
}
}
}
func testGroupedRequestDelete() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Passport: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer)
}
try db.create(table: "passport") { t in
t.column("countryCode", .text).notNull()
t.column("citizenId", .integer).notNull()
t.primaryKey(["countryCode", "citizenId"])
}
do {
try Player.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
FROM "player" \
GROUP BY "id")
""")
}
do {
try Player.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
FROM "player" \
GROUP BY "rowid")
""")
}
do {
try Passport.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
""")
}
do {
try Passport.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
""")
}
}
}
}
@@ -1,8 +1,8 @@
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
import GRDBCustomSQLite
#else
import GRDB
import GRDB
#endif
private struct Player: Codable, PersistableRecord, FetchableRecord {
@@ -10,6 +10,15 @@ private struct Player: Codable, PersistableRecord, FetchableRecord {
var name: String
var score: Int
var bonus: Int
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
t.column("bonus", .integer)
}
}
}
private enum Columns: String, ColumnExpression {
@@ -23,19 +32,9 @@ private extension QueryInterfaceRequest where RowDecoder == Player {
}
class MutablePersistableRecordUpdateTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
t.column("bonus", .integer)
}
}
}
func testRequestUpdateAll() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
let assignment = Columns.score <- 0
try Player.updateAll(db, assignment)
@@ -57,7 +56,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2)
""")
try Player.filter(sql: "id = 1").updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE id = 1
@@ -67,7 +66,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur')
""")
try Player.select(Columns.name).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
@@ -88,7 +87,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try Player.order(Columns.name).limit(1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 ORDER BY \"name\" LIMIT 1
@@ -109,6 +108,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testComplexAssignment() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score <- Columns.score * (Columns.bonus + 1))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * ("bonus" + 1)
@@ -118,6 +119,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testAssignmentSubtractAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score -= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - 1
@@ -132,7 +135,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - (-"bonus")
""")
try Player.updateAll(db, Columns.score -= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - ("bonus" * 2)
@@ -142,6 +145,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testAssignmentAddAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score += 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + 1
@@ -156,7 +161,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + (-"bonus")
""")
try Player.updateAll(db, Columns.score += Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + ("bonus" * 2)
@@ -166,6 +171,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testAssignmentMultiplyAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score *= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * 1
@@ -180,7 +187,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * (-"bonus")
""")
try Player.updateAll(db, Columns.score *= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * ("bonus" * 2)
@@ -190,6 +197,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testAssignmentDivideAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score /= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / 1
@@ -204,16 +213,18 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / (-"bonus")
""")
try Player.updateAll(db, Columns.score /= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / ("bonus" * 2)
""")
}
}
func testMultipleAssignments() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score <- 0, Columns.bonus <- 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0, "bonus" = 1
@@ -238,15 +249,17 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testUpdateAllWithoutAssignmentDoesNotAccessTheDatabase() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
sqlQueries.removeAll()
try XCTAssertEqual(Player.updateAll(db, []), 0)
try XCTAssertEqual(Player.all().updateAll(db, []), 0)
XCTAssert(sqlQueries.isEmpty)
}
}
func testUpdateAllReturnsNumberOfUpdatedRows() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 0, bonus: 2).insert(db)
try Player(id: 2, name: "Barbara", score: 0, bonus: 1).insert(db)
try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db)
@@ -269,6 +282,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testQueryInterfaceExtension() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 0, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 0, bonus: 0).insert(db)
try Player(id: 3, name: "Craig", score: 0, bonus: 0).insert(db)
@@ -289,6 +303,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func encode(to container: inout PersistenceContainer) { }
}
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try AbortPlayer.updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
@@ -303,7 +319,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try AbortPlayer.all().updateAll(db, [Column("score") <- 0])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
@@ -318,6 +334,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func encode(to container: inout PersistenceContainer) { }
}
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try IgnorePlayer.updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
@@ -342,6 +360,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
func testConflictPolicyCustom() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
@@ -368,4 +388,123 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
""")
}
}
func testJoinedRequestUpdate() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
static let team = belongsTo(Team.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Team: MutablePersistableRecord {
static let players = hasMany(Player.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("active", .boolean)
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.column("score", .integer)
}
do {
try Player.including(required: Player.team).updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "player"."rowid" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
}
do {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "p"."rowid" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
}
do {
try Team.having(Team.players.isEmpty).updateAll(db, Column("active") <- false)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0 WHERE rowid IN (\
SELECT "team"."rowid" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."rowid") = 0)
""")
}
do {
try Team.including(all: Team.players).updateAll(db, Column("active") <- false)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0
""")
}
}
}
func testGroupedRequestUpdate() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Passport: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer)
}
try db.create(table: "passport") { t in
t.column("countryCode", .text).notNull()
t.column("citizenId", .integer).notNull()
t.column("active", .boolean)
t.primaryKey(["countryCode", "citizenId"])
}
do {
try Player.all().groupByPrimaryKey().updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
FROM "player" \
GROUP BY "id")
""")
}
do {
try Player.all().group(Column.rowID).updateAll(db, Column("score") <- 0)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
FROM "player" \
GROUP BY "rowid")
""")
}
do {
try Passport.all().groupByPrimaryKey().updateAll(db, Column("active") <- true)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
""")
}
do {
try Passport.all().group(Column.rowID).updateAll(db, Column("active") <- true)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
""")
}
}
}
}
@@ -278,6 +278,46 @@ class QueryInterfaceRequestTests: GRDBTestCase {
}
}
func testAnnotatedWithForeignColumn() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorId", .integer).references("author")
}
try db.execute(sql: """
INSERT INTO author(id, name) VALUES (1, 'Arthur');
INSERT INTO book(id, authorId) VALUES (2, 1);
""")
struct Author: TableRecord { }
struct Book: TableRecord {
static let author = belongsTo(Author.self)
}
let alias = TableAlias()
let request = Book
.annotated(with: alias[Column("name")])
.joining(required: Book.author.aliased(alias))
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
// Just some sanity checks that the "author"."name" SQL column is
// simply exposed as "name" in Swift code:
XCTAssertEqual(row, ["id":2, "authorId":1, "name":"Arthur"])
XCTAssertEqual(Set(row.columnNames), ["id", "authorId", "name"])
XCTAssertEqual(row["name"], "Arthur")
}
XCTAssertEqual(lastSQLQuery, """
SELECT "book".*, "author"."name" \
FROM "book" \
JOIN "author" ON "author"."id" = "book"."authorId"
""")
}
}
func testMultipleSelect() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(