First tests for consumption of prefetched rows

This commit is contained in:
Gwendal Roué committed 2019-05-05 13:54:55 +02:00
1 parent 8d759898d3
commit 623f2eaf43
10 files changed
+1179 -882

No files matched your search

+6 -6
View File
@@ -33,8 +33,8 @@
560714962276177C0091BB10 /* Row+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714952276177C0091BB10 /* Row+QueryInterface.swift */; };
560714972276177C0091BB10 /* Row+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714952276177C0091BB10 /* Row+QueryInterface.swift */; };
560714982276177C0091BB10 /* Row+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714952276177C0091BB10 /* Row+QueryInterface.swift */; };
560714E3227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714E4227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714E3227DD0810091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingTests.swift */; };
560714E4227DD0810091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714E2227DD0810091BB10 /* AssociationPrefetchingTests.swift */; };
56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; };
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; };
@@ -934,7 +934,7 @@
5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = "<group>"; };
5607148B227617690091BB10 /* FetchableRecord+QueryInterface.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterface.swift"; sourceTree = "<group>"; };
560714952276177C0091BB10 /* Row+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterface.swift"; sourceTree = "<group>"; };
560714E2227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationHasManyPrefetchingSQLTests.swift; sourceTree = "<group>"; };
560714E2227DD0810091BB10 /* AssociationPrefetchingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingTests.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
@@ -1628,7 +1628,6 @@
5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */,
5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */,
5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */,
560714E2227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */,
56959632222D056D002CB7C9 /* AssociationHasManySQLTests.swift */,
56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */,
@@ -1641,6 +1640,7 @@
5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */,
5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */,
5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */,
560714E2227DD0810091BB10 /* AssociationPrefetchingTests.swift */,
5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */,
5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */,
);
@@ -2827,7 +2827,7 @@
56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */,
56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */,
56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E4227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714E4227DD0810091BB10 /* AssociationPrefetchingTests.swift in Sources */,
5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */,
56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */,
@@ -3017,7 +3017,7 @@
562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */,
56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */,
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationPrefetchingTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
+24 -1
View File
@@ -31,6 +31,12 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// The number of columns in the row.
public let count: Int
struct Prefetch {
var rows: [Row]?
var prefetches: [String: Prefetch]
}
var prefetches: [String: Prefetch] = [:]
// MARK: - Building rows
@@ -609,6 +615,18 @@ extension Row {
}
}
extension Row {
// MARK: - Prefetches
/// TODO
public var prefetchedRows: [String: [Row]] {
return prefetches.compactMapValues { $0.rows }
}
}
// MARK: - RowCursor
/// A cursor of database rows. For example:
///
/// try dbQueue.read { db in
@@ -1050,7 +1068,7 @@ extension Row {
}
private func debugDescription(level: Int) -> String {
if level == 0 && self == self.unadapted {
if level == 0 && self == self.unadapted && prefetches.isEmpty {
return description
}
let prefix = repeatElement(" ", count: level + 1).joined(separator: "")
@@ -1067,6 +1085,11 @@ extension Row {
for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) {
str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1)
}
for (key, prefetch) in prefetches.sorted(by: { $0.key < $1.key }) {
if let rows = prefetch.rows {
str += "\n" + prefix + "- " + key + ": \(rows.count) rows"
}
}
return str
}
@@ -40,8 +40,8 @@ public struct QueryInterfaceRequest<T> {
}
@usableFromInline
var needsPrefetch: Bool {
return query.relation.needsPrefetch
var prefetchedAssociations: [SQLAssociation] {
return query.relation.prefetchedAssociations
}
}
+145 -122
View File
@@ -1,129 +1,9 @@
extension Row {
// MARK: - Fetching From QueryInterfaceRequest
/// Returns an array of rows fetched from a fetch request.
///
/// let request = Player.all()
/// let rows = try Row.fetchAll(db, request)
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@inlinable
public static func fetchAll<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> [Row] {
if request.needsPrefetch {
return try fetchAllWithPrefetchedRows(db, request)
}
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
/// Returns a single row fetched from a fetch request.
///
/// let request = Player.filter(key: 1)
/// let row = try Row.fetchOne(db, request)
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@inlinable
public static func fetchOne<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> Row? {
if request.needsPrefetch {
return try fetchOneWithPrefetchedRows(db, request)
}
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
return try fetchOne(statement, adapter: adapter)
}
@usableFromInline
/* private */ static func fetchAllWithPrefetchedRows<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> [Row] {
// Fetch base rows
// TODO: avoid fatal errors "column ... is not selected" by making sure
// columns used by joins are fetched (and hidden by a row adapter if added)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
let rows = try fetchAll(statement, adapter: adapter)
return try rowsWithPrefetchedRows(db, rows, with: request.query)
}
@usableFromInline
/* private */ static func fetchOneWithPrefetchedRows<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> Row? {
// Fetch base rows
// TODO: avoid fatal errors "column ... is not selected" by making sure
// columns used by joins are fetched (and hidden by a row adapter if added)
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
guard let row = try fetchOne(statement, adapter: adapter) else {
return nil
}
return try rowsWithPrefetchedRows(db, [row], with: request.query)[0]
}
private static func rowsWithPrefetchedRows(_ db: Database, _ rows: [Row], with query: SQLSelectQuery) throws -> [Row] {
guard let firstRow = rows.first else {
return rows
}
let prefetchedAssociations = query.relation.prefetchedAssociations()
for association in prefetchedAssociations {
let pivotMapping = try association.pivotCondition.columnMapping(db)
let rightColumns = pivotMapping.map { $0.right }
let rightAlias = TableAlias()
let prefetchedRelation = association
.mapPivotRelation { $0.qualified(with: rightAlias) }
.destinationRelation(fromOriginRows: { _ in rows })
.annotated(with: rightColumns.map { rightAlias[Column($0)].aliased("grdb_\($0)") })
let prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation)
.fetchAll(db)
.grouped(byDatabaseValuesOnColumns: rightColumns.map { "grdb_\($0)" })
let groupingIndexes = firstRow.indexes(ofColumns: pivotMapping.map { $0.left })
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedRows[groupingKey] ?? []
print(association.keyPath, prefetchedRows)
// TODO: embed prefetchedRows inside row at association.keyPath
}
}
return rows
}
}
extension Array where Element == Row {
/// - precondition: Columns all exist in all rows. All rows have the same
/// columnns, in the same order.
fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] {
guard let firstRow = first else {
return [:]
}
let indexes = firstRow.indexes(ofColumns: columns)
return Dictionary(grouping: self, by: { row in
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
})
}
}
extension Row {
/// - precondition: Columns all exist in tthe row.
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
return columns.map { column -> Int in
guard let index = index(ofColumn: column) else {
fatalError("Column \(column) is not selected")
}
return index
}
}
}
extension QueryInterfaceRequest where RowDecoder == Row {
// MARK: Fetching Rows
// TODO: cursor
/// An array of fetched rows.
///
/// let request: QueryInterfaceRequest<Row> = ...
@@ -150,3 +30,146 @@ extension QueryInterfaceRequest where RowDecoder == Row {
return try Row.fetchOne(db, self)
}
}
extension Row {
// MARK: - Fetching From QueryInterfaceRequest
/// Returns an array of rows fetched from a fetch request.
///
/// let request = Player.all()
/// let rows = try Row.fetchAll(db, request)
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@inlinable
public static func fetchAll<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> [Row] {
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
let rows = try fetchAll(statement, adapter: adapter)
let associations = request.prefetchedAssociations
if associations.isEmpty == false {
try prefetch(db, associations: associations, in: rows)
}
return rows
}
/// Returns a single row fetched from a fetch request.
///
/// let request = Player.filter(key: 1)
/// let row = try Row.fetchOne(db, request)
///
/// - parameters:
/// - db: A database connection.
/// - request: A FetchRequest.
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@inlinable
public static func fetchOne<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> Row? {
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
guard let row = try fetchOne(statement, adapter: adapter) else {
return nil
}
let associations = request.prefetchedAssociations
if associations.isEmpty == false {
try prefetch(db, associations: associations, in: [row])
}
return row
}
@usableFromInline
/* private */ static func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [Row]) throws {
guard let firstRow = rows.first else {
return
}
for association in associations {
let pivotMapping = try association.pivotCondition.columnMapping(db)
let prefetchedRows: [[DatabaseValue] : [Row]]
do {
// Annotate prefetched rows with pivot columns, so that we can
// group them.
//
// Those pivot columns are necessaary when we prefetch
// indirect associations:
//
// // SELECT country.*, passport.citizenId AS grdb_citizenId
// // -- ^ the necessaary pivot column
// // FROM country
// // JOIN passport ON passport.countryCode = country.code
// // AND passport.citizenId IN (1, 2, 3)
// Citizen.including(all: Citizen.countries)
//
// Those pivot columns are redundant when we prefetch
// direct associations:
//
// // SELECT *, authorId AS grdb_authorId
// // -- ^ the redundant pivot column
// // FROM book
// // WHERE authorId IN (1, 2, 3)
// Author.including(all: Author.books)
//
// Maybe we'll remove this redundancy later.
let pivotColumns = pivotMapping.map { $0.right }
let pivotAlias = TableAlias()
let prefetchedRelation = association
.mapPivotRelation { $0.qualified(with: pivotAlias) }
.destinationRelation(fromOriginRows: { _ in rows })
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].aliased("grdb_\($0)") })
prefetchedRows = try QueryInterfaceRequest(relation: prefetchedRelation)
.fetchAll(db)
.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
}
let groupingIndexes = firstRow.indexes(ofColumns: pivotMapping.map { $0.left })
for row in rows {
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
let prefetchedRows = prefetchedRows[groupingKey, default: []]
row.prefetches.setRows(prefetchedRows, forKeyPath: association.keyPath)
}
}
}
}
extension Array where Element == Row {
/// - precondition: Columns all exist in all rows. All rows have the same
/// columnns, in the same order.
fileprivate func grouped(byDatabaseValuesOnColumns columns: [String]) -> [[DatabaseValue]: [Row]] {
guard let firstRow = first else {
return [:]
}
let indexes = firstRow.indexes(ofColumns: columns)
return Dictionary(grouping: self, by: { row in
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
})
}
}
extension Row {
/// - precondition: Columns all exist in the row.
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
return columns.map { column -> Int in
guard let index = index(ofColumn: column) else {
fatalError("Column \(column) is not selected")
}
return index
}
}
}
extension Dictionary where Key == String, Value == Row.Prefetch {
fileprivate mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
var keyPath = keyPath
let key = keyPath.removeFirst()
if keyPath.isEmpty {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].rows = rows
} else {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].prefetches.setRows(rows, forKeyPath: keyPath)
}
}
}
+105 -18
View File
@@ -1,14 +1,103 @@
/// A "relation" as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology):
/// A "relation", as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// > A set of tuples sharing the same attributes; a set of columns and rows.
/// SQLRelation is defined with a selection, a source table of query, and an
/// eventual filter and ordering.
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// | | | | |
/// | | | | • ordering
/// | | | • filterPromise
/// | | • children
/// SELECT ... FROM ... WHERE ... ORDER BY ...
/// | | | |
/// | | | • ordering
/// | | • filter
/// | • source
/// • selection
///
/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the
/// SQLSelectQuery type.
///
/// ## Promises
///
/// Filter and ordering are actually "promises", which are only resolved
/// when a database connection is available. This is how we can implement
/// requests such as `Record.filter(key: 1)` or `Record.orderedByPrimaryKey()`:
/// both need a database connection in order to introspect the primary key.
///
/// // SELECT * FROM player
/// // WHERE continent = 'EU'
/// // ORDER BY code -- primary key infered from the database schema
/// Country
/// .filter(Column("continent") == "EU")
/// .orderedByPrimaryKey()
///
/// ## Children
///
/// Relations may also have children. A child is a link to another relation, and
/// provide support for joins and prefetched relations.
///
/// Relations and their children constitute a tree of relations, which the user
/// builds with associations:
///
/// // Builds a relation with two children:
/// Author
/// .including(required: Author.country)
/// .including(all: Author.books)
///
/// There are four kinds of children:
///
/// - `.oneOptional`:
///
/// Such children are left joined. They may, or not, be included in
/// the selection.
///
/// // SELECT book.*
/// // FROM book
/// // LEFT JOIN author ON author.id = book.id
/// Book.joining(optional: Book.author)
///
/// // SELECT book.*, author.*
/// // FROM book
/// // LEFT JOIN author ON author.id = book.id
/// Book.including(optional: Book.author)
///
/// - `.oneRequired`:
///
/// Such children are inner joined. They may, or not, be included in
/// the selection.
///
/// // SELECT book.*
/// // FROM book
/// // JOIN author ON author.id = book.id AND author.country = 'FR'
/// Book.joining(required: Book.author.filter(Column("country") == "FR"))
///
/// // SELECT book.*, author.*
/// // FROM book
/// // JOIN author ON author.id = book.id AND author.country = 'FR'
/// Book.including(required: Book.author.filter(Column("country") == "FR"))
///
/// - `.allPrefetched`:
///
/// Such children are prefetched using several SQL requests:
///
/// // SELECT * FROM countries WHERE continent = 'EU'
/// // SELECT * FROM passport WHERE countryCode IN ('BE', 'DE', 'FR', ...)
/// Country
/// .filter(Column("continent") == "EU")
/// .including(all: Country.passports)
///
/// - `.allNotPrefetched`:
///
/// Such children are not joined, and not prefetched. They are used as
/// intermediate children towards a prefetched child. In the example
/// below, the country relation has a `.allNotPrefetched` child to
/// passports, and the passport relation has a `.allPrefetched` child
/// to citizens.
///
/// // SELECT * FROM countries WHERE continent = 'EU'
/// // SELECT citizens.* FROM citizens
/// // JOIN passport ON passport.citizenId = citizens.id
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...)
/// Country
/// .filter(Column("continent") == "EU")
/// .including(all: Country.citizens)
struct SQLRelation {
struct Child {
enum Kind {
@@ -38,6 +127,10 @@ struct SQLRelation {
return false
}
}
fileprivate func associationForKey(_ key: String) -> SQLAssociation {
return SQLAssociation(key: key, condition: condition, relation: relation)
}
}
var source: SQLSource
@@ -46,21 +139,15 @@ struct SQLRelation {
var ordering: SQLRelation.Ordering
var children: OrderedDictionary<String, Child>
// TODO: replace with !prefetchedAssociations.isEmpty if prefetchedAssociations
// happens to be sufficient
var needsPrefetch: Bool {
return children.contains { $0.value.kind == .allPrefetched || $0.value.relation.needsPrefetch }
}
func prefetchedAssociations() -> [SQLAssociation] {
var prefetchedAssociations: [SQLAssociation] {
return children.flatMap { key, child -> [SQLAssociation] in
switch child.kind {
case .allPrefetched:
return [SQLAssociation(key: key, condition: child.condition, relation: child.relation)]
return [child.associationForKey(key)]
case .oneOptional, .oneRequired, .allNotPrefetched:
return child.relation
.prefetchedAssociations()
.map { $0.through(SQLAssociation(key: key, condition: child.condition, relation: child.relation)) }
return child.relation.prefetchedAssociations.map {
$0.through(child.associationForKey(key))
}
}
}
}
+6 -6
View File
@@ -11,8 +11,8 @@
5607149C227618660091BB10 /* Row+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56071499227618660091BB10 /* Row+QueryInterface.swift */; };
5607149E227618800091BB10 /* FetchableRecord+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607149D227618800091BB10 /* FetchableRecord+QueryInterface.swift */; };
5607149F227618800091BB10 /* FetchableRecord+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607149D227618800091BB10 /* FetchableRecord+QueryInterface.swift */; };
560714ED227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714EE227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714ED227DD10F0091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationPrefetchingTests.swift */; };
560714EE227DD10F0091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EB227DD10F0091BB10 /* AssociationPrefetchingTests.swift */; };
56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; };
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; };
5613ED6221A95E6100DC7A68 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED5921A95E6100DC7A68 /* ValueObservation.swift */; };
@@ -690,7 +690,7 @@
5605F18C1C6B1A8700235C62 /* SQLSelectQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectQuery.swift; sourceTree = "<group>"; };
56071499227618660091BB10 /* Row+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+QueryInterface.swift"; sourceTree = "<group>"; };
5607149D227618800091BB10 /* FetchableRecord+QueryInterface.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterface.swift"; sourceTree = "<group>"; };
560714EB227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationHasManyPrefetchingSQLTests.swift; sourceTree = "<group>"; };
560714EB227DD10F0091BB10 /* AssociationPrefetchingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingTests.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = "<group>"; };
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = "<group>"; };
@@ -1346,7 +1346,6 @@
5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */,
5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */,
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */,
560714EB227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */,
56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */,
5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */,
@@ -1359,6 +1358,7 @@
5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */,
5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */,
5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */,
560714EB227DD10F0091BB10 /* AssociationPrefetchingTests.swift */,
5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */,
5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */,
);
@@ -2157,7 +2157,7 @@
5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
F3BA80E51CFB3011003DC1BA /* DatabaseFunctionTests.swift in Sources */,
560714EE227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714EE227DD10F0091BB10 /* AssociationPrefetchingTests.swift in Sources */,
F3BA80531CFB2B59003DC1BA /* DataMemoryTests.swift in Sources */,
F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */,
F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */,
@@ -2477,7 +2477,7 @@
56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */,
F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */,
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714ED227DD10F0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714ED227DD10F0091BB10 /* AssociationPrefetchingTests.swift in Sources */,
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */,
56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */,
F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */,
@@ -7,8 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
560714F0227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714F1227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714F0227DD1810091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingTests.swift */; };
560714F1227DD1810091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714EF227DD1810091BB10 /* AssociationPrefetchingTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -383,7 +383,7 @@
/* Begin PBXFileReference section */
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
560714EF227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyPrefetchingSQLTests.swift; sourceTree = "<group>"; };
560714EF227DD1810091BB10 /* AssociationPrefetchingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
@@ -630,7 +630,6 @@
564A1F95226B89DA001F64F1 /* AssociationBelongsToSQLTests.swift */,
564A1F33226B89CF001F64F1 /* AssociationChainRowScopesTests.swift */,
564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */,
560714EF227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */,
564A1F7C226B89D7001F64F1 /* AssociationHasManySQLTests.swift */,
564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */,
564A1FAE226B89DC001F64F1 /* AssociationHasOneSQLDerivationTests.swift */,
@@ -643,6 +642,7 @@
564A1F70226B89D6001F64F1 /* AssociationParallelDecodableRecordTests.swift */,
564A1FD8226B89E0001F64F1 /* AssociationParallelRowScopesTests.swift */,
564A1FDC226B89E1001F64F1 /* AssociationParallelSQLTests.swift */,
560714EF227DD1810091BB10 /* AssociationPrefetchingTests.swift */,
564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */,
564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
@@ -1047,7 +1047,7 @@
564A2048226B89E1001F64F1 /* RowAdapterTests.swift in Sources */,
564A2040226B89E1001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
564A2019226B89E1001F64F1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
560714F0227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714F0227DD1810091BB10 /* AssociationPrefetchingTests.swift in Sources */,
564A2080226B89E1001F64F1 /* StatementArgumentsTests.swift in Sources */,
564A2082226B89E1001F64F1 /* PersistableRecordTests.swift in Sources */,
564A2016226B89E1001F64F1 /* QueryInterfacePromiseTests.swift in Sources */,
@@ -1237,7 +1237,7 @@
564A20AC226B8E18001F64F1 /* RowAdapterTests.swift in Sources */,
564A20AD226B8E18001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
564A20AE226B8E18001F64F1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
560714F1227DD1810091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714F1227DD1810091BB10 /* AssociationPrefetchingTests.swift in Sources */,
564A20AF226B8E18001F64F1 /* StatementArgumentsTests.swift in Sources */,
564A20B0226B8E18001F64F1 /* PersistableRecordTests.swift in Sources */,
564A20B1226B8E18001F64F1 /* QueryInterfacePromiseTests.swift in Sources */,
@@ -7,8 +7,8 @@
objects = {
/* Begin PBXBuildFile section */
560714F3227DD1AE0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714F4227DD1AE0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */; };
560714F3227DD1AE0091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingTests.swift */; };
560714F4227DD1AE0091BB10 /* AssociationPrefetchingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560714F2227DD1AD0091BB10 /* AssociationPrefetchingTests.swift */; };
564A1FDE226B89E1001F64F1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F27226B89CE001F64F1 /* MutablePersistableRecordDeleteTests.swift */; };
564A1FDF226B89E1001F64F1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F28226B89CE001F64F1 /* AssociationHasOneThroughRowScopeTests.swift */; };
564A1FE0226B89E1001F64F1 /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A1F29226B89CF001F64F1 /* RowCopiedFromStatementTests.swift */; };
@@ -385,7 +385,7 @@
/* Begin PBXFileReference section */
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
560714F2227DD1AD0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyPrefetchingSQLTests.swift; sourceTree = "<group>"; };
560714F2227DD1AD0091BB10 /* AssociationPrefetchingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingTests.swift; sourceTree = "<group>"; };
564A1F1D226B876D001F64F1 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
564A1F26226B89CD001F64F1 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
@@ -633,7 +633,6 @@
564A1F95226B89DA001F64F1 /* AssociationBelongsToSQLTests.swift */,
564A1F33226B89CF001F64F1 /* AssociationChainRowScopesTests.swift */,
564A1F4D226B89D2001F64F1 /* AssociationChainSQLTests.swift */,
560714F2227DD1AD0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift */,
564A1F7C226B89D7001F64F1 /* AssociationHasManySQLTests.swift */,
564A1FB4226B89DD001F64F1 /* AssociationHasManyThroughSQLTests.swift */,
564A1FAE226B89DC001F64F1 /* AssociationHasOneSQLDerivationTests.swift */,
@@ -646,6 +645,7 @@
564A1F70226B89D6001F64F1 /* AssociationParallelDecodableRecordTests.swift */,
564A1FD8226B89E0001F64F1 /* AssociationParallelRowScopesTests.swift */,
564A1FDC226B89E1001F64F1 /* AssociationParallelSQLTests.swift */,
560714F2227DD1AD0091BB10 /* AssociationPrefetchingTests.swift */,
564A1F3E226B89D0001F64F1 /* AssociationRowScopeSearchTests.swift */,
564A1FCF226B89E0001F64F1 /* AssociationTableAliasTestsSQLTests.swift */,
564A1F6F226B89D6001F64F1 /* Betty.jpeg */,
@@ -1053,7 +1053,7 @@
564A2048226B89E1001F64F1 /* RowAdapterTests.swift in Sources */,
564A2040226B89E1001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
564A2019226B89E1001F64F1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
560714F3227DD1AE0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714F3227DD1AE0091BB10 /* AssociationPrefetchingTests.swift in Sources */,
564A2080226B89E1001F64F1 /* StatementArgumentsTests.swift in Sources */,
564A2082226B89E1001F64F1 /* PersistableRecordTests.swift in Sources */,
564A2016226B89E1001F64F1 /* QueryInterfacePromiseTests.swift in Sources */,
@@ -1243,7 +1243,7 @@
564A20AC226B8E18001F64F1 /* RowAdapterTests.swift in Sources */,
564A20AD226B8E18001F64F1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
564A20AE226B8E18001F64F1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
560714F4227DD1AE0091BB10 /* AssociationHasManyPrefetchingSQLTests.swift in Sources */,
560714F4227DD1AE0091BB10 /* AssociationPrefetchingTests.swift in Sources */,
564A20AF226B8E18001F64F1 /* StatementArgumentsTests.swift in Sources */,
564A20B0226B8E18001F64F1 /* PersistableRecordTests.swift in Sources */,
564A20B1226B8E18001F64F1 /* QueryInterfacePromiseTests.swift in Sources */,
@@ -1,715 +0,0 @@
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct A: TableRecord, FetchableRecord, Decodable {
var cola1: Int64
var cola2: String
}
private struct B: TableRecord, FetchableRecord, Decodable {
var colb1: Int64
var colb2: Int64
var colb3: String
}
private struct C: TableRecord, FetchableRecord, Decodable {
var colc1: Int64
var colc2: String
}
private struct D: TableRecord, FetchableRecord, Decodable {
var cold1: Int64
var cold2: Int64
var cold3: String
}
class AssociationHasManyPrefetchingSQLTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("cola1")
t.column("cola2", .text)
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("colb1")
t.column("colb2", .integer).references("a")
t.column("colb3", .text)
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("colc1")
t.column("colc2", .integer).references("a")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("cold1")
t.column("cold2", .integer).references("c")
t.column("cold3", .text)
}
try db.execute(
sql: """
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
""",
arguments: [
1, "a1",
2, "a2",
3, "a3",
4, 1, "b1",
5, 1, "b2",
6, 2, "b3",
7, 1,
8, 2,
9, 2,
10, 7, "d1",
11, 8, "d2",
12, 8, "d3",
13, 9, "d4",
])
}
}
func testIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE ("colb2" IN (1, 2, 3)) \
ORDER BY "colb1"
"""])
}
do {
let request = A
.filter(false)
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
"""])
}
do {
let request = A
.filter(Column("cola1") != 1)
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") == 4)
.orderByPrimaryKey()
.forKey("a1"))
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") != 4)
.orderByPrimaryKey()
.forKey("a2"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE ("cola1" <> 1) \
ORDER BY "cola1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE (("colb1" = 4) AND ("colb2" IN (2, 3))) \
ORDER BY "colb1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE (("colb1" <> 4) AND ("colb2" IN (2, 3))) \
ORDER BY "colb1"
"""])
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE ("colc2" IN (1, 2, 3)) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE ("cold2" IN (7, 8, 9)) \
ORDER BY "cold1"
"""])
}
do {
let request = A
.including(all: A
.hasMany(C.self)
.filter(false)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (0 AND ("colc2" IN (1, 2, 3))) \
ORDER BY "colc1"
"""])
}
do {
let request = A
.filter(Column("cola1") != 1)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("c1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("c2"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 1) \
ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" > 7) AND ("colc2" IN (2, 3))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" IN (8, 9))) \
ORDER BY "cold1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" IN (8, 9))) \
ORDER BY "cold1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" < 9) AND ("colc2" IN (2, 3))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" = 8)) \
ORDER BY "cold1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" = 8)) \
ORDER BY "cold1"
"""])
}
}
}
func testIncludingAllHasManyIncludingRequiredHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON ("d"."cold2" = "c"."colc1") \
WHERE ("c"."colc2" IN (1, 2, 3)) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
do {
let request = A
.including(all: A
.hasMany(C.self)
.filter(false)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON ("d"."cold2" = "c"."colc1") \
WHERE (0 AND ("c"."colc2" IN (1, 2, 3))) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
do {
let request = A
.filter(Column("cola1") != 1)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("c1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("c2"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 1) \
ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
JOIN "d" "d1" ON (("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11)) \
JOIN "d" "d2" ON (("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11)) \
WHERE (("c"."colc1" > 7) AND ("c"."colc2" IN (2, 3))) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
JOIN "d" "d1" ON (("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11)) \
JOIN "d" "d2" ON (("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11)) \
WHERE (("c"."colc1" < 9) AND ("c"."colc2" IN (2, 3))) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
"""])
}
}
}
func testIncludingAllHasManyThrough() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = A
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3))) \
ORDER BY "d"."cold1"
"""])
}
do {
let request = A
.filter(Column("cola1") != 1)
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).filter(Column("colc1") > 7).forKey("c1"), using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("d1"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c2"), using: C.hasMany(D.self))
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c2"), using: C.hasMany(D.self))
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d3"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE ("cola1" <> 1) \
ORDER BY "cola1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND (("c"."colc1" > 7) AND ("c"."colc2" IN (2, 3)))) \
ORDER BY "d"."cold1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (2, 3))) \
WHERE ("d"."cold1" <> 11) \
ORDER BY "d"."cold1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (2, 3))) \
WHERE ("d"."cold1" = 11) \
ORDER BY "d"."cold1"
"""])
}
}
}
func testIncludingAllHasManyThroughMergedWithHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
do {
let request = A
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey())
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE ("colc2" IN (1, 2, 3)) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE ("cold2" IN (7, 8, 9)) \
ORDER BY "cold1"
"""])
}
do {
let request = A
.filter(Column("cola1") != 1)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 8)
.orderByPrimaryKey()
.forKey("c1"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c1"), using: C.hasMany(D.self))
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("c2"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c2"), using: C.hasMany(D.self))
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 1) \
ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" <> 8) AND ("colc2" IN (2, 3))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" = 9)) \
ORDER BY "cold1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" <> 9) AND ("colc2" IN (2, 3))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" = 8)) \
ORDER BY "cold1"
"""])
}
}
}
func testIncludingOptionalBelongsToIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
do {
let request = B
.including(optional: B
.belongsTo(A.self)
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey())
)
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT "b".*, "a".* \
FROM "b" \
LEFT JOIN "a" ON ("a"."cola1" = "b"."colb2") \
ORDER BY "b"."colb1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND ("a"."cola1" IN (1, 2))) \
ORDER BY "c"."colc1"
"""])
}
do {
let request = B
.including(optional: B
.belongsTo(A.self)
.filter(Column("cola2") == "a1")
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") == 9)
.orderByPrimaryKey()
.forKey("c1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("c2"))
.forKey("a1"))
.including(optional: B
.belongsTo(A.self)
.filter(Column("cola2") == "a2")
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") == 9)
.orderByPrimaryKey()
.forKey("c1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("c2"))
.forKey("a2"))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
LEFT JOIN "a" "a1" ON (("a1"."cola1" = "b"."colb2") AND ("a1"."cola2" = 'a1')) \
LEFT JOIN "a" "a2" ON (("a2"."cola1" = "b"."colb2") AND ("a2"."cola2" = 'a2')) \
ORDER BY "b"."colb1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" = 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" <> 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" = 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" <> 9) \
ORDER BY "c"."colc1"
"""])
}
}
}
}
@@ -0,0 +1,879 @@
import XCTest
#if GRDBCUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private struct A: TableRecord, FetchableRecord, Decodable {
var cola1: Int64
var cola2: String
}
private struct B: TableRecord, FetchableRecord, Decodable {
var colb1: Int64
var colb2: Int64
var colb3: String
}
private struct C: TableRecord, FetchableRecord, Decodable {
var colc1: Int64
var colc2: String
}
private struct D: TableRecord, FetchableRecord, Decodable {
var cold1: Int64
var cold2: Int64
var cold3: String
}
class AssociationPrefetchingTests: GRDBTestCase {
override func setup(_ dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "a") { t in
t.autoIncrementedPrimaryKey("cola1")
t.column("cola2", .text)
}
try db.create(table: "b") { t in
t.autoIncrementedPrimaryKey("colb1")
t.column("colb2", .integer).references("a")
t.column("colb3", .text)
}
try db.create(table: "c") { t in
t.autoIncrementedPrimaryKey("colc1")
t.column("colc2", .integer).references("a")
}
try db.create(table: "d") { t in
t.autoIncrementedPrimaryKey("cold1")
t.column("cold2", .integer).references("c")
t.column("cold3", .text)
}
try db.execute(
sql: """
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO a (cola1, cola2) VALUES (?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO b (colb1, colb2, colb3) VALUES (?, ?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO c (colc1, colc2) VALUES (?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
INSERT INTO d (cold1, cold2, cold3) VALUES (?, ?, ?);
""",
arguments: [
1, "a1",
2, "a2",
3, "a3",
4, 1, "b1",
5, 1, "b2",
6, 2, "b3",
7, 1,
8, 2,
9, 2,
10, 7, "d1",
11, 8, "d2",
12, 8, "d3",
13, 9, "d4",
])
}
}
func testIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.forKey("bs")) // TODO: auto-pluralization
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE ("colb2" IN (1, 2, 3)) \
ORDER BY "colb1"
"""])
}
// PrefetchedRows
do {
let rows = try Row.fetchAll(db, request)
XCTAssertEqual(rows.count, 3)
XCTAssertEqual(rows[0], ["cola1": 1, "cola2": "a1"])
XCTAssertEqual(rows[0].prefetchedRows.count, 1)
XCTAssertEqual(rows[0].prefetchedRows["bs"]!.count, 2)
XCTAssertEqual(rows[0].prefetchedRows["bs"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colb2": 1]) // TODO: remove grdb_ column?
XCTAssertEqual(rows[0].prefetchedRows["bs"]![1], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colb2": 1]) // TODO: remove grdb_ column?
XCTAssertEqual(rows[1], ["cola1": 2, "cola2": "a2"])
XCTAssertEqual(rows[1].prefetchedRows.count, 1)
XCTAssertEqual(rows[1].prefetchedRows["bs"]!.count, 1)
XCTAssertEqual(rows[1].prefetchedRows["bs"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colb2": 2]) // TODO: remove grdb_ column?
XCTAssertEqual(rows[2], ["cola1": 3, "cola2": "a3"])
XCTAssertEqual(rows[2].prefetchedRows.count, 1)
XCTAssertEqual(rows[2].prefetchedRows["bs"]!.count, 0)
}
}
// Request with avoided prefetch
do {
let request = A
.filter(false)
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()) // TODO: auto-pluralization
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
"""])
}
// PrefetchedRows
do {
let rows = try Row.fetchAll(db, request)
XCTAssertEqual(rows.count, 0)
}
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") == 4)
.orderByPrimaryKey()
.forKey("bs1"))
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") != 4)
.orderByPrimaryKey()
.forKey("bs2"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE ("cola1" <> 3) \
ORDER BY "cola1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE (("colb1" = 4) AND ("colb2" IN (1, 2))) \
ORDER BY "colb1"
""",
"""
SELECT *, "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE (("colb1" <> 4) AND ("colb2" IN (1, 2))) \
ORDER BY "colb1"
"""])
}
// PrefetchedRows
do {
let rows = try Row.fetchAll(db, request)
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["cola1": 1, "cola2": "a1"])
XCTAssertEqual(rows[0].prefetchedRows.count, 2)
XCTAssertEqual(rows[0].prefetchedRows["bs1"]!.count, 1)
XCTAssertEqual(rows[0].prefetchedRows["bs1"]![0], ["colb1": 4, "colb2": 1, "colb3": "b1", "grdb_colb2": 1]) // TODO: remove grdb_ column?
XCTAssertEqual(rows[0].prefetchedRows["bs2"]!.count, 1)
XCTAssertEqual(rows[0].prefetchedRows["bs2"]![0], ["colb1": 5, "colb2": 1, "colb3": "b2", "grdb_colb2": 1]) // TODO: remove grdb_ column?
XCTAssertEqual(rows[1], ["cola1": 2, "cola2": "a2"])
XCTAssertEqual(rows[1].prefetchedRows.count, 2)
XCTAssertEqual(rows[1].prefetchedRows["bs1"]!.count, 0)
XCTAssertEqual(rows[1].prefetchedRows["bs2"]!.count, 1)
XCTAssertEqual(rows[1].prefetchedRows["bs2"]![0], ["colb1": 6, "colb2": 2, "colb3": "b3", "grdb_colb2": 2]) // TODO: remove grdb_ column?
}
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE ("colc2" IN (1, 2, 3)) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE ("cold2" IN (7, 8, 9)) \
ORDER BY "cold1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with avoided prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.filter(false)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (0 AND ("colc2" IN (1, 2, 3))) \
ORDER BY "colc1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("ds2"))
.orderByPrimaryKey()
.forKey("cs2"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 3) \
ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" > 7) AND ("colc2" IN (1, 2))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" IN (8, 9))) \
ORDER BY "cold1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" IN (8, 9))) \
ORDER BY "cold1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" < 9) AND ("colc2" IN (1, 2))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" IN (7, 8))) \
ORDER BY "cold1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" IN (7, 8))) \
ORDER BY "cold1"
"""])
}
// PrefetchedRows
do {
}
}
}
}
func testIncludingAllHasManyIncludingRequiredHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON ("d"."cold2" = "c"."colc1") \
WHERE ("c"."colc2" IN (1, 2, 3)) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with avoided prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.filter(false)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON ("d"."cold2" = "c"."colc1") \
WHERE (0 AND ("c"."colc2" IN (1, 2, 3))) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.forKey("cs2"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 3) \
ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
JOIN "d" "d1" ON (("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11)) \
JOIN "d" "d2" ON (("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11)) \
WHERE (("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2))) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
JOIN "d" "d1" ON (("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11)) \
JOIN "d" "d2" ON (("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11)) \
WHERE (("c"."colc1" < 9) AND ("c"."colc2" IN (1, 2))) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
"""])
}
// PrefetchedRows
do {
}
}
}
}
func testIncludingAllHasManyThrough() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2, 3))) \
ORDER BY "d"."cold1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).filter(Column("colc1") > 7).forKey("c1"), using: C.hasMany(D.self))
.orderByPrimaryKey()
.forKey("ds1"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c2"), using: C.hasMany(D.self))
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("ds2"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("c2"), using: C.hasMany(D.self))
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("ds3"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE ("cola1" <> 3) \
ORDER BY "cola1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND (("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2)))) \
ORDER BY "d"."cold1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2))) \
WHERE ("d"."cold1" <> 11) \
ORDER BY "d"."cold1"
""",
"""
SELECT "d".*, "c"."colc2" AS "grdb_colc2" \
FROM "d" \
JOIN "c" ON (("c"."colc1" = "d"."cold2") AND ("c"."colc2" IN (1, 2))) \
WHERE ("d"."cold1" = 11) \
ORDER BY "d"."cold1"
"""])
}
// PrefetchedRows
do {
}
}
}
}
func testIncludingAllHasManyThroughMergedWithHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey())
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self), using: C.hasMany(D.self))
.orderByPrimaryKey())
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE ("colc2" IN (1, 2, 3)) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE ("cold2" IN (7, 8, 9)) \
ORDER BY "cold1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 8)
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("cs1"), using: C.hasMany(D.self))
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("ds1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("cs2"))
.including(all: A
.hasMany(D.self, through: A.hasMany(C.self).forKey("cs2"), using: C.hasMany(D.self))
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("ds2"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE ("cola1" <> 3) \
ORDER BY "cola1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" <> 8) AND ("colc2" IN (1, 2))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" <> 11) AND ("cold2" IN (7, 9))) \
ORDER BY "cold1"
""",
"""
SELECT *, "colc2" AS "grdb_colc2" \
FROM "c" \
WHERE (("colc1" <> 9) AND ("colc2" IN (1, 2))) \
ORDER BY "colc1"
""",
"""
SELECT *, "cold2" AS "grdb_cold2" \
FROM "d" \
WHERE (("cold1" = 11) AND ("cold2" IN (7, 8))) \
ORDER BY "cold1"
"""])
}
// PrefetchedRows
do {
}
}
}
}
func testIncludingOptionalBelongsToIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
// Plain request
do {
let request = B
.including(optional: B
.belongsTo(A.self)
.including(all: A
.hasMany(C.self)
.orderByPrimaryKey())
)
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT "b".*, "a".* \
FROM "b" \
LEFT JOIN "a" ON ("a"."cola1" = "b"."colb2") \
ORDER BY "b"."colb1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND ("a"."cola1" IN (1, 2))) \
ORDER BY "c"."colc1"
"""])
}
// PrefetchedRows
do {
}
}
// Request with filters
do {
let request = B
.including(optional: B
.belongsTo(A.self)
.filter(Column("cola2") == "a1")
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") == 9)
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("cs2"))
.forKey("a1"))
.including(optional: B
.belongsTo(A.self)
.filter(Column("cola2") == "a2")
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") == 9)
.orderByPrimaryKey()
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") != 9)
.orderByPrimaryKey()
.forKey("cs2"))
.forKey("a2"))
.orderByPrimaryKey()
// SQL
do {
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT "b".*, "a1".*, "a2".* \
FROM "b" \
LEFT JOIN "a" "a1" ON (("a1"."cola1" = "b"."colb2") AND ("a1"."cola2" = 'a1')) \
LEFT JOIN "a" "a2" ON (("a2"."cola1" = "b"."colb2") AND ("a2"."cola2" = 'a2')) \
ORDER BY "b"."colb1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" = 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a1') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" <> 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" = 9) \
ORDER BY "c"."colc1"
""",
"""
SELECT "c".*, "a"."cola1" AS "grdb_cola1" \
FROM "c" \
JOIN "a" ON (("a"."cola1" = "c"."colc2") AND (("a"."cola2" = 'a2') AND ("a"."cola1" IN (1, 2)))) \
WHERE ("c"."colc1" <> 9) \
ORDER BY "c"."colc1"
"""])
}
// PrefetchedRows
do {
}
}
}
}
}