From ec2640a459e96f1acfbe097edf24ef4a8c7c314d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Nov 2020 19:21:46 +0100 Subject: [PATCH] CommonTableExpression is a table, after all --- .../Request/CommonTableExpression.swift | 112 +++++++------- .../Request/QueryInterfaceRequest.swift | 5 +- .../Request/RequestProtocols.swift | 45 ++++-- GRDB/QueryInterface/SQL/SQLQuery.swift | 2 +- GRDB/QueryInterface/SQL/SQLRelation.swift | 10 -- .../SQLGeneration/SQLQueryGenerator.swift | 21 +-- .../CommonTableExpressionTests.swift | 143 +++++++----------- 7 files changed, 154 insertions(+), 184 deletions(-) diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index eaa07f190..4695159ab 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -1,71 +1,75 @@ #warning("TODO: doc") public struct CommonTableExpression { - var key: String - var alias: TableAlias + var tableName: String var request: _FetchRequest var relationForAll: SQLRelation { SQLRelation( - source: .commonTableExpression(alias), - selectionPromise: DatabasePromise(value: [AllColumns()])) + source: .table(tableName: tableName, alias: nil), + selectionPromise: DatabasePromise(value: [_AllCTEColumns(request: request, alias: nil)])) } -} - -extension CommonTableExpression: Refinable { + #warning("TODO: doc") - public func forKey(_ key: String) -> Self { - with(\.key, key) - } - - #warning("TODO: doc") - public func aliased(_ alias: TableAlias) -> Self { - alias.becomeProxy(of: self.alias) - return self - } -} - -extension CommonTableExpression { - /// Returns a qualified value that is able to resolve ambiguities in - /// joined queries. - public subscript(_ selectable: SQLSelectable) -> SQLSelectable { - selectable._qualifiedSelectable(with: alias) - } - - /// Returns a qualified expression that is able to resolve ambiguities in - /// joined queries. - public subscript(_ expression: SQLExpression) -> SQLExpression { - expression._qualifiedExpression(with: alias) - } - - /// Returns a qualified ordering that is able to resolve ambiguities in - /// joined queries. - public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm { - ordering._qualifiedOrdering(with: alias) - } - - /// Returns a qualified columnn that is able to resolve ambiguities in - /// joined queries. - public subscript(_ column: String) -> SQLExpression { - Column(column)._qualifiedExpression(with: alias) - } -} - -extension QueryInterfaceRequest { - #warning("TODO: doc") - public func commonTableExpression() -> CommonTableExpression { - CommonTableExpression( - key: databaseTableName, - alias: TableAlias(tableName: databaseTableName), // Confusing. Should be a "baseName" - request: self) + public func all() -> QueryInterfaceRequest { + QueryInterfaceRequest(relation: relationForAll) } } extension _FetchRequest { #warning("TODO: doc") - public func commonTableExpression(key: String) -> CommonTableExpression { + public func commonTableExpression(tableName: String) -> CommonTableExpression { CommonTableExpression( - key: key, - alias: TableAlias(tableName: key), // Confusing. Should be a "baseName" + tableName: tableName, request: self) } } + +// MARK: - _AllCTEColumns + +/// :nodoc: +public struct _AllCTEColumns { + var request: _FetchRequest + var alias: TableAlias? +} + +extension _AllCTEColumns: SQLSelectable, Refinable { + /// :nodoc: + public func _count(distinct: Bool) -> _SQLCount? { + // SELECT DISTINCT * FROM tableName ... + if distinct { + // Can't count + return nil + } + + // SELECT * FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + return .all + } + + /// :nodoc: + public func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + // Never requalify + if self.alias != nil { + return self + } + return with(\.alias, alias) + } + + /// :nodoc: + public func _columnCount(_ db: Database) throws -> Int { + let context = SQLGenerationContext(db) + let sql = try request.requestSQL(context, forSingleResult: false) + let statement = try db.makeSelectStatement(sql: sql) + return statement.columnCount + } + + /// :nodoc: + public func _accept(_ visitor: inout Visitor) throws { + if let alias = alias { + return try _SQLQualifiedAllColumns(alias: alias)._accept(&visitor) + } else { + return try AllColumns()._accept(&visitor) + } + } +} diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index d10f4637c..af65a3e4d 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -273,9 +273,6 @@ extension QueryInterfaceRequest: TableRequest { // request.filter(keys: ...) // request.orderByPrimaryKey() return tableName - case .commonTableExpression: - #warning("TODO: is this ok?") - fatalError("Request is not based on a database table") case .subquery: // The only current use case for SQLSource.query is the // "trivial count query" (see SQLQuery.countQuery): @@ -341,7 +338,7 @@ extension QueryInterfaceRequest { #warning("TODO: doc") public func with(_ cte: CommonTableExpression) -> Self { - map(\.query) { $0.with(\.ctes[cte.key], cte) } + map(\.query) { $0.with(\.ctes[cte.tableName], cte.request) } } /// Creates a request bound to type RowDecoder. diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index 83e072367..a9c3573bd 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -587,28 +587,53 @@ extension JoinableRequest { } #warning("TODO: doc") - public func including(optional cte: CommonTableExpression, on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) -> Self { - _including(optional: association(to: cte, on: condition)) + public func including( + optional cte: CommonTableExpression, + forKey key: String, + on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) + -> Self + { + _including(optional: association(to: cte, forKey: key, on: condition)) } #warning("TODO: doc") - public func including(required cte: CommonTableExpression, on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) -> Self { - _including(required: association(to: cte, on: condition)) + public func including( + required cte: CommonTableExpression, + forKey key: String, + on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) + -> Self + { + _including(required: association(to: cte, forKey: key, on: condition)) } #warning("TODO: doc") - public func joining(optional cte: CommonTableExpression, on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) -> Self { - _joining(optional: association(to: cte, on: condition)) + public func joining( + optional cte: CommonTableExpression, + forKey key: String, + on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) + -> Self + { + _joining(optional: association(to: cte, forKey: key, on: condition)) } #warning("TODO: doc") - public func joining(required cte: CommonTableExpression, on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) -> Self { - _joining(required: association(to: cte, on: condition)) + public func joining( + required cte: CommonTableExpression, + forKey key: String, + on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) + -> Self + { + _joining(required: association(to: cte, forKey: key, on: condition)) } - private func association(to cte: CommonTableExpression, on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) -> _SQLAssociation { + private func association( + to cte: CommonTableExpression, + forKey key: String, + on condition: @escaping (TableAlias, TableAlias) -> SQLExpression) + -> _SQLAssociation + { _SQLAssociation( - key: .inflected(cte.key), + key: .fixedSingular(key), condition: .promise(condition), relation: cte.relationForAll, cardinality: .toOne) diff --git a/GRDB/QueryInterface/SQL/SQLQuery.swift b/GRDB/QueryInterface/SQL/SQLQuery.swift index a095bbdb7..7c0c131f3 100644 --- a/GRDB/QueryInterface/SQL/SQLQuery.swift +++ b/GRDB/QueryInterface/SQL/SQLQuery.swift @@ -10,7 +10,7 @@ struct SQLQuery { // `(a AND b AND c)` instead of `((a AND b) AND c)`. var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: []) var limit: SQLLimit? - var ctes: OrderedDictionary = [:] + var ctes: OrderedDictionary = [:] } extension SQLQuery: Refinable { diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 39512f2b2..530636e3d 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -393,7 +393,6 @@ extension SQLRelation: _JoinableRequest { enum SQLSource { case table(tableName: String, alias: TableAlias?) - case commonTableExpression(TableAlias) indirect case subquery(SQLQuery) func qualified(with alias: TableAlias) -> SQLSource { @@ -406,9 +405,6 @@ enum SQLSource { alias.setTableName(tableName) return .table(tableName: tableName, alias: alias) } - case let .commonTableExpression(sourceAlias): - alias.becomeProxy(of: sourceAlias) - return self case .subquery: return self } @@ -743,12 +739,6 @@ extension SQLSource { } return .table(tableName: tableName, alias: mergedAlias) } - case let (.commonTableExpression(alias), .commonTableExpression(otherAlias)): - guard let mergedAlias = alias.merged(with: otherAlias) else { - // can't merge - return nil - } - return .commonTableExpression(mergedAlias) default: // can't merge return nil diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 183e80654..cf4ac1efe 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -6,7 +6,7 @@ struct SQLQueryGenerator: Refinable { private let havingExpressionsPromise: DatabasePromise<[SQLExpression]> private let limit: SQLLimit? private let singleResult: Bool - private let ctes: OrderedDictionary + private let ctes: OrderedDictionary // For database region private let prefetchedAssociations: [_SQLAssociation] @@ -68,24 +68,17 @@ struct SQLQueryGenerator: Refinable { // Build an SQL generation context with all aliases found in the query, // so that we can disambiguate tables that are used several times with // SQL aliases. - var aliases = relation.allAliases - for alias in ctes.values.map(\.alias) { - // CTE alias is already in relation's if it is joined. - if aliases.contains(where: { $0 === alias }) == false { - aliases.append(alias) - } - } - let context = SQLGenerationContext(parent: context, aliases: aliases) + let context = SQLGenerationContext(parent: context, aliases: relation.allAliases) var sql = "" if !ctes.isEmpty { sql += "WITH " sql += try ctes - .map { (_, cte) in + .map { (tableName, request) in let cteContext = SQLGenerationContext(parent: context) - let cteSQL = try cte.request.requestSQL(cteContext, forSingleResult: false) - return "\(context.resolvedName(for: cte.alias).quotedDatabaseIdentifier) AS (\(cteSQL))" + let cteSQL = try request.requestSQL(cteContext, forSingleResult: false) + return "\(tableName.quotedDatabaseIdentifier) AS (\(cteSQL))" } .joined(separator: ", ") sql += " " @@ -735,9 +728,7 @@ private enum SQLQualifiedSource { case let .table(tableName, alias): let alias = alias ?? TableAlias(tableName: tableName) self = .table(tableName: tableName, alias: alias) - case let .commonTableExpression(alias): - self = .commonTableExpression(alias) - case let .subquery(subquery): + case let .subquery(subquery): self = .subquery(SQLQueryGenerator(query: subquery)) } } diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 3d6aab9dc..b7a371a2b 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -12,155 +12,118 @@ class CommonTableExpressionTests: GRDBTestCase { // Just add a WITH clause: query interface request do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".* FROM "t" "t1" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT * FROM "t" """) } // Just add a WITH clause: sql request do { let cte = SQLRequest(literal: "SELECT \("O'Brien")") - .commonTableExpression(key: "custom") + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) try assertEqualSQL(db, request, """ - WITH "custom" AS (SELECT 'O''Brien') \ - SELECT "t".* FROM "t" - """) - } - - // Just add a WITH clause: sql request with conflicting key - do { - let cte = SQLRequest(literal: "SELECT \("O'Brien")") - .commonTableExpression(key: "t") - let request = T.all() - .with(cte) - try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT 'O''Brien') \ - SELECT "t1".* FROM "t" "t1" - """) - } - - // Just add a WITH clause: sql request with conflicting alias name - do { - let cte = SQLRequest(literal: "SELECT \("O'Brien")") - .commonTableExpression(key: "custom") - .aliased(TableAlias(name: "t")) - let request = T.all() - .with(cte) - try assertEqualSQL(db, request, """ - WITH "t" AS (SELECT 'O''Brien') \ - SELECT "t1".* FROM "t" "t1" - """) - } - - // Just add a WITH clause: custom name for the CTE - do { - let cte = T.all() - .commonTableExpression() - .aliased(TableAlias(name: "custom")) - let request = T.all() - .with(cte) - try assertEqualSQL(db, request, """ - WITH "custom" AS (SELECT * FROM "t") \ - SELECT "t".* FROM "t" + WITH "cte" AS (SELECT 'O''Brien') \ + SELECT * FROM "t" """) } // Include query interface request as a CTE do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) - .including(optional: cte, on: { (left, right) in left["id"] > right["id"] }) + .including(optional: cte, forKey: "ignored", on: { (left, right) in left["id"] > right["id"] }) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".*, "t2".* \ - FROM "t" "t1" \ - LEFT JOIN "t2" ON "t1"."id" > "t2"."id" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".*, "cte".* \ + FROM "t" \ + LEFT JOIN "cte" ON "t"."id" > "cte"."id" """) } // Join query interface request as a CTE do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) - .joining(required: cte, on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "ignored", on: { (left, right) in left["id"] > right["id"] }) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".* \ - FROM "t" "t1" \ - JOIN "t2" ON "t1"."id" > "t2"."id" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" > "cte"."id" """) } // Join two CTEs with same key and condition do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) - .joining(required: cte, on: { (left, right) in left["id"] > right["id"] }) - .joining(required: cte, on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "ignored", on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "ignored", on: { (left, right) in left["id"] > right["id"] }) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".* \ - FROM "t" "t1" \ - JOIN "t2" ON "t1"."id" > "t2"."id" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" > "cte"."id" """) } - // Join two CTEs with same key but different condition + // Join two CTEs with same key but different condition (last condition wins) do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) - .joining(required: cte, on: { (left, right) in left["id"] > right["id"] }) - .joining(required: cte, on: { (left, right) in left["id"] + right["id"] == 1 }) + .joining(required: cte, forKey: "ignored", on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "ignored", on: { (left, right) in left["id"] + right["id"] == 1 }) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".* \ - FROM "t" "t1" \ - JOIN "t2" ON "t1"."id" > "t2"."id" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".* \ + FROM "t" \ + JOIN "cte" ON ("t"."id" + "cte"."id") = 1 """) } // Join two CTEs with different keys do { let cte = T.all() - .commonTableExpression() + .commonTableExpression(tableName: "cte") let request = T.all() .with(cte) - .joining(required: cte.forKey("a"), on: { (left, right) in left["id"] > right["id"] }) - .joining(required: cte.forKey("b"), on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "a", on: { (left, right) in left["id"] > right["id"] }) + .joining(required: cte, forKey: "b", on: { (left, right) in left["id"] > right["id"] }) try assertEqualSQL(db, request, """ - WITH "t2" AS (SELECT * FROM "t") \ - SELECT "t1".* \ - FROM "t" "t1" \ - JOIN "t2" ON "t1"."id" > "t2"."id" + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".* \ + FROM "t" \ + JOIN "cte" "cte1" ON "t"."id" > "cte1"."id" \ + JOIN "cte" "cte2" ON "t"."id" > "cte2"."id" """) } -// // Use CTE as a subquery -// do { -// let cte = T.all() -// .commonTableExpression() -// let request = T.all() -// .with(cte) -// .annotated(with: cte.all()) -// try assertEqualSQL(db, request, """ -// WITH "foo" AS (SELECT * FROM "t") \ -// SELECT "t".*, (SELECT * FROM "foo") FROM "t" -// """) -// } + // Use CTE as a subquery + do { + let cte = T.all() + .commonTableExpression(tableName: "cte") + let request = T.all() + .with(cte) + .annotated(with: cte.all()) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT *, (SELECT * FROM "cte") FROM "t" + """) + } } } }