diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index e4cb8a33b..b61fe07f4 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -188,17 +188,19 @@ extension TableRecord { condition: .expression(condition), relation: cte.relationForAll) } - - #warning("TODO: what about exposing left-right columns mapping instead?") - #warning("TODO: doc") + + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// - parameter cte: A common table expression. + /// - returns: An association to the common table expression. public static func association( - to cte: CommonTableExpression, - using columns: [Column] = []) + to cte: CommonTableExpression) -> JoinAssociation { JoinAssociation( key: .inflected(cte.tableName), - condition: .using(columns), + condition: .none, relation: cte.relationForAll) } } @@ -223,15 +225,18 @@ extension CommonTableExpression { relation: cte.relationForAll) } - #warning("TODO: doc") + /// Creates an association to a common table expression that you can join + /// or include in another request. + /// + /// - parameter cte: A common table expression. + /// - returns: An association to the common table expression. public func association( - to cte: CommonTableExpression, - using columns: [Column] = []) + to cte: CommonTableExpression) -> JoinAssociation { JoinAssociation( key: .inflected(cte.tableName), - condition: .using(columns), + condition: .none, relation: cte.relationForAll) } @@ -255,16 +260,19 @@ extension CommonTableExpression { relation: Destination.relationForAll) } - #warning("TODO: doc") + /// Creates an association to a table record that you can join + /// or include in another request. + /// + /// - parameter cte: A common table expression. + /// - returns: An association to the common table expression. public func association( - to destination: Destination.Type, - using columns: [Column] = []) + to destination: Destination.Type) -> JoinAssociation where Destination: TableRecord { JoinAssociation( key: .inflected(Destination.databaseTableName), - condition: .using(columns), + condition: .none, relation: Destination.relationForAll) } } diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index a5531c047..7971f1d94 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -526,18 +526,16 @@ enum SQLAssociationCondition { /// SELECT ... FROM author JOIN book ON author.id = book.authorId case foreignKey(request: SQLForeignKeyRequest, originIsLeft: Bool) - #warning("TODO: remove") - case using([Column]) - #warning("TODO: doc") case expression((TableAlias, TableAlias) -> SQLExpressible) + /// The "absent" joining condition + static let none = expression({ _, _ in true }) + var reversed: SQLAssociationCondition { switch self { case let .foreignKey(request: request, originIsLeft: originIsLeft): return .foreignKey(request: request, originIsLeft: !originIsLeft) - case .using: - return self case let .expression(condition): return .expression { condition($1, $0) } } @@ -764,13 +762,6 @@ extension SQLAssociationCondition { // can't merge return nil } - case let (.using(lhs), .using(rhs)): - if lhs == rhs { - return self - } else { - // can't merge - return nil - } case let (.expression, .expression(rhs)): // Can't compare functions: the last one wins return .expression(rhs) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift index 531020dc8..e17c486bb 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLPreparedRequestGenerator.swift @@ -144,10 +144,6 @@ private func prefetch(_ db: Database, associations: [_SQLAssociation], in rows: // are not prefetched with including(all:) fatalError("Not implemented: prefetch association without any foreign key") - case let .using(columns): - let pivotMapping: JoinMapping = columns.map { (left: $0.name, right: $0.name) } - try prefetch(db, association: association, pivotMapping: pivotMapping, in: rows) - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): let pivotMapping = try foreignKeyRequest .fetchForeignKeyMapping(db) @@ -228,11 +224,6 @@ func prefetchedRegion(_ db: Database, associations: [_SQLAssociation]) throws -> // are not prefetched with including(all:) fatalError("Not implemented: prefetch association without any foreign key") - case let .using(columns): - let pivotMapping: JoinMapping = columns.map { (left: $0.name, right: $0.name) } - let prefetchRegion = try prefetchedRegion(db, association: association, pivotMapping: pivotMapping) - region.formUnion(prefetchRegion) - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): let pivotMapping = try foreignKeyRequest .fetchForeignKeyMapping(db) diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 2a54afa8a..d06a73798 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -829,10 +829,13 @@ private struct SQLQualifiedJoin: Refinable { var joinExpressions: [SQLExpression] switch condition { case let .expression(condition): - joinExpressions = [condition(leftAlias, rightAlias).sqlExpression] - - case let .using(columns): - joinExpressions = columns.map { leftAlias[$0] == rightAlias[$0] } + let joinExpression = condition(leftAlias, rightAlias).sqlExpression + if joinExpression.isTrue { + // Avoid generating an ON clause if possible + joinExpressions = [] + } else { + joinExpressions = [joinExpression] + } case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): joinExpressions = try foreignKeyRequest @@ -858,6 +861,130 @@ private struct SQLQualifiedJoin: Refinable { } } +// MARK: - SQLExpressionIsTrue + +extension SQLExpression { + /// Returns true if the expression is trivially true. + /// + /// When in doubt, returns false. + /// + /// Support for removing the ON clause when possible. + var isTrue: Bool { + var visitor = SQLExpressionIsTrue() + do { + try _accept(&visitor) + } catch is SQLExpressionIsTrue.BreakError { + } catch { + try! { throw error }() + } + return visitor.isTrue + } +} + +/// Support for `SQLExpression.isTrue` +private struct SQLExpressionIsTrue: _SQLExpressionVisitor { + struct BreakError: Error { } + var isTrue = true + + private mutating func setFalse() throws -> Never { + isTrue = false + // Poor man's short-circuiting + throw BreakError() + } + + mutating func visit(_ dbValue: DatabaseValue) throws { + if dbValue != true.databaseValue { + try setFalse() + } + } + + mutating func visit(_ column: Column) throws where Column: ColumnExpression { + try setFalse() + } + + mutating func visit(_ column: _SQLQualifiedColumn) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionBetween) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionBinary) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionAssociativeBinary) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionCollate) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionContains) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionCount) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionCountDistinct) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionEqual) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionFastPrimaryKey) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionFunction) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionIsEmpty) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionLiteral) throws { + try setFalse() // Don't know - assume not true + } + + mutating func visit(_ expr: _SQLExpressionNot) throws { + try setFalse() // Could do better + } + + mutating func visit(_ expr: _SQLExpressionQualifiedFastPrimaryKey) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionTableMatch) throws { + try setFalse() + } + + mutating func visit(_ expr: _SQLExpressionUnary) throws { + try setFalse() + } + + // MARK: - _FetchRequestVisitor + + mutating func visit(_ request: AdaptedFetchRequest) throws { + try setFalse() // Don't know - assume not true + } + + mutating func visit(_ request: QueryInterfaceRequest) throws { + try setFalse() // Don't know - assume not true + } + + mutating func visit(_ request: SQLRequest) throws { + try setFalse() // Don't know - assume not true + } +} + // MARK: - SQLExpressionIsConstantInRequest extension SQLExpression { diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index 03f240c0f..3052ac612 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -488,14 +488,9 @@ extension TableRecord where Self: EncodableRecord { { switch association._sqlAssociation.pivot.condition { case .expression: - // Likely a GRDB bug: such condition only exist for CTEs, for which - // no public method builds an Association. + #warning("TODO: find a use case") fatalError("Not implemented: request association without any foreign key") - case .using: - #warning("TODO: request on USING clause") - fatalError("Not implemented") - case let .foreignKey(request: foreignKeyRequest, originIsLeft: originIsLeft): let destinationRelation = association ._sqlAssociation diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 49d601ee4..50c1137f7 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -74,19 +74,19 @@ class CommonTableExpressionTests: GRDBTestCase { """) } - // Include SQL request as a CTE (true ON clause) + // Include SQL request as a CTE do { let cte = CommonTableExpression( named: "cte", - literal: "SELECT \("O'Brien")") + literal: "SELECT 1 as id") let request = T.all() .with(cte) - .including(required: T.association(to: cte, on: { _, _ in true })) + .including(required: T.association(to: cte, on: { (left, right) in left["id"] == right["id"] })) try assertEqualSQL(db, request, """ - WITH "cte" AS (SELECT 'O''Brien') \ + WITH "cte" AS (SELECT 1 as id) \ SELECT "t".*, "cte".* \ FROM "t" \ - JOIN "cte" ON 1 + JOIN "cte" ON "t"."id" = "cte"."id" """) } @@ -106,22 +106,6 @@ class CommonTableExpressionTests: GRDBTestCase { """) } - // Include SQL request as a CTE (USING clause) - do { - let cte = CommonTableExpression( - named: "cte", - literal: "SELECT 1 AS id") - let request = T.all() - .with(cte) - .including(required: T.association(to: cte, using: [Column("id")])) - try assertEqualSQL(db, request, """ - WITH "cte" AS (SELECT 1 AS id) \ - SELECT "t".*, "cte".* \ - FROM "t" \ - JOIN "cte" ON "t"."id" = "cte"."id" - """) - } - // Include SQL request as a CTE (custom column name) do { let cte = CommonTableExpression( @@ -130,7 +114,7 @@ class CommonTableExpressionTests: GRDBTestCase { literal: "SELECT 1, 2") let request = T.all() .with(cte) - .including(required: T.association(to: cte, using: [Column("id")])) + .including(required: T.association(to: cte, on: { (left, right) in left["id"] == right["id"] })) try assertEqualSQL(db, request, """ WITH "cte"("id", "a") AS (SELECT 1, 2) \ SELECT "t".*, "cte".* \ @@ -230,21 +214,6 @@ class CommonTableExpressionTests: GRDBTestCase { """) } - // Include one CTE twice with same key and used columns - do { - let cte = CommonTableExpression(named: "cte", request: T.all()) - let request = T.all() - .with(cte) - .including(required: T.association(to: cte, using: [Column("id")])) - .including(required: T.association(to: cte, using: [Column("id")])) - try assertEqualSQL(db, request, """ - WITH "cte" AS (SELECT * FROM "t") \ - SELECT "t".*, "cte".* \ - FROM "t" \ - JOIN "cte" ON "t"."id" = "cte"."id" - """) - } - // Include one CTE twice with same key but different condition (last condition wins) do { let cte = CommonTableExpression(named: "cte", request: T.all()) @@ -265,14 +234,14 @@ class CommonTableExpressionTests: GRDBTestCase { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) - .including(required: T.association(to: cte, using: [Column("id")]).forKey("a")) - .including(required: T.association(to: cte, using: [Column("id")]).forKey("b")) + .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }).forKey("a")) + .including(required: T.association(to: cte, on: { (left, right) in left["id"] < right["id"] }).forKey("b")) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte1".*, "cte2".* \ FROM "t" \ - JOIN "cte" "cte1" ON "t"."id" = "cte1"."id" \ - JOIN "cte" "cte2" ON "t"."id" = "cte2"."id" + JOIN "cte" "cte1" ON "t"."id" > "cte1"."id" \ + JOIN "cte" "cte2" ON "t"."id" < "cte2"."id" """) }