Compare commits

...
32 Commits
Author SHA1 Message Date
Gwendal Roué a88067a815 Merge branch 'GRDB5' into dev/hasMany-first 2020-04-25 13:31:58 +02:00
Gwendal Roué df4d5b8603 Back to basics, round 2: keep all children of firstOnly relations 2020-04-19 17:44:50 +02:00
Gwendal Roué a7b8a73dba Cleanup
After failed experiment:

SELECT ...
FROM parent
JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id

The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early.

So we're still stuck with:

SELECT ...
FROM parent
JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1)

For some reason SQLite accepts the reference to the parent table in this case.
2020-04-19 14:14:13 +02:00
Gwendal Roué 278c18adfc Cleanup 2020-04-18 20:21:14 +02:00
Gwendal Roué cbd494e3b9 Documentation 2020-04-18 20:19:47 +02:00
Gwendal Roué c73fb0dd9b Back to basics 2020-04-18 20:14:27 +02:00
Gwendal Roué c966eb3ecf Cleanup 2020-04-18 19:09:02 +02:00
Gwendal Roué 217b0a3f3e More failing HasManyThrough.first tests 2020-04-18 17:52:50 +02:00
Gwendal Roué e604a10860 TODO 2020-04-18 17:06:29 +02:00
Gwendal Roué ac4f4c6611 Improve HasMany.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 162da80e4f Attempt at expressing some todos 2020-04-18 17:06:29 +02:00
Gwendal Roué 315496928b More failing HasManyThrough.first 2020-04-18 17:06:29 +02:00
Gwendal Roué d82cbb6853 Improve HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué 5fed231856 Simplify SQLAssociationCondition.filteringExpression 2020-04-18 17:06:29 +02:00
Gwendal Roué 45dfe7d7f1 More HasManyThrough.first tests 2020-04-18 17:06:29 +02:00
Gwendal Roué c7d1cca023 Ease testing SQL by ignoring white space 2020-04-18 17:06:29 +02:00
Gwendal Roué 615f4159d6 Rename firstInMany to firstOnly 2020-04-18 17:06:29 +02:00
Gwendal Roué 8057572357 Move firstInMany flag in SQLRelation 2020-04-18 17:06:29 +02:00
Gwendal Roué da63037948 Fix documentation 2020-04-18 17:06:29 +02:00
Gwendal Roué 2d3dafad7d Document first and last properties, set their association key 2020-04-18 17:06:29 +02:00
Gwendal Roué 7ed967b502 Cleanup SQLAssociationCardinality and SQLAssociationStep 2020-04-18 17:06:29 +02:00
Gwendal Roué f545789205 Avoid using the rowid column when we can use the regular primary key 2020-04-18 17:06:23 +02:00
Gwendal Roué 79373d5b74 Cleanup some old tests 2020-04-18 16:40:22 +02:00
Gwendal Roué f97088d63a Failing tests for HasManyThrough.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 860faf19f7 HasManyThrough.first and last 2020-04-18 16:40:22 +02:00
Gwendal Roué 0f54779386 Isolate tests for hasMany.first 2020-04-18 16:40:22 +02:00
Gwendal Roué 6f125bd3d7 SQLAssociation.associationForFirst() 2020-04-18 16:40:22 +02:00
Gwendal Roué 4483f037a4 Cleanup 2020-04-18 16:40:22 +02:00
Gwendal Roué 20296652dd More test for hasMany.first including nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d80922954a Let hasMany.first include nested associations 2020-04-18 16:40:22 +02:00
Gwendal Roué d67814ef61 Make sure hasMany.first doesn't lose information 2020-04-18 16:40:22 +02:00
Gwendal Roué fb550d30a0 HasManyAssociation.first and last 2020-04-18 16:40:22 +02:00
20 changed files with 1480 additions and 130 deletions

No files matched your search

+20
View File
@@ -189,6 +189,14 @@
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
@@ -1244,6 +1252,8 @@
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
@@ -1831,9 +1841,11 @@
5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */,
5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */,
5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */,
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */,
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */,
56959632222D056D002CB7C9 /* AssociationHasManySQLTests.swift */,
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
@@ -2845,10 +2857,12 @@
569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */,
5695310D1C9067DC00CF1A2B /* RecordCrashTests.swift in Sources */,
56BF2283241781C5003D86EB /* UtilsTests.swift in Sources */,
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5695310E1C9067DC00CF1A2B /* StatementColumnConvertibleCrashTests.swift in Sources */,
5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */,
5695310F1C9067DC00CF1A2B /* StatementCrashTests.swift in Sources */,
5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */,
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
560A37AF1C90A8D800949E71 /* DatabasePoolCrashTests.swift in Sources */,
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */,
);
@@ -3059,6 +3073,7 @@
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C16241D14450050755D /* FailableTestCase.swift in Sources */,
5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
@@ -3116,6 +3131,7 @@
5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
@@ -3265,6 +3281,7 @@
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
56677C15241D14450050755D /* FailableTestCase.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
@@ -3322,6 +3339,7 @@
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
@@ -3600,6 +3618,7 @@
AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */,
56677C17241D14450050755D /* FailableTestCase.swift in Sources */,
AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */,
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */,
@@ -3657,6 +3676,7 @@
AAA4DD85230F262000C74B15 /* AssociationParallelRowScopesTests.swift in Sources */,
AAA4DD86230F262000C74B15 /* SQLExpressionLiteralTests.swift in Sources */,
AAA4DD87230F262000C74B15 /* DropFirstCursorTests.swift in Sources */,
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
@@ -350,6 +350,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
// TODO: try to replace rowid with actual primary key
makeAggregate(SQLExpressionCountDistinct(Column.rowID))
.forKey("\(key.singularizedName)Count")
}
@@ -370,6 +371,7 @@ extension AssociationToMany {
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
// TODO: try to replace rowid with actual primary key
makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
@@ -27,6 +27,7 @@ typealias AssociationAggregatePreparation<RowDecoder> =
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
// TODO: replace rowid with actual primary key in the doc when implemented
/// Given a request, returns a tuple made of a request extended with the
/// associated records used to compute the aggregate, and an expression
/// whose value is the aggregated value.
@@ -99,4 +99,69 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
relation: Destination.all().relation,
cardinality: .toMany)
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let firstBook = hasMany(Book.self).order(Column("year")).first
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.firstBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var firstBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.firstBook.title) first")
/// }
public var first: HasOneAssociation<Origin, Destination> {
HasOneAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates a "Has one" association between the source and
/// destination types.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let lastBook = hasMany(Book.self).order(Column("year")).last
/// }
///
/// The association lets you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, firstBook) pairs:
/// let request = Author.including(required: Author.lastBook)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var lastBook: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.lastBook.title) last")
/// }
public var last: HasOneAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -55,4 +55,15 @@ public struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableR
public init(sqlAssociation: SQLAssociation) {
self.sqlAssociation = sqlAssociation
}
// TODO
public var first: HasOneThroughAssociation<Origin, Destination> {
HasOneThroughAssociation(sqlAssociation: sqlAssociation.associationForFirst())
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
}
// TODO
public var last: HasOneThroughAssociation<Origin, Destination> {
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
}
}
@@ -11,6 +11,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -21,6 +22,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -33,6 +35,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
}
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
+34 -13
View File
@@ -95,6 +95,17 @@ public /* TODO: internal */ struct SQLAssociation {
SQLAssociation(steps: other.steps + steps)
}
func associationForFirst() -> Self {
SQLAssociation(steps: steps.map { step in
switch step.cardinality {
case .toOne:
return step
case .toMany:
return step.map(\.relation) { $0.with(\.firstOnly, true) }
}
})
}
/// Given an origin alias and rows, returns the destination of the
/// association as a relation.
///
@@ -138,13 +149,10 @@ public /* TODO: internal */ struct SQLAssociation {
func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
// Filter the pivot
let pivot = self.pivot
let pivotAlias = TableAlias()
let filteredPivotRelation = pivot.relation
.qualified(with: pivotAlias)
.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db), rightAlias: pivotAlias)
})
let filteredPivotRelation = pivot.relation.filter({ db in
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
try pivot.condition.filteringExpression(db, leftRows: originRows(db))
})
if steps.count == 1 {
// This is a direct join from origin to destination, without
@@ -178,7 +186,12 @@ public /* TODO: internal */ struct SQLAssociation {
// children are useless:
let relation = step.relation
.selectOnly([])
.filteringChildren { $0.kind.cardinality == .toOne }
.filteringChildren({
switch $0.kind {
case .allPrefetched, .allNotPrefetched: return false
case .oneRequired, .oneOptional: return true
}
})
// Don't interfere with user-defined keys that could be added later
let key = step.key.map(\.baseName) { "grdb_\($0)" }
@@ -203,7 +216,16 @@ struct SQLAssociationStep: Refinable {
var relation: SQLRelation
var cardinality: SQLAssociationCardinality
var keyName: String { key.name(for: cardinality) }
var isSingular: Bool {
switch cardinality {
case .toOne:
return true
case .toMany:
return relation.firstOnly
}
}
var keyName: String { key.name(singular: isSingular) }
}
enum SQLAssociationCardinality {
@@ -319,11 +341,10 @@ enum SQLAssociationKey: Refinable {
}
}
func name(for cardinality: SQLAssociationCardinality) -> String {
switch cardinality {
case .toOne:
func name(singular: Bool) -> String {
if singular {
return singularizedName
case .toMany:
} else {
return pluralizedName
}
}
@@ -141,3 +141,22 @@ struct SQLExpressionNot: SQLExpression {
SQLExpressionNot(expression.qualifiedExpression(with: alias))
}
}
// MARK: -
extension Database {
/// Returns an expression for the primary key of this table.
///
/// When the table as a primary key made of several columns, we return
/// the rowid column. Eventually we'll support
/// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal
/// with WITHOUT ROWID tables.
func primaryKeyExpression(_ tableName: String) throws -> SQLExpression {
let columns = try primaryKey(tableName).columns
if columns.count == 1 {
return Column(columns[0])
} else {
return Column.rowID
}
}
}
+56 -15
View File
@@ -111,12 +111,12 @@ struct SQLRelation {
// Record.including(all: associationThroughPivot)
case allNotPrefetched
var cardinality: SQLAssociationCardinality {
var isSingular: Bool {
switch self {
case .oneOptional, .oneRequired:
return .toOne
return true
case .allPrefetched, .allNotPrefetched:
return .toMany
return false
}
}
}
@@ -140,11 +140,20 @@ struct SQLRelation {
fileprivate func makeAssociationForKey(_ key: String) -> SQLAssociation {
let key = SQLAssociationKey.fixed(key)
let cardinality: SQLAssociationCardinality
switch kind {
case .oneOptional, .oneRequired:
cardinality = .toOne
case .allPrefetched, .allNotPrefetched:
cardinality = .toMany
}
return SQLAssociation(
key: key,
condition: condition,
relation: relation,
cardinality: kind.cardinality)
cardinality: cardinality)
}
}
@@ -155,6 +164,9 @@ struct SQLRelation {
// `((a AND b) AND c)`.
var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
// If true, the relation refers to the first row only, and we'll need to
// perform explicit limit at the SQL level.
var firstOnly = false
var children: OrderedDictionary<String, Child> = [:]
var prefetchedAssociations: [SQLAssociation] {
@@ -175,6 +187,18 @@ struct SQLRelation {
}
}
}
/// Returns nil if there is no way to express the primary key of the
/// relation as an expression.
func primaryKeyExpression(_ db: Database) throws -> SQLExpression? {
switch source {
case .query:
// No primary key for sub query
return nil
case let .table(tableName: tableName, alias: _):
return try db.primaryKeyExpression(tableName)
}
}
}
extension SQLRelation: Refinable {
@@ -200,6 +224,19 @@ extension SQLRelation: Refinable {
}
}
// Prepending filters for aesthetic reasons
func prependingFilters(_ filters: [SQLExpression]) -> Self {
map(\.filtersPromise) { filtersPromise in
filtersPromise.flatMap { existingFilters in
DatabasePromise { _ in filters + existingFilters }
}
}
}
func unfiltered() -> Self {
with(\.filtersPromise, DatabasePromise(value: []))
}
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
with(\.ordering, SQLRelation.Ordering(orderings: orderings))
}
@@ -254,10 +291,10 @@ extension SQLRelation {
func appendingChild(for association: SQLAssociation, kind: SQLRelation.Child.Kind) -> Self {
// Preserve association cardinality in intermediate steps of
// including(all:), and force desired cardinality otherwize
let childCardinality = (kind == .allNotPrefetched)
? association.destination.cardinality
: kind.cardinality
let childKey = association.destination.key.name(for: childCardinality)
let isSingular = (kind == .allNotPrefetched)
? association.destination.isSingular
: kind.isSingular
let childKey = association.destination.key.name(singular: isSingular)
let child = SQLRelation.Child(
kind: kind,
condition: association.destination.condition,
@@ -549,13 +586,11 @@ struct SQLAssociationCondition: Equatable {
/// - parameter db: A database connection.
/// - parameter leftAlias: A TableAlias for the table on the left of the
/// JOIN operator.
/// - parameter rightAlias: A TableAlias for the table on the right of the
/// JOIN operator.
/// - Returns: An array of SQL expression that should be joined with
/// the AND operator.
func expressions(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> [SQLExpression] {
func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] {
try columnMappings(db).map {
QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias)
Column($0.right) == QualifiedColumn($0.left, alias: leftAlias)
}
}
@@ -564,7 +599,7 @@ struct SQLAssociationCondition: Equatable {
///
/// Given `right.a = left.b`, returns `right.a = 1` or
/// `right.a IN (1, 2, 3)`.
func filteringExpression(_ db: Database, leftRows: [Row], rightAlias: TableAlias) throws -> SQLExpression {
func filteringExpression(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
if leftRows.isEmpty {
// Degenerate case: there is no row to attach
return false.sqlExpression
@@ -578,7 +613,7 @@ struct SQLAssociationCondition: Equatable {
if columnMappings.count == 1 {
// Join on a single right column.
let rightColumn = QualifiedColumn(columnMapping.right, alias: rightAlias)
let rightColumn = Column(columnMapping.right)
// Unique database values and filter out NULL:
var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue })
@@ -600,7 +635,7 @@ struct SQLAssociationCondition: Equatable {
// (table.a = 1) AND (table.b = 2)
columnMappings
.map({ columns -> SQLExpression in
let rightColumn = QualifiedColumn(columns.right, alias: rightAlias)
let rightColumn = Column(columns.right)
let leftValue = leftRow[columns.left] as DatabaseValue
return rightColumn == leftValue
})
@@ -629,6 +664,11 @@ struct SQLAssociationCondition: Equatable {
extension SQLRelation {
/// Returns nil if relations can't be merged (conflict in source, joins...)
func merged(with other: SQLRelation) -> Self? {
guard firstOnly == other.firstOnly else {
// can't merge
return nil
}
guard let mergedSource = source.merged(with: other.source) else {
// can't merge
return nil
@@ -665,6 +705,7 @@ extension SQLRelation {
selection: mergedSelection,
filtersPromise: mergedFiltersPromise,
ordering: mergedOrdering,
firstOnly: firstOnly,
children: mergedChildren)
}
}
@@ -1,5 +1,5 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator {
struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
@@ -168,7 +168,7 @@ struct SQLQueryGenerator {
}
}
/// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
/// DELETE FROM table WHERE id IN (SELECT id FROM table ...)
private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement {
guard case let .table(tableName: tableName, alias: _) = relation.source else {
// Programmer error
@@ -176,14 +176,13 @@ struct SQLQueryGenerator {
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let primaryKey = try db.primaryKeyExpression(tableName)
// SELECT rowid FROM table ...
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
let selectSQL = try generator.sql(db, &context)
// DELETE FROM table WHERE rowid IN (SELECT rowid FROM table ...)
let sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE rowid IN (\(selectSQL))"
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
@@ -258,7 +257,7 @@ struct SQLQueryGenerator {
}
}
/// UPDATE table SET ... WHERE rowid IN (SELECT rowid FROM table ...)
/// UPDATE table SET ... WHERE id IN (SELECT id FROM table ...)
/// Returns nil if assignments is empty
private func makeTrivialUpdateStatement(
_ db: Database,
@@ -278,6 +277,7 @@ struct SQLQueryGenerator {
}
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
let primaryKey = try db.primaryKeyExpression(tableName)
// UPDATE table...
var sql = "UPDATE "
@@ -292,10 +292,12 @@ struct SQLQueryGenerator {
.joined(separator: ", ")
sql += " SET " + assignmentsSQL
// WHERE rowid IN (SELECT rowid FROM ...)
var generator = self
generator.relation = generator.relation.selectOnly([Column.rowID])
sql += try " WHERE rowid IN (\(generator.sql(db, &context)))"
// WHERE id IN (SELECT rowid FROM ...)
sql += " WHERE "
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
sql += " IN ("
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
statement.arguments = context.arguments
@@ -481,23 +483,7 @@ private struct SQLQualifiedRelation {
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
joins = relation.children.compactMapValues { child -> SQLQualifiedJoin? in
let kind: SQLQualifiedJoin.Kind
switch child.kind {
case .oneRequired:
kind = .innerJoin
case .oneOptional:
kind = .leftJoin
case .allPrefetched, .allNotPrefetched:
// This relation child is not fetched with an SQL join.
return nil
}
return SQLQualifiedJoin(
kind: kind,
condition: child.condition,
relation: SQLQualifiedRelation(child.relation))
}
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) }
filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } }
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
@@ -620,26 +606,76 @@ private enum SQLQualifiedSource {
}
/// A "qualified" join, where all tables are identified with a table alias.
private struct SQLQualifiedJoin {
private struct SQLQualifiedJoin: Refinable {
enum Kind: String {
case leftJoin = "LEFT JOIN"
case innerJoin = "JOIN"
init?(_ kind: SQLRelation.Child.Kind) {
switch kind {
case .oneRequired:
self = .innerJoin
case .oneOptional:
self = .leftJoin
case .allPrefetched, .allNotPrefetched:
// Eager loading of to-many associations is not implemented with joins
return nil
}
}
}
let kind: Kind
let condition: SQLAssociationCondition
let relation: SQLQualifiedRelation
enum Target {
case all
case first(SQLRelation)
}
var kind: Kind
var condition: SQLAssociationCondition
var relation: SQLQualifiedRelation
var target: Target
init?(_ child: SQLRelation.Child) {
guard let kind = Kind(child.kind) else {
return nil
}
self.kind = kind
self.condition = child.condition
// Remove non-joined grand children
let relation = child.relation.filteringChildren { Kind($0.kind) != nil }
if relation.firstOnly {
// Split relation into an "outer" relation exposed to the rest of
// the query, and a "subRelation", private to the join, limited
// to a single row:
//
// v--- outer relation
// JOIN child ON id = (SELECT id FROM child ... LIMIT 1)
// ^--- subRelation
//
// Outer relation has no filter or ordering: those are handled
// by the subRelation.
let outerRelation = relation
.with(\.firstOnly, false)
.unfiltered()
.unordered()
self.relation = SQLQualifiedRelation(outerRelation)
self.target = .first(relation)
} else {
self.relation = SQLQualifiedRelation(relation)
self.target = .all
}
}
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
SQLQualifiedJoin(
kind: kind,
condition: condition,
relation: relation.selectOnly(selection))
func selectOnly(_ selection: [SQLSelectable]) -> Self {
map(\.relation) { $0.selectOnly(selection) }
}
private func sql(
@@ -665,13 +701,43 @@ private struct SQLQualifiedJoin {
case .leftJoin:
allowsInnerJoin = false
}
// JOIN table...
sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))"
let rightAlias = relation.sourceAlias
let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias)
+ relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))"
switch target {
case .all:
// ... ON <join conditions> AND <other filters>
var filters = try condition.expressions(db, leftAlias: leftAlias)
filters += try relation.filtersPromise.resolve(db)
if filters.isEmpty == false {
let filterSQL = filters
.joined(operator: .and)
.qualifiedExpression(with: rightAlias)
.expressionSQL(&context, wrappedInParenthesis: false)
sql += " ON \(filterSQL)"
}
case var .first(subRelation):
// Subquery: SELECT id ...
guard let primaryKey = try subRelation.primaryKeyExpression(db) else {
fatalError("Not implemented: support for WITHOUT ROWID optimization")
}
subRelation = subRelation.selectOnly([primaryKey])
// Subquery: ... WHERE <condition filters> AND <other filters>
let filters = try condition.expressions(db, leftAlias: leftAlias)
subRelation = subRelation.prependingFilters(filters)
// Subquery: ... LIMIT 1
let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil))
// ... ON id = (SELECT id FROM table WHERE <condition filters> AND <other filters> LIMIT 1)
sql += " ON "
sql += rightAlias[primaryKey].expressionSQL(&context, wrappedInParenthesis: false)
sql += " = ("
sql += try SQLQueryGenerator(subQuery).sql(db, &context)
sql += ")"
}
for (_, join) in relation.joins {
@@ -489,7 +489,21 @@ extension TableRecord where Self: EncodableRecord {
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
try [Row(PersistenceContainer(db, self))]
})
return QueryInterfaceRequest(relation: destinationRelation)
let request = QueryInterfaceRequest<A.RowDecoder>(relation: destinationRelation)
// Deal with "firstOnly" relations
guard let firstOnlyIndex = association.sqlAssociation.steps.firstIndex(where: { $0.relation.firstOnly }) else {
return request
}
if
let toManyIndex = association.sqlAssociation.steps.lastIndex(where: { !$0.isSingular }),
toManyIndex > firstOnlyIndex
{
fatalError("Not implemented: loading multiple records associated to a `first` or `last` to-one association")
}
return request.limit(1)
}
}
@@ -547,6 +561,7 @@ extension TableRecord {
// MARK: - Association Aggregates
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -556,6 +571,7 @@ extension TableRecord {
all().annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
@@ -565,6 +581,7 @@ extension TableRecord {
all().annotated(with: aggregates)
}
// TODO: replace rowid with actual primary key in the doc when implemented
/// Creates a request with the provided aggregate *predicate*.
///
/// // SELECT player.*
+12
View File
@@ -107,6 +107,10 @@
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
@@ -787,6 +791,8 @@
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
@@ -1339,9 +1345,11 @@
5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */,
5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */,
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */,
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */,
56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */,
56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */,
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
@@ -2341,6 +2349,7 @@
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */,
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */,
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
5615B286222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
@@ -2398,6 +2407,7 @@
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */,
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
@@ -2676,6 +2686,7 @@
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */,
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */,
567E420A242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
5615B285222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
@@ -2733,6 +2744,7 @@
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */,
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
+1
View File
@@ -21,6 +21,7 @@
## Features
- [ ] Turn a hasMany to hasOne without first/last : hasMany(Book.self).filter(Column("isBest") /* assume a single book is flagged best */).asOne()
- [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user
- [ ] Support for more kinds of joins: https://github.com/groue/GRDB.swift/issues/740
- [ ] Delay SQL generation of SQLLiteral and SQLRequest: https://github.com/groue/GRDB.swift/issues/697
@@ -0,0 +1,468 @@
import XCTest
import GRDB
/// Test SQL generation
class AssociationHasManyFirstSQLTests: GRDBTestCase {
func testHasManyFirst() throws {
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().including(optional: association), """
SELECT "parent".*, "child".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(optional: association), """
SELECT "parent".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT * FROM "child"
WHERE "parentId" = 1
ORDER BY "id"
LIMIT 1
""")
}
}
}
func testHasManyFirstWithOneDeeperAssociation() throws {
struct Toy: TableRecord { }
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId", .integer).references("child")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.joining(required: Child.hasOne(Toy.self))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().including(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().joining(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.including(required: Child.hasOne(Toy.self))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "toy".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let alias = TableAlias()
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.filter(Column("id") == alias[Column("id")] + 1)
.first
.joining(required: Child.hasOne(Toy.self).filter(Column("id") == alias[Column("id")] * 2))
try assertMatchSQL(db, Parent.all().aliased(alias).including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
try assertMatchSQL(db, Parent.all().aliased(alias).joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
}
do {
let alias = TableAlias()
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.filter(Column("id") == alias[Column("id")] + 1)
.first
.including(required: Child.hasOne(Toy.self).filter(Column("id") == alias[Column("id")] * 2))
try assertMatchSQL(db, Parent.all().aliased(alias).including(required: association), """
SELECT "parent".*, "child".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
try assertMatchSQL(db, Parent.all().aliased(alias).joining(required: association), """
SELECT "parent".*, "toy".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
WHERE ("child"."parentId" = "parent"."id") AND ("child"."id" = ("parent"."id" + 1))
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON ("toy"."childId" = "child"."id") AND ("toy"."id" = ("parent"."id" * 2))
""")
}
}
}
func testHasManyFirstWithTwoDeeperAssociations() throws {
struct Vendor: TableRecord { }
struct Toy: TableRecord { }
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "vendor") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
t.autoIncrementedPrimaryKey("id")
t.column("childId", .integer).references("child")
t.column("vendorId", .integer).references("vendor")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.joining(required: Child.hasOne(Toy.self).including(optional: Toy.belongsTo(Vendor.self)))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().including(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
// TODO: implement
// Not implemented: chaining a required association behind an optional association
// try assertMatchSQL(db, Parent.all().joining(optional: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "vendor".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.first
.including(required: Child.hasOne(Toy.self).including(optional: Toy.belongsTo(Vendor.self)))
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*, "toy".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*, "toy".*, "vendor".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "child".*, "toy".*, "vendor".*
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
LEFT JOIN "vendor" ON "vendor"."id" = "toy"."vendorId"
WHERE "child"."parentId" = 1
ORDER BY "child"."id"
LIMIT 1
""")
}
}
}
func testHasManyLast() throws {
struct Child: TableRecord { }
struct Parent: TableRecord, EncodableRecord {
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
container["rowid"] = 2
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
do {
let association = Parent
.hasMany(Child.self)
.orderByPrimaryKey()
.last
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().including(optional: association), """
SELECT "parent".*, "child".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(optional: association), """
SELECT "parent".*
FROM "parent"
LEFT JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
WHERE "child"."parentId" = "parent"."id"
ORDER BY "child"."id" DESC
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT * FROM "child"
WHERE "parentId" = 1
ORDER BY "id" DESC
LIMIT 1
""")
}
}
}
}
@@ -780,6 +780,7 @@ class AssociationHasManySQLTests: GRDBTestCase {
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
@@ -793,17 +794,17 @@ class AssociationHasManySQLTests: GRDBTestCase {
try assertEqualSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "child".* \
FROM "parent" JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "child".* \
FROM "child" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "toy" ON "toy"."childId" = "child"."id" \
WHERE "child"."parentId" = 1
""")
}
@@ -0,0 +1,580 @@
import XCTest
import GRDB
/// Test SQL generation
// TODO: test request(for: hasManyThrough(hasMany.first, hasMany) (all comments of the last message in a chat)
class AssociationHasManyThroughFirstSQLTests: GRDBTestCase {
func testBelongsToHasMany() throws {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["bId"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."id" = 1)
LIMIT 1
""")
}
}
}
func testHasOneHasMany() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasOne(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."aId" = "a"."id"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."aId" = "a"."id"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."aId" = "a"."id"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."aId" = "a"."id"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON ("b"."id" = "c"."bId") AND ("b"."aId" = 1) LIMIT 1
""")
}
}
}
func testHasManyBelongsTo() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = belongsTo(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
t.column("aId").references("a")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."id" = "b"."cId"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
WHERE ("b"."cId" = "c"."id") AND ("b"."aId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
func testHasManyHasOne() throws {
struct A: TableRecord, EncodableRecord {
static let b = hasMany(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
struct B: TableRecord {
static let c = hasOne(C.self)
}
struct C: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
t.column("aId").references("a")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
do {
let association = A.c.first
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "c".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b" JOIN "c"
ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "c".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
LEFT JOIN "c" ON "c"."bId" = "b"."id"
WHERE "b"."aId" = "a"."id"
LIMIT 1)
LEFT JOIN "c" ON "c"."bId" = "b"."id"
""")
try assertMatchSQL(db, A().request(for: association), """
SELECT "c".*
FROM "c"
JOIN "b" ON "b"."id" = (
SELECT "b"."id"
FROM "b"
WHERE ("b"."id" = "c"."bId") AND ("b"."aId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
func testHasManyThroughHasManyFirst() throws {
struct A: TableRecord, EncodableRecord {
static let b = belongsTo(B.self)
static let c = hasMany(C.self, through: b, using: B.c)
static let d = hasMany(D.self, through: c.first, using: C.d)
func encode(to container: inout PersistenceContainer) {
container["bId"] = 1
}
}
struct B: TableRecord {
static let c = hasMany(C.self)
}
struct C: TableRecord {
static let d = hasMany(D.self)
}
struct D: TableRecord {
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("id")
t.column("bId").references("b")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("id")
t.column("cId").references("c")
}
do {
let association = A.d
try assertMatchSQL(db, A.all().including(required: association), """
SELECT "a".*, "d".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().including(optional: association), """
SELECT "a".*, "d".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
LEFT JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
LEFT JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().joining(required: association), """
SELECT "a".*
FROM "a"
JOIN "b" ON "b"."id" = "a"."bId"
JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
JOIN "d" ON "d"."cId" = "c"."id"
""")
try assertMatchSQL(db, A.all().joining(optional: association), """
SELECT "a".*
FROM "a"
LEFT JOIN "b" ON "b"."id" = "a"."bId"
LEFT JOIN "c" ON "c"."id" = (
SELECT "c"."id"
FROM "c"
LEFT JOIN "d" ON "d"."cId" = "c"."id"
WHERE "c"."bId" = "b"."id"
LIMIT 1)
LEFT JOIN "d" ON "d"."cId" = "c"."id"
""")
// TODO: implement
// Not implemented: loading multiple records associated to a `first` or `last` to-one association
// try assertMatchSQL(db, A().request(for: association), """
// SELECT ...
// """)
}
}
}
func testAssociationFilteredByOtherAssociation() throws {
struct Pet: TableRecord {
static let child = belongsTo(Child.self)
}
struct Toy: TableRecord { }
struct Child: TableRecord {
static let toy = hasOne(Toy.self)
static let pets = hasMany(Pet.self)
}
struct Parent: TableRecord, EncodableRecord {
static let children = hasMany(Child.self)
func encode(to container: inout PersistenceContainer) {
container["id"] = 1
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
t.column("childId", .integer).references("child")
}
try db.create(table: "pet") { t in
t.column("childId", .integer).references("child")
}
}
try dbQueue.inDatabase { db in
do {
let association = Parent.hasMany(
Pet.self,
through: Parent.children.joining(required: Child.toy),
using: Child.pets)
.first
try assertMatchSQL(db, Parent.all().including(required: association), """
SELECT "parent".*, "pet".*
FROM "parent"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
WHERE "child"."parentId" = "parent"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* FROM "parent"
JOIN "child"
ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
WHERE "child"."parentId" = "parent"."id"
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
JOIN "pet" ON "pet"."rowid" = (
SELECT "pet"."rowid"
FROM "pet"
WHERE "pet"."childId" = "child"."id"
LIMIT 1)
""")
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "pet".*
FROM "pet"
JOIN "child" ON "child"."id" = (
SELECT "child"."id"
FROM "child"
JOIN "toy" ON "toy"."childId" = "child"."id"
WHERE ("child"."id" = "pet"."childId") AND ("child"."parentId" = 1)
LIMIT 1)
JOIN "toy" ON "toy"."childId" = "child"."id"
LIMIT 1
""")
}
do {
#warning("TODO: generate correct SQL")
// let association = Parent.hasMany(
// Pet.self,
// through: Parent.children.filter(sql: "1 + 1"),
// using: Child.pets.joining(required: Pet.child.filter(sql: "1").joining(required: Child.toy)))
// .first
// try assertMatchSQL(db, Parent.all().including(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent.all().joining(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent().request(for: association), """
// SELECT ...
// """)
}
do {
let association = Parent.hasMany(
Pet.self,
through: Parent.children.filter(sql: "1 + 1"),
using: Child.pets)
.joining(required: Pet.child.filter(sql: "1").joining(required: Child.toy))
.first
#warning("TODO: generate correct SQL")
// try assertMatchSQL(db, Parent.all().including(required: association), """
// SELECT ...
// """)
// try assertMatchSQL(db, Parent.all().joining(required: association), """
// SELECT ...
// """)
try assertMatchSQL(db, Parent().request(for: association), """
SELECT "pet".*
FROM "pet"
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1)
JOIN "toy" ON "toy"."childId" = "child1"."id"
JOIN "child" "child2" ON "child2"."id" = (
SELECT "child"."id"
FROM "child"
WHERE ("child"."id" = "pet"."childId") AND (1 + 1) AND ("child"."parentId" = 1)
LIMIT 1)
LIMIT 1
""")
}
}
}
}
@@ -332,6 +332,7 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "child") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "toy") { t in
@@ -352,21 +353,21 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "pet" ON "pet"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id" \
JOIN "pet" ON "pet"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" ON "child"."parentId" = "parent"."id" \
JOIN "toy" ON "toy"."childId" = "child"."rowid" \
JOIN "pet" ON "pet"."childId" = "child"."rowid"
JOIN "toy" ON "toy"."childId" = "child"."id" \
JOIN "pet" ON "pet"."childId" = "child"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" ON ("child"."rowid" = "pet"."childId") AND ("child"."parentId" = 1) \
JOIN "toy" ON "toy"."childId" = "child"."rowid"
JOIN "child" ON ("child"."id" = "pet"."childId") AND ("child"."parentId" = 1) \
JOIN "toy" ON "toy"."childId" = "child"."id"
""")
}
do {
@@ -378,24 +379,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
""")
}
do {
@@ -408,24 +409,24 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase {
SELECT "parent".*, "pet".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent.all().joining(required: association), """
SELECT "parent".* \
FROM "parent" \
JOIN "child" "child1" ON ("child1"."parentId" = "parent"."id") AND (1 + 1) \
JOIN "pet" ON "pet"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."rowid"
JOIN "pet" ON "pet"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child2"."id"
""")
try assertEqualSQL(db, Parent().request(for: association), """
SELECT "pet".* \
FROM "pet" \
JOIN "child" "child1" ON ("child1"."rowid" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."rowid" \
JOIN "child" "child2" ON ("child2"."rowid" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
JOIN "child" "child1" ON ("child1"."id" = "pet"."childId") AND (1) \
JOIN "toy" ON "toy"."childId" = "child1"."id" \
JOIN "child" "child2" ON ("child2"."id" = "pet"."childId") AND (1 + 1) AND ("child2"."parentId" = 1)
""")
}
}
+25 -4
View File
@@ -136,27 +136,48 @@ class GRDBTestCase: XCTestCase {
XCTAssertEqual(recordDict, rowDict, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares SQL strings (ignoring leading and trailing white space and semicolons).
func assertEqualSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
// Trim white space and ";"
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
XCTAssertEqual(lhs.trimmingCharacters(in: cs), rhs.trimmingCharacters(in: cs), file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares SQL strings (ignoring leading and trailing white space and semicolons).
func assertEqualSQL<Request: FetchRequest>(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
let request = try request.makePreparedRequest(db, forSingleResult: false)
try request.statement.makeCursor().next()
assertEqualSQL(lastSQLQuery, sql, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
/// Compares SQL strings (ignoring leading and trailing white space and semicolons).
func assertEqualSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
try databaseReader.unsafeRead { db in
try assertEqualSQL(db, request, sql, file: file, line: line)
}
}
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL(_ lhs: String, _ rhs: String, file: StaticString = #file, line: UInt = #line) {
let cs = CharacterSet.whitespacesAndNewlines.union(CharacterSet(charactersIn: ";"))
let lScalars = Array(lhs.unicodeScalars.filter { !cs.contains($0) })
let rScalars = Array(rhs.unicodeScalars.filter { !cs.contains($0) })
XCTAssert(lScalars == rScalars, "assertMatchSQL failed: \(lhs) does not match \(rhs)", file: file, line: line)
}
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL<Request: FetchRequest>(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
let request = try request.makePreparedRequest(db, forSingleResult: false)
try request.statement.makeCursor().next()
assertMatchSQL(lastSQLQuery, sql, file: file, line: line)
}
/// Compares SQL strings (ignoring ALL white space and semicolons).
func assertMatchSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
try databaseReader.unsafeRead { db in
try assertMatchSQL(db, request, sql, file: file, line: line)
}
}
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
try! databaseReader.unsafeRead { db in
let request = try request.makePreparedRequest(db, forSingleResult: false)
@@ -205,8 +205,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.including(required: Player.team).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "player"."rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
@@ -215,8 +215,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
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" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
@@ -224,8 +224,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Team.having(Team.players.isEmpty).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "team" WHERE rowid IN (\
SELECT "team"."rowid" \
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
@@ -261,8 +261,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id")
""")
@@ -270,8 +270,8 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Player.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "player" WHERE rowid IN (\
SELECT "rowid" \
DELETE FROM "player" WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid")
""")
@@ -279,7 +279,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Passport.all().groupByPrimaryKey().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
@@ -288,7 +288,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase {
do {
try Passport.all().group(Column.rowID).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, """
DELETE FROM "passport" WHERE rowid IN (\
DELETE FROM "passport" WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
@@ -422,8 +422,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "player"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
@@ -432,8 +432,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
// Regression test for https://github.com/groue/GRDB.swift/issues/758
try Player.including(required: Player.team.filter(Column("active") == 1)).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "player"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON ("team"."id" = "player"."teamId") AND ("team"."active" = 1))
""")
@@ -442,8 +442,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "p"."rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
@@ -451,8 +451,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Team.having(Team.players.isEmpty).updateAll(db, Column("active").set(to: false))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0 WHERE rowid IN (\
SELECT "team"."rowid" \
UPDATE "team" SET "active" = 0 WHERE "id" IN (\
SELECT "team"."id" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
@@ -489,8 +489,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.all().groupByPrimaryKey().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id")
""")
@@ -498,8 +498,8 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Player.all().group(Column.rowID).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE rowid IN (\
SELECT "rowid" \
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid")
""")
@@ -507,7 +507,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Passport.all().groupByPrimaryKey().updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "countryCode", "citizenId")
@@ -516,7 +516,7 @@ class MutablePersistableRecordUpdateTests: GRDBTestCase {
do {
try Passport.all().group(Column.rowID).updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE rowid IN (\
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")