mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63590ede60 |
No files matched your search
@@ -172,6 +172,11 @@ public struct SQL: Sendable {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from an SQL ordering term.
|
||||
public init(_ ordering: some SQLOrderingTerm) {
|
||||
self.init(elements: [.ordering(ordering.sqlOrdering)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
|
||||
@@ -281,6 +281,12 @@ extension Association {
|
||||
relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
}
|
||||
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation.limit = SQLLimit(limit: limit, offset: offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationToOne
|
||||
|
||||
@@ -1518,7 +1518,7 @@ private func prefetch(
|
||||
fatalError("Not implemented: prefetch association without any foreign key")
|
||||
|
||||
case let .foreignKey(pivotForeignKey):
|
||||
let originTable = originRelation.source.tableName
|
||||
let originTable = originRelation.source.associationOriginTable ?? originRelation.source.tableName
|
||||
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
|
||||
let pivotColumns = pivotMapping.map(\.right)
|
||||
let leftColumns = pivotMapping.map(\.left)
|
||||
@@ -1651,7 +1651,7 @@ func makePrefetchRequest(
|
||||
// Author.including(all: Author.books)
|
||||
let pivotAlias = TableAlias()
|
||||
|
||||
let prefetchRelation = association
|
||||
var prefetchRelation = association
|
||||
.with {
|
||||
$0.pivot.relation = $0.pivot.relation
|
||||
.aliased(pivotAlias)
|
||||
@@ -1660,7 +1660,52 @@ func makePrefetchRequest(
|
||||
.destinationRelation()
|
||||
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
|
||||
|
||||
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
|
||||
if let limit = prefetchRelation.limit {
|
||||
let baseName = "grdb_" + association.destination.key.name(singular: true)
|
||||
let cteName = baseName + "_limited"
|
||||
let rowNumberName = "rowNumber"
|
||||
|
||||
let ordering = prefetchRelation.ordering
|
||||
|
||||
let rowNumberFilter: SQLExpression
|
||||
if let offset = limit.offset {
|
||||
rowNumberFilter = ((offset + 1)..<(offset + 1 + limit.limit)).contains(Column(rowNumberName)).sqlExpression
|
||||
} else {
|
||||
rowNumberFilter = (Column(rowNumberName) <= limit.limit).sqlExpression
|
||||
}
|
||||
|
||||
#warning("TODO: the order clause may refer to stuff inside the CTE.")
|
||||
var limitedPrefetchRelation = prefetchRelation
|
||||
// Annotate with the row number
|
||||
.annotatedWhenConnected { db in
|
||||
var sql: SQL = "ROW_NUMBER() OVER (PARTITION BY "
|
||||
sql.append(literal: pivotColumns
|
||||
.map { SQL(Column($0)) }
|
||||
.joined(separator: ", "))
|
||||
|
||||
let orderings = try ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql.append(sql: " ORDER BY ")
|
||||
sql.append(literal: orderings
|
||||
.map { SQL($0) }
|
||||
.joined(separator: ", "))
|
||||
}
|
||||
sql.append(sql: ")")
|
||||
return [sql.forKey(rowNumberName)]
|
||||
}
|
||||
// Limit is applied below, with the rowNumber filter
|
||||
.unlimited()
|
||||
// Turn into a CTE so that we can filter by rowNumber
|
||||
.asCommonTableExpression(named: cteName)
|
||||
// Reapply order
|
||||
.orderWhenConnected { try ordering.resolve($0) }
|
||||
// Turnt the limit into a rowNumber filter
|
||||
.filter(rowNumberFilter)
|
||||
|
||||
return QueryInterfaceRequest<Row>(relation: limitedPrefetchRelation)
|
||||
} else {
|
||||
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
|
||||
}
|
||||
}
|
||||
|
||||
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
|
||||
|
||||
@@ -282,6 +282,12 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func unlimited() -> Self {
|
||||
with {
|
||||
$0.limit = nil
|
||||
}
|
||||
}
|
||||
|
||||
func withStableOrder() -> Self {
|
||||
with { relation in
|
||||
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
|
||||
@@ -655,6 +661,47 @@ extension SQLRelation {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation {
|
||||
#warning("TODO: the order clause may refer to stuff inside the CTE.")
|
||||
#warning("TODO: Try to leave the ordering inside the CTE")
|
||||
func asCommonTableExpression(named tableName: String) -> Self {
|
||||
with { relation in
|
||||
GRDBPrecondition(ctes[tableName] == nil, """
|
||||
Can't turn relation into a Common Table Expression because \
|
||||
CTE '\(tableName)' is already defined. Please file a bug \
|
||||
at https://github.com/groue/GRDB.swift/issues/new
|
||||
""")
|
||||
|
||||
relation.ctes[tableName] = SQLCTE(
|
||||
tableName: tableName,
|
||||
columns: nil,
|
||||
sqlSubquery: .relation(
|
||||
self
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingPrefetchedAssociations()),
|
||||
isRecursive: false)
|
||||
|
||||
relation.source = SQLSource(
|
||||
tableName: tableName,
|
||||
associationOriginTable: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
|
||||
relation.selectionPromise = DatabasePromise { _ in [.allColumns] }
|
||||
relation.filterPromise = nil
|
||||
relation.isDistinct = false
|
||||
relation.groupPromise = nil
|
||||
relation.havingExpressionPromise = nil
|
||||
relation.limit = nil
|
||||
|
||||
relation = relation.filteringChildren { child in
|
||||
switch child.kind {
|
||||
case .all, .bridge: true
|
||||
case .oneOptional, .oneRequired: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLLimit
|
||||
|
||||
struct SQLLimit {
|
||||
@@ -673,9 +720,15 @@ struct SQLLimit {
|
||||
// MARK: - SQLSource
|
||||
|
||||
struct SQLSource: Sendable {
|
||||
/// The name of a database table to select from.
|
||||
var tableName: String
|
||||
var alias: TableAlias?
|
||||
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
func aliased(_ alias: TableAlias) -> SQLSource {
|
||||
if let sourceAlias = self.alias {
|
||||
alias.becomeProxy(of: sourceAlias)
|
||||
|
||||
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
let region = try prefetchedRegion(
|
||||
db,
|
||||
associations: prefetchedAssociations,
|
||||
from: relation.source.tableName)
|
||||
from: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
statement.databaseRegion.formUnion(region)
|
||||
}
|
||||
|
||||
@@ -741,9 +741,15 @@ private struct SQLQualifiedSource {
|
||||
var tableName: String
|
||||
var alias: TableAlias
|
||||
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
init(_ source: SQLSource) {
|
||||
self.tableName = source.tableName
|
||||
self.alias = source.alias ?? TableAlias(tableName: source.tableName)
|
||||
self.associationOriginTable = source.associationOriginTable
|
||||
assert(alias.tableName == tableName)
|
||||
}
|
||||
|
||||
|
||||
@@ -157,6 +157,110 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.none()
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") == 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs1")
|
||||
.limit(3))
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") != 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs2")
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs1_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" = 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs2_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" <> 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs2_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -188,6 +292,42 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.select(Column("colb2"))
|
||||
.distinct()
|
||||
.order(Column("colb2"))
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb2") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb2"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -304,6 +444,141 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey_limit() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "parent") { t in
|
||||
t.column("parentA", .text)
|
||||
t.column("parentB", .text)
|
||||
t.primaryKey(["parentA", "parentB"])
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.column("pA", .text)
|
||||
t.column("pB", .text)
|
||||
t.column("name", .text)
|
||||
t.foreignKey(["pA", "pB"], references: "parent")
|
||||
}
|
||||
try db.execute(sql: """
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar');
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1');
|
||||
""")
|
||||
|
||||
struct Parent: TableRecord { }
|
||||
struct Child: TableRecord { }
|
||||
|
||||
// Plain request
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = Parent
|
||||
.none()
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.filter(Column("name") == "foo")
|
||||
.limit(3))
|
||||
.filter(Column("parentA") == "foo")
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Limited ordered request (preserve both ordering and limit in the CTE)
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
|
||||
SELECT * FROM "grdb_children_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8)
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -455,6 +730,218 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany_limit() 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()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE "colc2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE "cold2" IN (7, 8, 9)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided second-level prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE 0 AND ("colc2" IN (1, 2, 3))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// 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()
|
||||
.limit(1)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(2)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(4)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(5)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs1_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" > 7) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 1 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 2 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs2_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" < 9) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs2_limited" \
|
||||
WHERE "rowNumber" <= 5 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 4 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
])}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -730,6 +1217,138 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany_limit() 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()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
#warning("TODO: ordering on D is lost")
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
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"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey())
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
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"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") > 7)
|
||||
.including(optional: 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()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(optional: 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()
|
||||
.limit(3)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
|
||||
FROM "c" \
|
||||
LEFT 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" \
|
||||
LEFT 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"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyThroughHasManyUsingHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
|
||||
Reference in new issue
Block a user