From 73f4a9fb23e2b8e756d877e94623884ca3f43a88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Apr 2019 13:23:53 +0200 Subject: [PATCH 1/3] whitespace --- .../QueryInterface/Association/Association.swift | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index afee564bb..99765fbdb 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -246,28 +246,36 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.sqlAssociation.relation(from: $0, required: false) } + return mapRelation { + association.sqlAssociation.relation(from: $0, required: false) + } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.sqlAssociation.relation(from: $0, required: true) } + return mapRelation { + association.sqlAssociation.relation(from: $0, required: true) + } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.select([]).sqlAssociation.relation(from: $0, required: false) } + return mapRelation { + association.select([]).sqlAssociation.relation(from: $0, required: false) + } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { - return mapRelation { association.select([]).sqlAssociation.relation(from: $0, required: true) } + return mapRelation { + association.select([]).sqlAssociation.relation(from: $0, required: true) + } } } From 1e3de49251fb6bbc15417f1f9f382cfea682bc9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Apr 2019 13:25:56 +0200 Subject: [PATCH 2/3] Rename SQLJoin.Condition to SQLJoinCondition --- .../Association/Association.swift | 4 +- .../Association/BelongsToAssociation.swift | 2 +- .../Association/HasManyAssociation.swift | 2 +- .../Association/HasOneAssociation.swift | 2 +- GRDB/QueryInterface/SQLRelation.swift | 160 +++++++++--------- .../SQLSelectQueryGenerator.swift | 2 +- 6 files changed, 87 insertions(+), 85 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 99765fbdb..cd22fb01e 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -410,7 +410,7 @@ public /* TODO: internal */ struct SQLAssociation { // SQLAssociation is a non-empty array of association elements private struct Element { var key: String - var condition: SQLJoin.Condition + var condition: SQLJoinCondition var relation: SQLRelation } private var head: Element @@ -423,7 +423,7 @@ public /* TODO: internal */ struct SQLAssociation { self.tail = tail } - init(key: String, condition: SQLJoin.Condition, relation: SQLRelation) { + init(key: String, condition: SQLJoinCondition, relation: SQLRelation) { head = Element(key: key, condition: condition, relation: relation) tail = [] } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index d4d7fbb6e..f3d89f70b 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -146,7 +146,7 @@ extension TableRecord { destinationTable: Destination.databaseTableName, foreignKey: foreignKey) - let condition = SQLJoin.Condition( + let condition = SQLJoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: true) diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index eaecd468f..c3bbb9267 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -146,7 +146,7 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - let condition = SQLJoin.Condition( + let condition = SQLJoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: false) diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 2605ba97c..03700fffa 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -148,7 +148,7 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - let condition = SQLJoin.Condition( + let condition = SQLJoinCondition( foreignKeyRequest: foreignKeyRequest, originIsLeft: false) diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index 2fcc310be..b30fa3ce4 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -198,89 +198,91 @@ extension SQLRelation { } } +// MARK: - SQLJoinCondition + +/// The condition that links two joined tables. +/// +/// Currently, we only support one kind of join condition: foreign keys. +/// +/// SELECT ... FROM book JOIN author ON author.id = book.authorId +/// <- the join condition --> +/// +/// When we eventually add support for new ways to join tables, Condition +/// is the type we'll need to update. +/// +/// Condition equality allows merging of associations: +/// +/// // request1 and request2 are equivalent +/// let request1 = Book +/// .including(required: Book.author) +/// let request2 = Book +/// .including(required: Book.author) +/// .including(required: Book.author) +/// +/// // request3 and request4 are equivalent +/// let request3 = Book +/// .including(required: Book.author.filter(condition1 && condition2)) +/// let request4 = Book +/// .joining(required: Book.author.filter(condition1)) +/// .including(optional: Book.author.filter(condition2)) +struct SQLJoinCondition: Equatable { + /// Definition of a foreign key + var foreignKeyRequest: ForeignKeyRequest + + /// True if the table at the origin of the foreign key is on the left of + /// the sql JOIN operator. + /// + /// Let's consider the `book.authorId -> author.id` foreign key. + /// Its origin table is `book`. + /// + /// The origin table `book` is on the left of the JOIN operator for + /// the BelongsTo association: + /// + /// -- Book.including(required: Book.author) + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// + /// The origin table `book`is on the right of the JOIN operator for + /// the HasMany and HasOne associations: + /// + /// -- Author.including(required: Author.books) + /// SELECT ... FROM author JOIN book ON author.id = book.authorId + var originIsLeft: Bool + + var reversed: SQLJoinCondition { + return SQLJoinCondition(foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft) + } + + /// Returns an SQL expression for the join condition. + /// + /// SELECT ... FROM book JOIN author ON author.id = book.authorId + /// <- the SQL expression --> + /// + /// - 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 SQL expression. + func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { + let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db) + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + + return columnMapping + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } + .joined(operator: .and) + } +} + // MARK: - SQLJoin struct SQLJoin { - /// The condition that links two joined tables. - /// - /// Currently, we only support one kind of join condition: foreign keys. - /// - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// <- the join condition --> - /// - /// When we eventually add support for new ways to join tables, Condition - /// is the type we'll need to update. - /// - /// Condition equality allows merging of associations: - /// - /// // request1 and request2 are equivalent - /// let request1 = Book - /// .including(required: Book.author) - /// let request2 = Book - /// .including(required: Book.author) - /// .including(required: Book.author) - /// - /// // request3 and request4 are equivalent - /// let request3 = Book - /// .including(required: Book.author.filter(condition1 && condition2)) - /// let request4 = Book - /// .joining(required: Book.author.filter(condition1)) - /// .including(optional: Book.author.filter(condition2)) - struct Condition: Equatable { - /// Definition of a foreign key - var foreignKeyRequest: ForeignKeyRequest - - /// True if the table at the origin of the foreign key is on the left of - /// the sql JOIN operator. - /// - /// Let's consider the `book.authorId -> author.id` foreign key. - /// Its origin table is `book`. - /// - /// The origin table `book` is on the left of the JOIN operator for - /// the BelongsTo association: - /// - /// -- Book.including(required: Book.author) - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// - /// The origin table `book`is on the right of the JOIN operator for - /// the HasMany and HasOne associations: - /// - /// -- Author.including(required: Author.books) - /// SELECT ... FROM author JOIN book ON author.id = book.authorId - var originIsLeft: Bool - - var reversed: Condition { - return Condition(foreignKeyRequest: foreignKeyRequest, originIsLeft: !originIsLeft) - } - - /// Returns an SQL expression for the join condition. - /// - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// <- the SQL expression --> - /// - /// - 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 SQL expression. - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { - let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db) - let columnMapping: [(left: Column, right: Column)] - if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } - } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } - } - - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) - } - } - var isRequired: Bool - var condition: Condition + var condition: SQLJoinCondition var relation: SQLRelation } diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift index 5ac95d52c..f512e95b1 100644 --- a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -405,7 +405,7 @@ private enum SQLQualifiedSource { /// A "qualified" join, where all tables are identified with a table alias. private struct SQLQualifiedJoin { private let isRequired: Bool - private let condition: SQLJoin.Condition + private let condition: SQLJoinCondition let relation: SQLQualifiedRelation init(_ join: SQLJoin) { From 708538bcf071b10e1de771310483703f79b056fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 28 Apr 2019 14:46:20 +0200 Subject: [PATCH 3/3] Refactor join conditions --- GRDB/Core/DatabaseValue.swift | 48 +++++++- .../Association/Association.swift | 22 ++-- GRDB/QueryInterface/Column.swift | 16 --- .../QueryInterfaceRequest+Association.swift | 10 +- .../SQLExpression+QueryInterface.swift | 70 ------------ GRDB/QueryInterface/SQLExpression.swift | 7 -- GRDB/QueryInterface/SQLRelation.swift | 106 ++++++++++++++++-- .../SQLSelectQueryGenerator.swift | 29 +++-- 8 files changed, 176 insertions(+), 132 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index e6da5a18a..1adaea701 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -279,12 +279,6 @@ extension DatabaseValue { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return self } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return self - } } // CustomStringConvertible @@ -305,3 +299,45 @@ extension DatabaseValue { } } } + +/// Compares DatabaseValue like SQLite. +/// +/// See RxGRDB for tests. +/// +/// This comparison is not public because it does not handle text collations, +/// and may be dangerous when put in user hands. +/// +/// So far, the only goal of this sorting method so far is aesthetic, and +/// easier testing. +func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool { + switch (lhs.storage, rhs.storage) { + case (.int64(let lhs), .int64(let rhs)): + return lhs < rhs + case (.double(let lhs), .double(let rhs)): + return lhs < rhs + case (.int64(let lhs), .double(let rhs)): + return Double(lhs) < rhs + case (.double(let lhs), .int64(let rhs)): + return lhs < Double(rhs) + case (.string(let lhs), .string(let rhs)): + return lhs.utf8.lexicographicallyPrecedes(rhs.utf8) + case (.blob(let lhs), .blob(let rhs)): + return lhs.lexicographicallyPrecedes(rhs, by: <) + case (.blob, _): + return false + case (_, .blob): + return true + case (.string, _): + return false + case (_, .string): + return true + case (.int64, _), (.double, _): + return false + case (_, .int64), (_, .double): + return true + case (.null, _): + return false + case (_, .null): + return true + } +} diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index cd22fb01e..5d7a2d5b8 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -488,26 +488,26 @@ public /* TODO: internal */ struct SQLAssociation { /// /// // SELECT head.* FROM head WHERE head.originId = 123 /// origin.request(for: association) - func relation(to originTable: String, container originContainer: @escaping (Database) throws -> PersistenceContainer) -> SQLRelation { - // Build a "pivot" relation whose filter is the pivot condition - // injected with values contained in originContainer. + func pivotRelation(from originAlias: TableAlias, rows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation { let pivotCondition = pivot.condition let pivotAlias = TableAlias() let pivotRelation = pivot.relation .qualified(with: pivotAlias) .filter { db in - let originAlias = TableAlias(tableName: originTable) + // Build a join expression: `association.originId = origin.id` + let joinExpression = try pivotCondition.joinExpression(db, leftAlias: originAlias, rightAlias: pivotAlias) - // Build a join condition: `association.originId = origin.id` - let joinExpression = try pivotCondition.sqlExpression(db, leftAlias: originAlias, rightAlias: pivotAlias) - - // Replace `origin.id` with 123 - return try joinExpression.resolvedExpression(inContext: [originAlias: originContainer(db)]) + // Resolve to `association.originId = 123` or `association.originId IN (1, 2, 3)` + return try joinExpression.resolved(withLeftRows: originRows(db)) } - // We use elements backward: join conditions have to be reversed. + // We join elements backward: join conditions have to be reversed. let reversedElements = zip([head] + tail, tail) - .map { Element(key: $1.key, condition: $0.condition.reversed, relation: $1.relation.select([])) } + .map { (element, nextElement) in + Element( + key: nextElement.key, + condition: element.condition.reversed, + relation: nextElement.relation.select([])) } .reversed() // Empty tail? diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index e66ca6ba4..44be63df0 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -36,12 +36,6 @@ extension ColumnExpression { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return QualifiedColumn(name, alias: alias) } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return self - } } /// A column in a database table. @@ -85,16 +79,6 @@ struct QualifiedColumn: ColumnExpression { // Never requalify return self } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - guard - let container = context[alias], - let value = container.value(forCaseInsensitiveColumn: name) else - { - return self - } - return value - } } /// Support for column enums: diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 0fcb5230c..47b3f3bd1 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -107,10 +107,12 @@ extension TableRecord where Self: EncodableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { - let relation = association.sqlAssociation.relation( - to: type(of: self).databaseTableName, - container: { try PersistenceContainer($0, self) }) - return QueryInterfaceRequest(query: SQLSelectQuery(relation: relation)) + let originAlias = TableAlias(tableName: type(of: self).databaseTableName) + let pivotRelation = association.sqlAssociation.pivotRelation( + from: originAlias, + rows: { db in try [Row(PersistenceContainer(db, self))] }) + let query = SQLSelectQuery(relation: pivotRelation) + return QueryInterfaceRequest(query: query) } } diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 3268d3091..3d1c0deb8 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -89,12 +89,6 @@ public struct SQLExpressionLiteral : SQLExpression { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return self } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return self - } } // MARK: - SQLExpressionUnary @@ -166,12 +160,6 @@ public struct SQLExpressionUnary : SQLExpression { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context)) - } } // MARK: - SQLExpressionBinary @@ -275,12 +263,6 @@ public struct SQLExpressionBinary : SQLExpression { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) - } } // MARK: - SQLExpressionAnd @@ -308,10 +290,6 @@ struct SQLExpressionAnd : SQLExpression { return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) }) } - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) }) - } - func matchedRowIds(rowIdName: String?) -> Set? { let matchedRowIds = expressions.compactMap { $0.matchedRowIds(rowIdName: rowIdName) @@ -348,10 +326,6 @@ struct SQLExpressionOr : SQLExpression { return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) }) } - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) }) - } - func matchedRowIds(rowIdName: String?) -> Set? { if expressions.isEmpty { return [] @@ -414,10 +388,6 @@ struct SQLExpressionEqual: SQLExpression { return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) } - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionEqual(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) - } - func matchedRowIds(rowIdName: String?) -> Set? { // FIXME: this implementation ignores column aliases switch op { @@ -486,10 +456,6 @@ struct SQLExpressionContains : SQLExpression { return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) } - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) - } - func matchedRowIds(rowIdName: String?) -> Set? { // FIXME: this implementation ignores column aliases // Look for `id IN (1, 2, 3)` @@ -560,14 +526,6 @@ struct SQLExpressionBetween : SQLExpression { upperBound.qualifiedExpression(with: alias), negated: isNegated) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionBetween( - expression.resolvedExpression(inContext: context), - lowerBound.resolvedExpression(inContext: context), - upperBound.resolvedExpression(inContext: context), - negated: isNegated) - } } // MARK: - SQLExpressionFunction @@ -646,12 +604,6 @@ public struct SQLExpressionFunction : SQLExpression { public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) }) - } } // MARK: - SQLExpressionCount @@ -675,10 +627,6 @@ struct SQLExpressionCount : SQLExpression { func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionCount(counted.qualifiedSelectable(with: alias)) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return self - } } // MARK: - SQLExpressionCountDistinct @@ -701,10 +649,6 @@ struct SQLExpressionCountDistinct : SQLExpression { func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return self - } } // MARK: - SQLExpressionIsEmpty @@ -737,10 +681,6 @@ struct SQLExpressionIsEmpty : SQLExpression { func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionIsEmpty(countExpression.qualifiedExpression(with: alias), isEmpty: isEmpty) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionIsEmpty(countExpression.resolvedExpression(inContext: context), isEmpty: isEmpty) - } } // MARK: - TableMatchExpression @@ -758,12 +698,6 @@ struct TableMatchExpression: SQLExpression { alias: self.alias, pattern: pattern.qualifiedExpression(with: alias)) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return TableMatchExpression( - alias: alias, - pattern: pattern.resolvedExpression(inContext: context)) - } } // MARK: - SQLExpressionCollate @@ -793,8 +727,4 @@ struct SQLExpressionCollate : SQLExpression { func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName) - } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index 4d491ebca..ff235ed34 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -48,9 +48,6 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func qualifiedExpression(with alias: TableAlias) -> SQLExpression - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -147,8 +144,4 @@ struct SQLExpressionNot : SQLExpression { func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionNot(expression.qualifiedExpression(with: alias)) } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionNot(expression.resolvedExpression(inContext: context)) - } } diff --git a/GRDB/QueryInterface/SQLRelation.swift b/GRDB/QueryInterface/SQLRelation.swift index b30fa3ce4..db08a3aca 100644 --- a/GRDB/QueryInterface/SQLRelation.swift +++ b/GRDB/QueryInterface/SQLRelation.swift @@ -1,6 +1,14 @@ /// A "relation" as defined by the [relational terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology): /// /// > A set of tuples sharing the same attributes; a set of columns and rows. +/// +/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ... +/// | | | | | +/// | | | | • ordering +/// | | | • filterPromise +/// | | • joins +/// | • source +/// • selection struct SQLRelation { var source: SQLSource var selection: [SQLSelectable] @@ -207,10 +215,10 @@ extension SQLRelation { /// SELECT ... FROM book JOIN author ON author.id = book.authorId /// <- the join condition --> /// -/// When we eventually add support for new ways to join tables, Condition +/// When we eventually add support for new ways to join tables, SQLJoinCondition /// is the type we'll need to update. /// -/// Condition equality allows merging of associations: +/// SQLJoinCondition equality allows merging of associations: /// /// // request1 and request2 are equivalent /// let request1 = Book @@ -254,8 +262,9 @@ struct SQLJoinCondition: Equatable { /// Returns an SQL expression for the join condition. /// - /// SELECT ... FROM book JOIN author ON author.id = book.authorId - /// <- the SQL expression --> + /// SELECT * FROM left JOIN right ON (right.a = left.b) + /// <----------------> + /// SQLJoinExpression /// /// - parameter db: A database connection. /// - parameter leftAlias: A TableAlias for the table on the left of the @@ -263,18 +272,93 @@ struct SQLJoinCondition: Equatable { /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. /// - Returns: An SQL expression. - func sqlExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLExpression { + func joinExpression(_ db: Database, leftAlias: TableAlias, rightAlias: TableAlias) throws -> SQLJoinExpression { let foreignKeyMapping = try foreignKeyRequest.fetchMapping(db) - let columnMapping: [(left: Column, right: Column)] + let columnMapping: [(left: String, right: String)] if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + columnMapping = foreignKeyMapping.map { (left: $0.origin, right: $0.destination) } } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + columnMapping = foreignKeyMapping.map { (left: $0.destination, right: $0.origin) } + } + return SQLJoinExpression(leftAlias: leftAlias, rightAlias: rightAlias, columnMapping: columnMapping) + } +} + +// MARK: - SQLJoinExpression + +/// The expression used to join two tables: +/// +/// SELECT * FROM left JOIN right ON (right.a = left.b) +/// <----------------> +/// SQLJoinExpression +/// +/// SQLJoinExpression can be resolved against rows, in order to give +/// `right.a = 1` or `right.a IN (1, 2, 3)`. +struct SQLJoinExpression: SQLExpression { + var leftAlias: TableAlias + var rightAlias: TableAlias + var columnMapping: [(left: String, right: String)] + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return columnMapping + .map { QualifiedColumn($0.right, alias: rightAlias) == QualifiedColumn($0.left, alias: leftAlias) } + .joined(operator: .and) + .expressionSQL(&context) + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + // self is already qualified + return self + } + + /// Resolves against given rows. + /// + /// Given `right.a = left.b`, returns `right.a = 1` or + /// `right.a IN (1, 2, 3)`. + func resolved(withLeftRows rows: [Row]) -> SQLExpression { + let valueMappings = columnMapping.map { columns in + (column: QualifiedColumn(columns.right, alias: rightAlias), + dbValues: rows.map { $0[columns.left] as DatabaseValue }) } - return columnMapping - .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } - .joined(operator: .and) + guard let firstValueMapping = valueMappings.first else { + // Likely a GRDB bug + fatalError("No joining column") + } + + if valueMappings.count == 1 { + // Join on a single column. + // Unique and sort database values for nicer output: + let dbValues = firstValueMapping.dbValues + .reduce(into: Set(), { $0.insert($1) }) + .sorted(by: <) + + guard let dbValue = dbValues.first else { + // Likely a GRDB bug + fatalError("No resolving rows") + } + + if dbValues.count == 1 { + // Single row: table.a = 1 + return (firstValueMapping.column == dbValue) + } else { + // Multiple rows: table.a IN (1, 2, 3) + return dbValues.contains(firstValueMapping.column) + } + } else { + // Join on a multiple columns. + assert(Set(valueMappings.map { $0.dbValues.count }).count == 1, "inconsistent values count") + if firstValueMapping.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") + } + } } } diff --git a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift index f512e95b1..5aa9de57d 100644 --- a/GRDB/QueryInterface/SQLSelectQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLSelectQueryGenerator.swift @@ -215,11 +215,21 @@ struct SQLSelectQueryGenerator { } /// A "qualified" relation, where all tables are identified with a table alias. +/// +/// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... +/// | | | | | | +/// | | | | | • ordering +/// | | | | • filterPromise +/// | | | • directJoins +/// | | • alias +/// | • source +/// • fullSelection private struct SQLQualifiedRelation { /// The alias for the relation /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ alias + /// | + /// • alias let alias: TableAlias /// All aliases, including aliases of joined relations @@ -235,7 +245,8 @@ private struct SQLQualifiedRelation { /// The source /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ source + /// | + /// • source let source: SQLQualifiedSource /// The selection, not including selection of joined relations @@ -244,7 +255,8 @@ private struct SQLQualifiedRelation { /// The full selection, including selection of joined relations /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ fullSelection + /// | + /// • fullSelection var selection: [SQLSelectable] { return joins.reduce(into: ownSelection) { $0.append(contentsOf: $1.value.relation.selection) @@ -254,7 +266,8 @@ private struct SQLQualifiedRelation { /// The filtering clause /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ filterPromise + /// | + /// • filterPromise let filterPromise: DatabasePromise /// The ordering, not including ordering of joined relations @@ -263,7 +276,8 @@ private struct SQLQualifiedRelation { /// The full ordering, including orderings of joined relations /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ ordering + /// | + /// • ordering var ordering: SQLRelation.Ordering { return joins.reduce(ownOrdering) { $0.appending($1.value.relation.ordering) @@ -273,7 +287,8 @@ private struct SQLQualifiedRelation { /// The joins /// /// SELECT ... FROM ... AS ... JOIN ... WHERE ... ORDER BY ... - /// ^ joins + /// | + /// • joins let joins: OrderedDictionary init(_ relation: SQLRelation) { @@ -433,7 +448,7 @@ private struct SQLQualifiedJoin { let rightAlias = relation.alias let filters = try [ - condition.sqlExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), + condition.joinExpression(db, leftAlias: leftAlias, rightAlias: rightAlias), relation.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty {