From a7b8a73dba9725475a6ac0dd0e46e82009236ae4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 19 Apr 2020 14:14:13 +0200 Subject: [PATCH] Cleanup After failed experiment: SELECT ... FROM parent JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early. So we're still stuck with: SELECT ... FROM parent JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1) For some reason SQLite accepts the reference to the parent table in this case. --- GRDB/QueryInterface/SQL/SQLRelation.swift | 15 ++++-- .../SQLGeneration/SQLQueryGenerator.swift | 46 +++++++++++-------- 2 files changed, 38 insertions(+), 23 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index c9d448659..da9b01374 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -224,6 +224,15 @@ extension SQLRelation: Refinable { } } + // Prepending filters for aesthetic reasons + func prependingFilters(_ filters: [SQLExpression]) -> Self { + map(\.filtersPromise) { filtersPromise in + filtersPromise.flatMap { existingFilters in + DatabasePromise { _ in filters + existingFilters } + } + } + } + func unfiltered() -> Self { with(\.filtersPromise, DatabasePromise(value: [])) } @@ -577,13 +586,11 @@ struct SQLAssociationCondition: Equatable { /// - parameter db: A database connection. /// - parameter leftAlias: A TableAlias for the table on the left of the /// JOIN operator. - /// - parameter rightAlias: A TableAlias for the table on the right of the - /// JOIN operator. /// - Returns: An array of SQL expression that should be joined with /// the AND operator. - func expressions(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> [SQLExpression] { + func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] { try columnMappings(db).map { - QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias) + Column($0.right) == QualifiedColumn($0.left, alias: leftAlias) } } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index ece0eef24..2ca9e5423 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -1,4 +1,3 @@ - /// SQLQueryGenerator is able to generate an SQL SELECT query. struct SQLQueryGenerator: Refinable { fileprivate private(set) var relation: SQLQualifiedRelation @@ -627,7 +626,7 @@ private struct SQLQualifiedJoin: Refinable { enum Target { case all - case subRelation(SQLRelation) + case first(SQLRelation) } var kind: Kind @@ -667,10 +666,8 @@ private struct SQLQualifiedJoin: Refinable { .unfiltered() .unordered() - let subRelation = relation - self.relation = SQLQualifiedRelation(outerRelation) - self.target = .subRelation(subRelation) + self.target = .first(relation) } else { self.relation = SQLQualifiedRelation(relation) self.target = .all @@ -709,32 +706,43 @@ private struct SQLQualifiedJoin: Refinable { case .leftJoin: allowsInnerJoin = false } + + // JOIN table... sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))" let rightAlias = relation.sourceAlias switch target { case .all: - let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: rightAlias) - + relation.filtersPromise.resolve(db) + // ... ON AND + var filters = try condition.expressions(db, leftAlias: leftAlias) + filters += try relation.filtersPromise.resolve(db) if filters.isEmpty == false { - sql += " ON \(filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false))" + let filterSQL = filters + .joined(operator: .and) + .qualifiedExpression(with: rightAlias) + .expressionSQL(&context, wrappedInParenthesis: false) + sql += " ON \(filterSQL)" } - case let .subRelation(subRelation): + case var .first(subRelation): + // Subquery: SELECT id ... guard let primaryKey = try subRelation.primaryKeyExpression(db) else { - fatalError("Not implemented") + fatalError("Not implemented: support for WITHOUT ROWID optimization") } - let subAlias = TableAlias() - let filters = try condition.expressions(db, leftAlias: leftAlias, rightAlias: subAlias) - let subRelation = subRelation - .qualified(with: subAlias) - .selectOnly([primaryKey]) - .map(\.filtersPromise) { $0.flatMap { DatabasePromise(value: filters + $0) } } - let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil)) - let subQueryGenerator = SQLQueryGenerator(subQuery) + subRelation = subRelation.select([primaryKey]) + // Subquery: ... WHERE AND + let filters = try condition.expressions(db, leftAlias: leftAlias) + subRelation = subRelation.prependingFilters(filters) + + // Subquery: ... LIMIT 1 + let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil)) + + // ... ON id = (SELECT id FROM table WHERE AND LIMIT 1) sql += " ON " sql += rightAlias[primaryKey].expressionSQL(&context, wrappedInParenthesis: false) - sql += try " = (" + subQueryGenerator.sql(db, &context) + ")" + sql += " = (" + sql += try SQLQueryGenerator(subQuery).sql(db, &context) + sql += ")" } for (_, join) in relation.joins {