Association prefetching: add support for composite foreign keys

This commit is contained in:
Gwendal Roué committed 2019-05-20 19:35:50 +02:00
1 parent c841120d3b
commit 7674f2f522
2 files changed
+91 -23

No files matched your search

+23 -22
View File
@@ -460,21 +460,18 @@ struct SQLAssociationCondition: Equatable {
return false.sqlExpression
}
let columnMapping = try self.columnMapping(db)
let valueMappings = columnMapping.map { columns in
(column: QualifiedColumn(columns.right, alias: rightAlias),
dbValues: leftRows.map { $0[columns.left] as DatabaseValue })
}
guard let valueMapping = valueMappings.first else {
let columnMappings = try self.columnMapping(db)
guard let columnMapping = columnMappings.first else {
// Degenerate case: no joining column
return true.sqlExpression
}
if valueMappings.count == 1 {
// Join on a single column.
if columnMappings.count == 1 {
// Join on a single right column.
let rightColumn = QualifiedColumn(columnMapping.right, alias: rightAlias)
// Unique database values and filter out NULL:
var dbValues = Set(valueMapping.dbValues)
var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue })
dbValues.remove(.null)
if dbValues.isEmpty {
@@ -482,23 +479,27 @@ struct SQLAssociationCondition: Equatable {
return false.sqlExpression
} else if dbValues.count == 1 {
// Single row: table.a = 1
return (valueMapping.column == dbValues.first!)
return (rightColumn == dbValues.first!)
} else {
// Multiple rows: table.a IN (1, 2, 3)
// Multiple rows: table.a IN (1, 2, 3, ...)
// Sort database values for nicer output.
return dbValues.sorted(by: <).contains(valueMapping.column)
return dbValues.sorted(by: <).contains(rightColumn)
}
} else {
// Join on a multiple columns.
if valueMapping.dbValues.count == 1 {
// Single row: (table.a = 1) AND (table.b = 2)
return valueMappings
.map { $0.column == $0.dbValues[0] }
.joined(operator: .and)
} else {
// Multiple rows: TODO
fatalError("not implemented")
}
// ((table.a = 1) AND (table.b = 2)) OR ((table.a = 3) AND (table.b = 4)) ...
return leftRows
.map { leftRow in
// (table.a = 1) AND (table.b = 2)
columnMappings
.map { columns -> SQLExpression in
let rightColumn = QualifiedColumn(columns.right, alias: rightAlias)
let leftValue = leftRow[columns.left] as DatabaseValue
return rightColumn == leftValue
}
.joined(operator: .and)
}
.joined(operator: .or)
}
}
}
@@ -100,7 +100,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
.filter(false)
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()) // TODO: auto-pluralization
.orderByPrimaryKey())
.orderByPrimaryKey()
sqlQueries.removeAll()
@@ -155,6 +155,73 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
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("parentA", .text)
t.column("parentB", .text)
t.column("name", .text)
t.foreignKey(["parentA", "parentB"], 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 (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar1');
INSERT INTO child (parentA, parentB, name) VALUES ('foo', 'bar', 'foobar2');
INSERT INTO child (parentA, parentB, name) VALUES ('baz', 'qux', 'bazqux1');
""")
struct Parent: TableRecord { }
struct Child: TableRecord { }
// Plain request
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
SELECT *, "parentA" AS "grdb_parentA", "parentB" AS "grdb_parentB" \
FROM "child" \
WHERE ((("parentA" = 'baz') AND ("parentB" = 'qux')) OR (("parentA" = 'foo') AND ("parentB" = 'bar')))
"""])
}
// Request with avoided prefetch
do {
let request = Parent
.filter(false)
.including(all: Parent
.hasMany(Child.self))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter { $0.contains("SELECT") }
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
"""])
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in