mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
HasManyAssociation.first and last
This commit is contained in:
1 parent
a715c6328d
commit
fb550d30a0
8 files changed
+250
-27
No files matched your search
@@ -97,6 +97,7 @@ public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toOne)
|
||||
cardinality: .toOne,
|
||||
firstOnly: false)
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,19 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toMany)
|
||||
cardinality: .toMany,
|
||||
firstOnly: false)
|
||||
}
|
||||
|
||||
/// TODO
|
||||
public var first: HasOneAssociation<Origin, Destination> {
|
||||
var step = sqlAssociation.steps[0]
|
||||
step.firstOnly = true
|
||||
return HasOneAssociation(sqlAssociation: SQLAssociation(steps: [step]))
|
||||
}
|
||||
|
||||
/// TODO
|
||||
public var last: HasOneAssociation<Origin, Destination> {
|
||||
reversed().first
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toOne)
|
||||
cardinality: .toOne,
|
||||
firstOnly: false)
|
||||
}
|
||||
}
|
||||
@@ -75,13 +75,15 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
key: SQLAssociationKey,
|
||||
condition: SQLAssociationCondition,
|
||||
relation: SQLRelation,
|
||||
cardinality: SQLAssociationCardinality)
|
||||
cardinality: SQLAssociationCardinality,
|
||||
firstOnly: Bool)
|
||||
{
|
||||
let step = SQLAssociationStep(
|
||||
key: key,
|
||||
condition: condition,
|
||||
relation: relation,
|
||||
cardinality: cardinality)
|
||||
cardinality: cardinality,
|
||||
firstOnly: firstOnly)
|
||||
self.init(steps: [step])
|
||||
}
|
||||
|
||||
@@ -187,7 +189,8 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
key: key,
|
||||
condition: nextStep.condition.reversed,
|
||||
relation: relation,
|
||||
cardinality: .toOne)
|
||||
cardinality: .toOne,
|
||||
firstOnly: false)
|
||||
})
|
||||
.reversed()
|
||||
let reversedAssociation = SQLAssociation(steps: Array(reversedSteps))
|
||||
@@ -202,6 +205,7 @@ struct SQLAssociationStep: Refinable {
|
||||
var condition: SQLAssociationCondition
|
||||
var relation: SQLRelation
|
||||
var cardinality: SQLAssociationCardinality
|
||||
var firstOnly: Bool
|
||||
|
||||
var keyName: String { key.name(for: cardinality) }
|
||||
}
|
||||
|
||||
@@ -124,6 +124,7 @@ struct SQLRelation {
|
||||
var kind: Kind
|
||||
var condition: SQLAssociationCondition
|
||||
var relation: SQLRelation
|
||||
var firstOnly: Bool
|
||||
|
||||
/// Returns true iff this child can change the parent count.
|
||||
///
|
||||
@@ -144,7 +145,8 @@ struct SQLRelation {
|
||||
key: key,
|
||||
condition: condition,
|
||||
relation: relation,
|
||||
cardinality: kind.cardinality)
|
||||
cardinality: kind.cardinality,
|
||||
firstOnly: firstOnly)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,6 +218,15 @@ extension SQLRelation: Refinable {
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
map(\.source) { $0.qualified(with: alias) }
|
||||
}
|
||||
|
||||
// Remove everything but selection
|
||||
var witnessRelation: Self {
|
||||
var result = self
|
||||
result.filtersPromise = DatabasePromise(value: [])
|
||||
result.ordering = SQLRelation.Ordering()
|
||||
result.children = [:]
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation {
|
||||
@@ -261,7 +272,8 @@ extension SQLRelation {
|
||||
let child = SQLRelation.Child(
|
||||
kind: kind,
|
||||
condition: association.destination.condition,
|
||||
relation: association.destination.relation)
|
||||
relation: association.destination.relation,
|
||||
firstOnly: association.destination.firstOnly)
|
||||
|
||||
let initialSteps = association.steps.dropLast()
|
||||
if initialSteps.isEmpty {
|
||||
@@ -705,6 +717,11 @@ extension SQLRelation.Child {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard firstOnly == other.firstOnly else {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let mergedRelation = relation.merged(with: other.relation) else {
|
||||
// can't merge
|
||||
return nil
|
||||
@@ -718,7 +735,8 @@ extension SQLRelation.Child {
|
||||
return SQLRelation.Child(
|
||||
kind: mergedKind,
|
||||
condition: condition,
|
||||
relation: mergedRelation)
|
||||
relation: mergedRelation,
|
||||
firstOnly: firstOnly)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -493,10 +493,19 @@ private struct SQLQualifiedRelation {
|
||||
return nil
|
||||
}
|
||||
|
||||
return SQLQualifiedJoin(
|
||||
kind: kind,
|
||||
condition: child.condition,
|
||||
relation: SQLQualifiedRelation(child.relation))
|
||||
if child.firstOnly {
|
||||
return SQLQualifiedJoin(
|
||||
kind: kind,
|
||||
condition: child.condition,
|
||||
relation: SQLQualifiedRelation(child.relation.witnessRelation),
|
||||
target: .firstOnly(child.relation))
|
||||
} else {
|
||||
return SQLQualifiedJoin(
|
||||
kind: kind,
|
||||
condition: child.condition,
|
||||
relation: SQLQualifiedRelation(child.relation),
|
||||
target: .all)
|
||||
}
|
||||
}
|
||||
sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) }
|
||||
filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } }
|
||||
@@ -620,26 +629,30 @@ private enum SQLQualifiedSource {
|
||||
}
|
||||
|
||||
/// A "qualified" join, where all tables are identified with a table alias.
|
||||
private struct SQLQualifiedJoin {
|
||||
private struct SQLQualifiedJoin: Refinable {
|
||||
enum Kind: String {
|
||||
case leftJoin = "LEFT JOIN"
|
||||
case innerJoin = "JOIN"
|
||||
}
|
||||
|
||||
let kind: Kind
|
||||
let condition: SQLAssociationCondition
|
||||
let relation: SQLQualifiedRelation
|
||||
enum Target {
|
||||
case all
|
||||
case firstOnly(SQLRelation)
|
||||
}
|
||||
|
||||
var kind: Kind
|
||||
var condition: SQLAssociationCondition
|
||||
var relation: SQLQualifiedRelation
|
||||
var target: Target
|
||||
// var firstOnly: Bool
|
||||
|
||||
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
|
||||
try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
|
||||
SQLQualifiedJoin(
|
||||
kind: kind,
|
||||
condition: condition,
|
||||
relation: relation.selectOnly(selection))
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
map(\.relation) { $0.selectOnly(selection) }
|
||||
}
|
||||
|
||||
private func sql(
|
||||
@@ -668,10 +681,28 @@ private struct SQLQualifiedJoin {
|
||||
sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))"
|
||||
|
||||
let rightAlias = relation.sourceAlias
|
||||
let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias)
|
||||
+ relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))"
|
||||
switch target {
|
||||
case let .all:
|
||||
let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias)
|
||||
+ relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))"
|
||||
}
|
||||
case let .firstOnly(subRelation):
|
||||
#warning("TODO: use child.condition")
|
||||
let subAlias = TableAlias()
|
||||
let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: subAlias)
|
||||
let subRelation = subRelation
|
||||
.qualified(with: subAlias)
|
||||
.selectOnly([Column.rowID])
|
||||
.map(\.filtersPromise) { $0.flatMap { DatabasePromise(value: filters + $0) } }
|
||||
let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil))
|
||||
let subQueryGenerator = SQLQueryGenerator(subQuery)
|
||||
|
||||
sql += " ON "
|
||||
sql += rightAlias[Column.rowID].expressionSQL(&context, wrappedInParenthesis: false)
|
||||
// SELECT rowid FROM child WHERE child.parentId = parent.id ORDER BY id DESC LIMIT 1
|
||||
sql += try " = (" + subQueryGenerator.sql(db, &context) + ")"
|
||||
}
|
||||
|
||||
for (_, join) in relation.joins {
|
||||
|
||||
@@ -489,7 +489,12 @@ extension TableRecord where Self: EncodableRecord {
|
||||
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
|
||||
try [Row(PersistenceContainer(db, self))]
|
||||
})
|
||||
return QueryInterfaceRequest(relation: destinationRelation)
|
||||
let request = QueryInterfaceRequest<A.RowDecoder>(relation: destinationRelation)
|
||||
if association.sqlAssociation.destination.firstOnly {
|
||||
return request.limit(1)
|
||||
} else {
|
||||
return request
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -760,4 +760,154 @@ class AssociationHasOneSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testHasManyFirst() throws {
|
||||
struct Child : TableRecord { }
|
||||
struct Parent: TableRecord, EncodableRecord {
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = 1
|
||||
container["rowid"] = 2
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parent") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("parentId", .integer).references("parent")
|
||||
}
|
||||
|
||||
do {
|
||||
let association = Parent
|
||||
.hasMany(Child.self)
|
||||
.orderByPrimaryKey()
|
||||
.first()
|
||||
try assertEqualSQL(db, Parent.all().including(required: association), """
|
||||
SELECT "parent".*, "child".* \
|
||||
FROM "parent" \
|
||||
JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().including(optional: association), """
|
||||
SELECT "parent".*, "child".* \
|
||||
FROM "parent" \
|
||||
LEFT JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().joining(required: association), """
|
||||
SELECT "parent".* \
|
||||
FROM "parent" \
|
||||
JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().joining(optional: association), """
|
||||
SELECT "parent".* \
|
||||
FROM "parent" \
|
||||
LEFT JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent().request(for: association), """
|
||||
SELECT * FROM "child" \
|
||||
WHERE "parentId" = 1 \
|
||||
ORDER BY "id" \
|
||||
LIMIT 1
|
||||
""")
|
||||
}
|
||||
// TODO: test that first/last can be used with filtering with further association
|
||||
}
|
||||
}
|
||||
|
||||
func testHasManyLast() throws {
|
||||
struct Child : TableRecord { }
|
||||
struct Parent: TableRecord, EncodableRecord {
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container["id"] = 1
|
||||
container["rowid"] = 2
|
||||
}
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(table: "parent") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("parentId", .integer).references("parent")
|
||||
}
|
||||
|
||||
do {
|
||||
let association = Parent
|
||||
.hasMany(Child.self)
|
||||
.orderByPrimaryKey()
|
||||
.last()
|
||||
try assertEqualSQL(db, Parent.all().including(required: association), """
|
||||
SELECT "parent".*, "child".* \
|
||||
FROM "parent" \
|
||||
JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" DESC \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().including(optional: association), """
|
||||
SELECT "parent".*, "child".* \
|
||||
FROM "parent" \
|
||||
LEFT JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" DESC \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().joining(required: association), """
|
||||
SELECT "parent".* \
|
||||
FROM "parent" \
|
||||
JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" DESC \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent.all().joining(optional: association), """
|
||||
SELECT "parent".* \
|
||||
FROM "parent" \
|
||||
LEFT JOIN "child" ON "child"."rowid" = (\
|
||||
SELECT "child"."rowid" \
|
||||
FROM "child" \
|
||||
WHERE "child"."parentId" = "parent"."id" \
|
||||
ORDER BY "child"."id" DESC \
|
||||
LIMIT 1)
|
||||
""")
|
||||
try assertEqualSQL(db, Parent().request(for: association), """
|
||||
SELECT * FROM "child" \
|
||||
WHERE "parentId" = 1 \
|
||||
ORDER BY "id" DESC \
|
||||
LIMIT 1
|
||||
""")
|
||||
}
|
||||
// TODO: test that first/last can be used with filtering with further association
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user