From 17e745f52b2e79a0f21278bbf70fcf0da46be92a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 9 May 2020 09:41:45 +0200 Subject: [PATCH] SQLRequestProtocol, close FetchRequest --- GRDB.xcodeproj/project.pbxproj | 10 + GRDB/Core/FetchRequest.swift | 127 ++++---- GRDB/Core/SQLLiteral.swift | 6 +- GRDB/Core/SQLRequest.swift | 57 +--- GRDB/Core/SQLRequestProtocol.swift | 44 +++ GRDB/Fixit/GRDB-5.0.swift | 8 + .../Request/QueryInterfaceRequest.swift | 301 +++++++----------- .../SQLGeneration/SQLGenerationContext.swift | 15 +- .../SQLGeneration/SQLQueryGenerator.swift | 46 +-- .../SQLInterpolation+QueryInterface.swift | 247 +++++++++----- GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests/CompilationProtocolTests.swift | 8 - Tests/GRDBTests/FetchRequestTests.swift | 100 ++++-- Tests/GRDBTests/SQLLiteralTests.swift | 26 ++ 14 files changed, 581 insertions(+), 420 deletions(-) create mode 100644 GRDB/Core/SQLRequestProtocol.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 2d51c107c..c0809a480 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -799,6 +799,10 @@ 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; + 56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; }; + 56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; }; + 56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; }; + 56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; }; 56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; }; 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -1498,6 +1502,7 @@ 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = ""; }; 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; + 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; @@ -2158,6 +2163,7 @@ 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */, 56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */, 56FBFED82210731A00945324 /* SQLRequest.swift */, + 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */, 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, @@ -2808,6 +2814,7 @@ 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, + 56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2913,6 +2920,7 @@ 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */, 56A2FA3B24424F4700E97D23 /* Export.swift in Sources */, 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, @@ -3456,6 +3464,7 @@ AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */, 56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */, AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */, + 56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */, 56A2FA3D24424F4800E97D23 /* Export.swift in Sources */, AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, @@ -3792,6 +3801,7 @@ 5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294E223533F40006E219 /* EncodableRecord.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, + 56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */, 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index f52de9e6a..a972b5340 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,6 +1,7 @@ // MARK: - PreparedRequest /// A PreparedRequest is a request that is ready to be executed. +/// :nodoc: public struct PreparedRequest { /// A prepared statement public var statement: SelectStatement @@ -10,42 +11,18 @@ public struct PreparedRequest { /// Support for eager loading of hasMany associations. var supplementaryFetch: (([Row]) throws -> Void)? - - /// Creates a PreparedRequest. - /// - /// - parameter statement: A prepared statement that is ready to - /// be executed. - /// - parameter adapter: An eventual adapter for rows fetched by the - /// select statement. - public init( - statement: SelectStatement, - adapter: RowAdapter? = nil) - { - self.init(statement: statement, adapter: adapter, supplementaryFetch: nil) - } - - init( - statement: SelectStatement, - adapter: RowAdapter?, - supplementaryFetch: (([Row]) throws -> Void)?) - { - self.statement = statement - self.adapter = adapter - self.supplementaryFetch = supplementaryFetch - } } +extension PreparedRequest: Refinable { } + // MARK: - FetchRequest /// The protocol for all requests that fetch database rows, and tell how those /// rows should be interpreted. /// -/// struct Player: FetchableRecord { ... } -/// let request: ... // Some FetchRequest that fetches Player -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchOne(db) // Player? -public protocol FetchRequest: DatabaseRegionConvertible { +/// This protocol is "closed": you can not define custom types that conform +/// to it. +public protocol FetchRequest: SQLRequestProtocol, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder @@ -60,50 +37,66 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// Returns the number of rows fetched by the request. /// - /// The default implementation builds a naive SQL query based on the - /// statement returned by the `prepare` method: - /// `SELECT COUNT(*) FROM (...)`. - /// - /// Adopting types can refine this method in order to use more - /// efficient SQL. - /// /// - parameter db: A database connection. func fetchCount(_ db: Database) throws -> Int } extension FetchRequest { - - /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { - AdaptedFetchRequest(self, adapter) - } - /// Returns the number of rows fetched by the request. /// - /// This default implementation builds a naive SQL query based on the - /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. + /// The default implementation builds a naive SQL query based on the + /// statement returned by the `requestSQL(_:forSingleResult:)` method: + /// `SELECT COUNT(*) FROM (...)`. /// /// - parameter db: A database connection. public func fetchCount(_ db: Database) throws -> Int { - let request = try makePreparedRequest(db, forSingleResult: false) - let sql = "SELECT COUNT(*) FROM (\(request.statement.sql))" - return try Int.fetchOne(db, sql: sql, arguments: request.statement.arguments)! + let context = SQLGenerationContext(db) + let sql = try requestSQL(context, forSingleResult: false) + let countSQL = "SELECT COUNT(*) FROM (\(sql))" + return try Int.fetchOne(db, sql: countSQL, arguments: context.arguments)! } /// Returns the database region that the request looks into. /// /// This default implementation returns a region built from the statement - /// returned by the `prepare` method. + /// returned by the `requestSQL(_:forSingleResult)` method. /// /// - parameter db: A database connection. public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - let request = try makePreparedRequest(db, forSingleResult: false) - return request.statement.selectedRegion + let context = SQLGenerationContext(db) + let sql = try requestSQL(context, forSingleResult: false) + let statement = try db.makeSelectStatement(sql: sql) + return statement.selectedRegion + } + + /// Returns a PreparedRequest that is ready to be executed. + /// + /// This default implementation returns a request built from the + /// `requestSQL(_:forSingleResult)` method. + /// + /// - parameter db: A database connection. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use this to optimize the + /// prepared statement. + /// - returns: A prepared request. + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let context = SQLGenerationContext(db) + let sql = try requestSQL(context, forSingleResult: singleResult) + let statement = try db.makeSelectStatement(sql: sql) + statement.arguments = context.arguments + return PreparedRequest(statement: statement) } } // MARK: - AdaptedFetchRequest +extension FetchRequest { + /// Returns an adapted request. + public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + AdaptedFetchRequest(self, adapter) + } +} + /// An adapted request. public struct AdaptedFetchRequest: FetchRequest { public typealias RowDecoder = Base.RowDecoder @@ -118,6 +111,11 @@ public struct AdaptedFetchRequest: FetchRequest { self.adapter = adapter } + /// :nodoc: + public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try base.requestSQL(context, forSingleResult: singleResult) + } + /// :nodoc: public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { var request = try base.makePreparedRequest(db, forSingleResult: singleResult) @@ -147,15 +145,33 @@ public struct AdaptedFetchRequest: FetchRequest { /// An AnyFetchRequest forwards its operations to an underlying request, /// hiding its specifics. public struct AnyFetchRequest: FetchRequest { - private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest - private let _fetchCount: (Database) throws -> Int + // DatabaseRegionConvertible private let _databaseRegion: (Database) throws -> DatabaseRegion + // SQLRequestProtocol + private let _requestSQL: (SQLGenerationContext, _ singleResult: Bool) throws -> String + + // FetchRequest + private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest + private let _fetchCount: (Database) throws -> Int + + #warning("TODO: force same RowDecoder, and expose asRequest(of:)") /// Creates a request that wraps and forwards operations to `request`. public init(_ request: Request) { + _databaseRegion = request.databaseRegion + _requestSQL = request.requestSQL _preparedRequest = request.makePreparedRequest _fetchCount = request.fetchCount - _databaseRegion = request.databaseRegion + } + + /// :nodoc: + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + try _databaseRegion(db) + } + + /// :nodoc: + public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try _requestSQL(context, singleResult) } /// :nodoc: @@ -167,9 +183,4 @@ public struct AnyFetchRequest: FetchRequest { public func fetchCount(_ db: Database) throws -> Int { try _fetchCount(db) } - - /// :nodoc: - public func databaseRegion(_ db: Database) throws -> DatabaseRegion { - try _databaseRegion(db) - } } diff --git a/GRDB/Core/SQLLiteral.swift b/GRDB/Core/SQLLiteral.swift index 4adcbf54f..f389b27cf 100644 --- a/GRDB/Core/SQLLiteral.swift +++ b/GRDB/Core/SQLLiteral.swift @@ -14,7 +14,7 @@ public struct SQLLiteral { /// table aliases. enum Element { case sql(String, StatementArguments = StatementArguments()) - case subquery((SQLGenerationContext) throws -> String) + case subquery(SQLRequestProtocol) // Cases below can be qualified with a table alias case expression(SQLExpression) case selectable(SQLSelectable) @@ -29,8 +29,8 @@ public struct SQLLiteral { fatalError("Not implemented: turning an SQL parameter into an SQL literal value") } return sql - case let .subquery(function): - return try function(context) + case let .subquery(request): + return try request.requestSQL(context, forSingleResult: false) case let .expression(expression): return try expression.expressionSQL(context, wrappedInParenthesis: false) case let .selectable(selectable): diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 24792ced1..4f6004155 100644 --- a/GRDB/Core/SQLRequest.swift +++ b/GRDB/Core/SQLRequest.swift @@ -1,5 +1,5 @@ /// A FetchRequest built from raw SQL. -public struct SQLRequest: FetchRequest { +public struct SQLRequest { /// There are two statement caches: one "public" for statements generated by /// the user, and one "internal" for the statements generated by GRDB. Those /// are separated so that GRDB has no opportunity to inadvertently modify @@ -99,17 +99,25 @@ public struct SQLRequest: FetchRequest { self.adapter = adapter self.cache = cache } - - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - /// - /// - parameter db: A database connection. - /// - parameter singleResult: SQLRequest disregards this hint. - /// +} + +extension SQLRequest: SQLRequestProtocol { /// :nodoc: + public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try sqlLiteral.sql(context) + } +} + +extension SQLRequest: DatabaseRegionConvertible { + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + try makePreparedRequest(db, forSingleResult: false).statement.selectedRegion + } +} + +extension SQLRequest: FetchRequest { public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { let context = SQLGenerationContext(db) - let sql = try sqlLiteral.sql(context) + let sql = try requestSQL(context, forSingleResult: false) let statement: SelectStatement switch cache { case .none: @@ -124,37 +132,6 @@ public struct SQLRequest: FetchRequest { } } -// Support for `request.contains(expression)` -extension SQLRequest: SQLCollection { - /// :nodoc - public func collectionSQL(_ context: SQLGenerationContext) throws -> String { - try sqlLiteral.sql(context) - } - - /// :nodoc - public func qualifiedCollection(with alias: TableAlias) -> SQLCollection { - self - } -} - -// Support for `request == expression` -// -// Note: I wish we would give SQLExpression conformance to SQLRequest and -// QueryInterfaceRequest. -// -// But this does not play well with SQLInterpolation. Interpolation won't embed -// the request as a subquery, without wrapping parenthesis (in order to let the -// user perform unions). Instead, it insists on embedding it as an expression, -// wrapped in parenthesis (as support for `Column("score") = maxScoreRequest`). -// -// Maybe, when we master the Swift compiler a little more... -extension SQLRequest: SQLSpecificExpressible { - /// :nodoc - public var sqlExpression: SQLExpression { - sqlLiteral.sqlExpression - } -} - extension SQLRequest: ExpressibleByStringInterpolation { /// :nodoc public init(unicodeScalarLiteral: String) { diff --git a/GRDB/Core/SQLRequestProtocol.swift b/GRDB/Core/SQLRequestProtocol.swift new file mode 100644 index 000000000..aabe2c413 --- /dev/null +++ b/GRDB/Core/SQLRequestProtocol.swift @@ -0,0 +1,44 @@ +/// The protocol that can generate SQL requests and subqueries. +public protocol SQLRequestProtocol: SQLExpression, SQLCollection { + /// Returns the request SQL. + /// + /// - parameter context: An SQL generation context. + /// - parameter singleResult: A hint that a single result row will be + /// consumed. Implementations can optionally use this to optimize the + /// returned SQL. + /// - returns: An SQL string. + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String +} + +// MARK: - SQLExpression + +extension SQLRequestProtocol { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { + let sql = try requestSQL(context, forSingleResult: false) + return "(\(sql))" + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + self + } +} + +// MARK: - SQLCollection + +extension SQLRequestProtocol { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func collectionSQL(_ context: SQLGenerationContext) throws -> String { + try requestSQL(context, forSingleResult: false) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedCollection(with alias: TableAlias) -> SQLCollection { + self + } +} diff --git a/GRDB/Fixit/GRDB-5.0.swift b/GRDB/Fixit/GRDB-5.0.swift index cd11fd43c..68b9fe73a 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -137,6 +137,14 @@ extension FetchRequest where RowDecoder == Row { { preconditionFailure() } } +extension PreparedRequest { + @available(*, unavailable, message: "PreparedRequest initializer is no longer available.") + public init( + statement: SelectStatement, + adapter: RowAdapter? = nil) + { preconditionFailure() } +} + extension QueryInterfaceRequest { @available(*, unavailable, renamed: "RowDecoder") typealias T = RowDecoder diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 100525d00..949fc40a1 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -5,13 +5,13 @@ // // It wraps an SQLQuery, and has an attached type. // -// The attached type helps decoding raw database values: +// The attached RowDecoder type helps decoding raw database values: // // try dbQueue.read { db in // try playerRequest.fetchAll(db) // [Player] // } // -// The attached type also helps the compiler validate associated requests: +// RowDecoder also helps the compiler validate associated requests: // // playerRequest.including(required: Player.team) // OK // fruitRequest.including(required: Player.team) // Does not compile @@ -38,43 +38,11 @@ extension QueryInterfaceRequest { } } -extension QueryInterfaceRequest: FetchRequest { - /// Returns a tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - /// - /// - parameter db: A database connection. - /// - parameter singleResult: A hint as to whether the query should be optimized for a single result. - /// - returns: A prepared statement and an eventual row adapter. - /// :nodoc: - public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult) - let (statement, adapter) = try generator.prepare(db) - let associations = query.relation.prefetchedAssociations - if associations.isEmpty { - return PreparedRequest(statement: statement, adapter: adapter) - } else { - // Eager loading of prefetched associations - return PreparedRequest( - statement: statement, - adapter: adapter, - supplementaryFetch: { rows in - try prefetch(db, associations: associations, in: rows) - }) - } - } - - /// Returns the number of rows fetched by the request. - /// - /// - parameter db: A database connection. - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - try query.fetchCount(db) - } - - /// Returns the database region that the request looks into. - /// - /// - parameter db: A database connection. - /// :nodoc: +extension QueryInterfaceRequest: Refinable { } + +// MARK: - DatabaseRegionConvertible + +extension QueryInterfaceRequest: DatabaseRegionConvertible { public func databaseRegion(_ db: Database) throws -> DatabaseRegion { var region = try SQLQueryGenerator(query: query) .makeSelectStatement(db) @@ -116,9 +84,41 @@ extension QueryInterfaceRequest: FetchRequest { } } -extension QueryInterfaceRequest: SelectionRequest { - // MARK: Request Derivation +// MARK: - SQLRequestProtocol + +extension QueryInterfaceRequest: SQLRequestProtocol { + /// :nodoc: + public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult) + return try generator.requestSQL(context) + } +} + +// MARK: - FetchRequest + +extension QueryInterfaceRequest: FetchRequest { + public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult) + let preparedRequest = try generator.makePreparedRequest(db) + let associations = query.relation.prefetchedAssociations + if associations.isEmpty { + return preparedRequest + } else { + // Eager loading of prefetched associations + return preparedRequest.with(\.supplementaryFetch) { rows in + try prefetch(db, associations: associations, in: rows) + } + } + } + public func fetchCount(_ db: Database) throws -> Int { + try query.fetchCount(db) + } +} + +// MARK: - Request Derivation + +extension QueryInterfaceRequest: SelectionRequest { /// Creates a request which selects *selection promise*. /// /// // SELECT id, email FROM player @@ -228,8 +228,6 @@ extension QueryInterfaceRequest: SelectionRequest { } extension QueryInterfaceRequest: FilteredRequest { - // MARK: Request Derivation - /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// @@ -242,8 +240,6 @@ extension QueryInterfaceRequest: FilteredRequest { } extension QueryInterfaceRequest: OrderedRequest { - // MARK: Request Derivation - /// Creates a request with the provided *orderings promise*. /// /// // SELECT * FROM player ORDER BY name @@ -287,8 +283,6 @@ extension QueryInterfaceRequest: OrderedRequest { } extension QueryInterfaceRequest: AggregatingRequest { - // MARK: Request Derivation - /// Creates a request grouped according to *expressions promise*. public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest { map(\.query) { $0.group(expressions) } @@ -330,142 +324,6 @@ extension QueryInterfaceRequest: _JoinableRequest { extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { } -extension QueryInterfaceRequest: Refinable { - - // MARK: Request Derivation - - /// Creates a request which returns distinct rows. - /// - /// // SELECT DISTINCT * FROM player - /// var request = Player.all() - /// request = request.distinct() - /// - /// // SELECT DISTINCT name FROM player - /// var request = Player.select(Column("name")) - /// request = request.distinct() - public func distinct() -> QueryInterfaceRequest { - map(\.query) { $0.distinct() } - } - - /// Creates a request which fetches *limit* rows, starting at *offset*. - /// - /// // SELECT * FROM player LIMIT 1 - /// var request = Player.all() - /// request = request.limit(1) - /// - /// Any previous limit is replaced. - public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - map(\.query) { $0.limit(limit, offset: offset) } - } - - /// Creates a request that allows you to define expressions that target - /// a specific database table. - /// - /// In the example below, the "team.avgScore < player.score" condition in - /// the ON clause could be not achieved without table aliases. - /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) - /// } - /// - /// // SELECT player.*, team.* - /// // JOIN team ON ... AND team.avgScore < player.score - /// let playerAlias = TableAlias() - /// let request = Player - /// .all() - /// .aliased(playerAlias) - /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) - public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - map(\.query) { $0.qualified(with: alias) } - } - - /// Creates a request bound to type Target. - /// - /// The returned request can fetch if the type Target is fetchable (Row, - /// value, record). - /// - /// // Int? - /// let maxScore = try Player - /// .select(max(scoreColumn)) - /// .asRequest(of: Int.self) // <-- - /// .fetchOne(db) - /// - /// - parameter type: The fetched type Target - /// - returns: A typed request bound to type Target. - public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { - QueryInterfaceRequest(query: query) - } -} - -// Support for `request.contains(expression)` -extension QueryInterfaceRequest: SQLCollection { - /// :nodoc - public func collectionSQL(_ context: SQLGenerationContext) throws -> String { - // If the request selects several colums, SQLite 3.28.0 may complain - // with an error: - // - // -- Error: sub-select returns 2 columns - expected 1 - // SELECT * FROM t WHERE a IN (SELECT a, b FROM t); - // - // But other requests accept multiple columns: - // - // -- OK - // SELECT * FROM t WHERE (a, b) IN (SELECT a, b FROM t); - // - // So we do not prevent using requests that select several columns - // as expressions. - try SQLQueryGenerator(query: query).sql(context) - } - - /// :nodoc - public func qualifiedCollection(with alias: TableAlias) -> SQLCollection { - self - } -} - -// Support for `request == expression` -// -// Note: I wish we would give SQLExpression conformance to -// QueryInterfaceRequest. See SQLRequest for more information. -extension QueryInterfaceRequest: SQLSpecificExpressible { - private struct Expression: SQLExpression { - let generator: SQLQueryGenerator - - func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { - try "(" + generator.sql(context) + ")" - } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - self - } - } - - /// :nodoc - public var sqlExpression: SQLExpression { - // We're generating an *expression*, so we have to deal with the fact - // that the request may return several rows, and select several columns. - // - // In practice, SQLite only considers the first returned row. - // So we don't have to set the `forSingleResult` flag of the generator - // in order to make sure a single row is returned. - // - // And if the request selects several colums, SQLite 3.28.0 may complain - // with a "row value misused" error: - // - // -- Error: row value misused - // SELECT * FROM t WHERE a = (SELECT a, b FROM t); - // - // But other requests accept multiple columns: - // - // -- OK - // SELECT * FROM t WHERE (a, b) = (SELECT a, b FROM t); - // - // So we do not prevent using requests that select several columns - // as expressions. - Expression(generator: SQLQueryGenerator(query: query)) - } -} - extension QueryInterfaceRequest: TableRequest { /// :nodoc: public var databaseTableName: String { @@ -491,14 +349,77 @@ extension QueryInterfaceRequest: TableRequest { fatalError("Request is not based on a database table") } } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + map(\.query) { $0.qualified(with: alias) } + } } extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { } +extension QueryInterfaceRequest { + /// Creates a request which returns distinct rows. + /// + /// // SELECT DISTINCT * FROM player + /// var request = Player.all() + /// request = request.distinct() + /// + /// // SELECT DISTINCT name FROM player + /// var request = Player.select(Column("name")) + /// request = request.distinct() + public func distinct() -> QueryInterfaceRequest { + map(\.query) { $0.distinct() } + } + + /// Creates a request which fetches *limit* rows, starting at *offset*. + /// + /// // SELECT * FROM player LIMIT 1 + /// var request = Player.all() + /// request = request.limit(1) + /// + /// Any previous limit is replaced. + public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { + map(\.query) { $0.limit(limit, offset: offset) } + } + + /// Creates a request bound to type Target. + /// + /// The returned request can fetch if the type Target is fetchable (Row, + /// value, record). + /// + /// // Int? + /// let maxScore = try Player + /// .select(max(scoreColumn)) + /// .asRequest(of: Int.self) // <-- + /// .fetchOne(db) + /// + /// - parameter type: The fetched type Target + /// - returns: A typed request bound to type Target. + public func asRequest(of type: RowDecoder.Type) -> QueryInterfaceRequest { + QueryInterfaceRequest(query: query) + } +} + +// MARK: - Batch Delete + extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { - - // MARK: Batch Delete - /// Deletes matching rows; returns the number of deleted rows. /// /// - parameter db: A database connection. @@ -509,9 +430,11 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute() return db.changesCount } - - // MARK: Batch Update - +} + +// MARK: - Batch Update + +extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { /// Updates matching rows; returns the number of updated rows. /// /// For example: diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index e30c82bac..f529944cb 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -1,15 +1,14 @@ /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// SQLGenerationContext support for SQL generation: +/// SQLGenerationContext supports SQL generation: /// -/// - It provides a database connection so that request elements can perform -/// database introspection in order to build their SQL representation. +/// - It provides a database connection during SQL generation, for any purpose +/// such as schema introspection. /// /// - It provides unique table aliases in order to disambiguates table names /// and columns. /// -/// - Request elements can turn database values as SQLite statement arguments, -/// in order to prevent SQL injection. +/// - It gathers SQL arguments in order to prevent SQL injection. /// /// :nodoc: public final class SQLGenerationContext { @@ -75,7 +74,9 @@ public final class SQLGenerationContext { } /// Returns whether arguments could be appended. - /// May be false for SQLGenerationContext.rawSQLContext + /// + /// A false result means that the generation context does not support + /// SQL arguments. func append(arguments: StatementArguments) -> Bool { argumentsSink.append(arguments: arguments) } @@ -144,7 +145,7 @@ class StatementArgumentsSink { // fileprivate so that SQLGenerationContext.append(arguments:) is the only // available api. - /// Returns whether arguments could be appended. + /// Returns false for SQLGenerationContext.rawSQLContext fileprivate func append(arguments: StatementArguments) -> Bool { if arguments.isEmpty { return true diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index f6355aad7..fd5e94076 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -59,11 +59,11 @@ struct SQLQueryGenerator: Refinable { self.singleResult = singleResult } - func sql(_ parentContext: SQLGenerationContext) throws -> String { + func requestSQL(_ context: SQLGenerationContext) throws -> String { // 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. - let context = SQLGenerationContext(parent: parentContext, aliases: relation.allAliases) + let context = SQLGenerationContext(parent: context, aliases: relation.allAliases) var sql = "SELECT" @@ -137,8 +137,25 @@ struct SQLQueryGenerator: Refinable { return sql } - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - try (makeSelectStatement(db), rowAdapter(db)) + func makePreparedRequest(_ db: Database) throws -> PreparedRequest { + try PreparedRequest( + statement: makeSelectStatement(db), + adapter: rowAdapter(db)) + } + + /// Returns a select statement + func makeSelectStatement(_ db: Database) throws -> SelectStatement { + // Build + let context = SQLGenerationContext(db) + let sql = try requestSQL(context) + + // Compile & set arguments + let statement = try db.makeSelectStatement(sql: sql) + statement.arguments = context.arguments + + // Optimize databaseRegion + statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion) + return statement } private func optimizedSelectedRegion(_ db: Database, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion { @@ -321,7 +338,7 @@ struct SQLQueryGenerator: Refinable { var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE " sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(context) + sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -439,7 +456,7 @@ struct SQLQueryGenerator: Refinable { sql += " WHERE " sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false) sql += " IN (" - sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(context) + sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context) sql += ")" let statement = try db.makeUpdateStatement(sql: sql) @@ -447,21 +464,6 @@ struct SQLQueryGenerator: Refinable { return statement } - /// Returns a select statement - func makeSelectStatement(_ db: Database) throws -> SelectStatement { - // Build - let context = SQLGenerationContext(db) - let sql = try self.sql(context) - - // Compile & set arguments - let statement = try db.makeSelectStatement(sql: sql) - statement.arguments = context.arguments - - // Optimize databaseRegion - statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion) - return statement - } - /// Informs about the query grouping private enum GroupingInfo { /// No grouping at all: SELECT ... FROM player @@ -757,7 +759,7 @@ private enum SQLQualifiedSource { return "\(tableName.quotedDatabaseIdentifier)" } case let .subquery(generator): - let sql = try generator.sql(context) + let sql = try generator.requestSQL(context) return "(\(sql))" } } diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index dc047f906..868b75eab 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -1,10 +1,24 @@ /// :nodoc: extension SQLInterpolation { + + // MARK: - TableRecord + /// Appends the table name of the record type. /// /// // SELECT * FROM player /// let request: SQLRequest = "SELECT * FROM \(Player.self)" - public mutating func appendInterpolation(_ table: T.Type) { + public mutating func appendInterpolation(_ table: T.Type) + where T: TableRecord + { + appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) + } + + /// Appends the table name of the record type. + /// + /// // SELECT * FROM player + /// let request: SQLRequest = "SELECT * FROM \(Player.self)" + @_disfavoredOverload + public mutating func appendInterpolation(_ table: TableRecord.Type) { appendLiteral(table.databaseTableName.quotedDatabaseIdentifier) } @@ -13,7 +27,19 @@ extension SQLInterpolation { /// // INSERT INTO player ... /// let player: Player = ... /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." - public mutating func appendInterpolation(tableOf record: T) { + public mutating func appendInterpolation(tableOf record: T) + where T: TableRecord + { + appendInterpolation(type(of: record)) + } + + /// Appends the table name of the record. + /// + /// // INSERT INTO player ... + /// let player: Player = ... + /// let request: SQLRequest = "INSERT INTO \(tableOf: player) ..." + @_disfavoredOverload + public mutating func appendInterpolation(tableOf record: TableRecord) { appendInterpolation(type(of: record)) } @@ -26,61 +52,102 @@ extension SQLInterpolation { /// // SELECT p.* FROM player p /// let player: Player = ... /// let request: SQLRequest = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p" - public mutating func appendInterpolation(columnsOf record: T.Type, tableAlias: String? = nil) { + public mutating func appendInterpolation(columnsOf record: T.Type, tableAlias: String? = nil) + where T: TableRecord + { let alias = TableAlias(name: tableAlias ?? T.databaseTableName) elements.append(contentsOf: T.databaseSelection .map { CollectionOfOne(.selectable($0.qualifiedSelectable(with: alias))) } .joined(separator: CollectionOfOne(.sql(", ")))) } + // MARK: - SQLSelectable + /// Appends the selectable SQL. /// /// // SELECT * FROM player /// let request: SQLRequest = """ /// SELECT \(AllColumns()) FROM player /// """ - public mutating func appendInterpolation(_ selection: SQLSelectable) { + public mutating func appendInterpolation(_ selection: T) + where T: SQLSelectable + { elements.append(.selectable(selection)) } + /// Appends the selectable SQL, or NULL if it is nil. + /// + /// // SELECT * FROM player + /// let request: SQLRequest = """ + /// SELECT \(AllColumns()) FROM player + /// """ + @_disfavoredOverload + public mutating func appendInterpolation(_ selection: SQLSelectable?) { + if let selection = selection { + elements.append(.selectable(selection)) + } else { + appendLiteral("NULL") + } + } + + // MARK: - SQLOrderingTerm + + /// Appends the ordering SQL. + /// + /// // SELECT name FROM player ORDER BY name DESC + /// let request: SQLRequest = """ + /// SELECT * FROM player ORDER BY \(Column("name").desc) + /// """ + public mutating func appendInterpolation(_ orderingTerm: T) + where T: SQLOrderingTerm + { + elements.append(.orderingTerm(orderingTerm)) + } + + /// Appends the ordering SQL. + /// + /// // SELECT name FROM player ORDER BY name DESC + /// let request: SQLRequest = """ + /// SELECT * FROM player ORDER BY \(Column("name").desc) + /// """ + @_disfavoredOverload + public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) { + elements.append(.orderingTerm(orderingTerm)) + } + + // MARK: - SQLExpressible + + /// Appends the expression SQL. + /// + /// // SELECT name FROM player + /// let request: SQLRequest = """ + /// SELECT \(Column("name")) FROM player + /// """ + public mutating func appendInterpolation(_ expressible: T) + where T: SQLExpressible + { + elements.append(.expression(expressible.sqlExpression)) + } + /// Appends the expression SQL. /// /// // SELECT name FROM player /// let request: SQLRequest = """ /// SELECT \(Column("name")) FROM player /// """ - public mutating func appendInterpolation(_ expressible: SQLExpressible & SQLSelectable & SQLOrderingTerm) { - elements.append(.expression(expressible.sqlExpression)) - } - - /// Appends the name of the coding key. - /// - /// // SELECT name FROM player - /// let request: SQLRequest = " - /// SELECT \(CodingKey.name) FROM player - /// """ - public mutating func appendInterpolation( - _ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey) + public mutating func appendInterpolation(_ expressible: T) + where T: SQLExpressible & SQLSelectable & SQLOrderingTerm { - elements.append(.expression(codingKey.sqlExpression)) + elements.append(.expression(expressible.sqlExpression)) } /// Appends the expression SQL, or NULL if it is nil. /// - /// // SELECT score + ? FROM player - /// let bonus = 1000 - /// let request: SQLRequest = """ - /// SELECT score + \(bonus) FROM player + /// // SELECT name FROM player + /// let request: SQLRequest = """ + /// SELECT \(Column("name")) FROM player /// """ - /// - /// You can also derive literal expressions from other expressions: - /// - /// func date(_ value: SQLExpressible) -> SQLExpression { - /// SQLLiteral("DATE(\(value))").sqlExpression - /// } - /// - /// // SELECT * FROM player WHERE DATE(createdAt) = '2020-02-25' - /// let request = Player.filter(date(Column("createdAt")) == "2020-02-25") + @_disfavoredOverload public mutating func appendInterpolation(_ expressible: SQLExpressible?) { if let expressible = expressible { elements.append(.expression(expressible.sqlExpression)) @@ -89,25 +156,78 @@ extension SQLInterpolation { } } + // MARK: - CodingKey + /// Appends the name of the coding key. /// /// // SELECT name FROM player - /// let request: SQLRequest = """ + /// let request: SQLRequest = " /// SELECT \(CodingKey.name) FROM player /// """ - public mutating func appendInterpolation(_ codingKey: CodingKey) { - appendInterpolation(Column(codingKey.stringValue)) + public mutating func appendInterpolation(_ key: T) + where T: CodingKey + { + appendInterpolation(Column(key.stringValue)) } - // When a value is both an expression and a sequence of expressions, - // favor the expression side. Use case: Foundation.Data interpolation. - /// :nodoc: - public mutating func appendInterpolation(_ expressible: T) - where T: Sequence, T.Element: SQLExpressible, T: SQLExpressible + /// Appends the name of the coding key. + /// + /// // SELECT name FROM player + /// let request: SQLRequest = " + /// SELECT \(CodingKey.name) FROM player + /// """ + public mutating func appendInterpolation(_ key: T) + where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm { - elements.append(.expression(expressible.sqlExpression)) + appendInterpolation(Column(key.stringValue)) } - + + /// Appends the name of the coding key. + /// + /// // SELECT name FROM player + /// let request: SQLRequest = " + /// SELECT \(CodingKey.name) FROM player + /// """ + @_disfavoredOverload + public mutating func appendInterpolation(_ key: CodingKey) { + appendInterpolation(Column(key.stringValue)) + } + + // MARK: - SQLRequestProtocol + + /// Appends the request SQL (not wrapped inside parentheses). + /// + /// let subquery = Player.select(max(Column("score"))) + /// // or + /// let subQuery: SQLRequest = "SELECT MAX(score) FROM player" + /// + /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE score = (\(subquery)) + /// """ + public mutating func appendInterpolation(_ request: T) + where T: SQLRequestProtocol + { + elements.append(.subquery(request)) + } + + /// Appends the request SQL (not wrapped inside parentheses). + /// + /// let subquery = Player.select(max(Column("score"))) + /// // or + /// let subQuery: SQLRequest = "SELECT MAX(score) FROM player" + /// + /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) + /// let request: SQLRequest = """ + /// SELECT * FROM player WHERE score = (\(subquery)) + /// """ + @_disfavoredOverload + public mutating func appendInterpolation(_ request: SQLRequestProtocol) { + elements.append(.subquery(request)) + } + + // MARK: - Sequence + /// Appends a sequence of expressions, wrapped in parentheses. /// /// // SELECT * FROM player WHERE id IN (?,?,?) @@ -123,7 +243,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE id IN \(ids) /// """ - public mutating func appendInterpolation(_ sequence: S) where S: Sequence, S.Element: SQLExpressible { + public mutating func appendInterpolation(_ sequence: T) + where T: Sequence, T.Element: SQLExpressible + { appendInterpolation(sequence.lazy.map(\.sqlExpression)) } @@ -142,7 +264,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE a IN \(expressions) /// """ - public mutating func appendInterpolation(_ sequence: S) where S: Sequence, S.Element == SQLExpression { + public mutating func appendInterpolation(_ sequence: T) + where T: Sequence, T.Element == SQLExpression + { let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) } if e.isEmpty { appendLiteral("(SELECT NULL WHERE NULL)") @@ -153,37 +277,12 @@ extension SQLInterpolation { } } - /// Appends the ordering SQL. - /// - /// // SELECT name FROM player ORDER BY name DESC - /// let request: SQLRequest = """ - /// SELECT * FROM player ORDER BY \(Column("name").desc) - /// """ - public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) { - elements.append(.orderingTerm(ordering)) - } - - /// Appends the request SQL (not wrapped inside parentheses). - /// - /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) - /// let subQuery: SQLRequest = "SELECT MAX(score) FROM player" - /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE score = (\(subQuery)) - /// """ - public mutating func appendInterpolation(_ request: SQLRequest) { - elements.append(.subquery(request.sqlLiteral.sql)) - } - - /// Appends the request SQL (not wrapped inside parentheses). - /// - /// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player) - /// let subQuery = Player.select(max(Column("score"))) - /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE score = (\(subQuery)) - /// """ - public mutating func appendInterpolation(_ request: QueryInterfaceRequest) { - elements.append(.subquery { context in - try SQLQueryGenerator(query: request.query).sql(context) - }) + // When a value is both an expression and a sequence of expressions, + // favor the expression side. Use case: Foundation.Data interpolation. + /// :nodoc: + public mutating func appendInterpolation(_ expressible: T) + where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible + { + elements.append(.expression(expressible.sqlExpression)) } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index f9d81cb67..663c45e4c 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -466,6 +466,8 @@ 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; + 56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; }; + 56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; @@ -1034,6 +1036,7 @@ 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = ""; }; 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; + 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; @@ -1666,6 +1669,7 @@ 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */, 56E9FAD42210538400C703A8 /* SQLLiteral.swift */, 56FBFED52210731000945324 /* SQLRequest.swift */, + 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */, 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, @@ -2194,6 +2198,7 @@ 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */, + 56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */, 56A2FA3A24424F4200E97D23 /* Export.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, @@ -2530,6 +2535,7 @@ 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */, + 56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */, 56A2FA3924424F4200E97D23 /* Export.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index a1d19d0eb..45166302f 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -101,14 +101,6 @@ private class UserPersistableRecord2 : PersistableRecord { func encode(to container: inout PersistenceContainer) { } } -// MARK: - FetchRequest - -private struct UserRowRequest : FetchRequest { - struct CustomType { } - typealias RowDecoder = CustomType - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { preconditionFailure() } -} - // MARK: - FetchableRecord private struct UserFetchableRecord1 : FetchableRecord { diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index 02cc4f246..bfb535f74 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -4,10 +4,10 @@ import GRDB class FetchRequestTests: GRDBTestCase { func testRequestFetchRows() throws { - struct CustomRequest : FetchRequest { + struct CustomRequest: FetchRequest { typealias RowDecoder = Row - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT * FROM table1" } } @@ -31,8 +31,8 @@ class FetchRequestTests: GRDBTestCase { func testRequestFetchValues() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Int - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT id FROM table1" } } @@ -59,8 +59,8 @@ class FetchRequestTests: GRDBTestCase { } struct CustomRequest : FetchRequest { typealias RowDecoder = CustomRecord - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT id FROM table1")) + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT id FROM table1" } } @@ -84,8 +84,8 @@ class FetchRequestTests: GRDBTestCase { func testRequestFetchCount() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM table1")) + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT * FROM table1" } } @@ -107,10 +107,10 @@ class FetchRequestTests: GRDBTestCase { func testRequestCustomizedFetchCount() throws { struct CustomRequest : FetchRequest { typealias RowDecoder = Row - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { - try PreparedRequest(statement: db.makeSelectStatement(sql: "INVALID")) + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "INVALID" } - + func fetchCount(_ db: Database) throws -> Int { 2 } } @@ -134,11 +134,11 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHint() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = T - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { if singleResult { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'single' AS hint")) + return "SELECT 'single' AS hint" } else { - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple' AS hint")) + return "SELECT 'multiple' AS hint" } } } @@ -336,9 +336,9 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHintIsNotUsedForDefaultFetchCount() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Void - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { if singleResult { fatalError("not implemented") } - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT 'multiple'")) + return "SELECT 'multiple'" } } @@ -353,9 +353,9 @@ class FetchRequestTests: GRDBTestCase { func testSingleResultHintIsNotUsedForDefaultDatabaseRegion() throws { struct CustomRequest: FetchRequest { typealias RowDecoder = Void - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { if singleResult { fatalError("not implemented") } - return try PreparedRequest(statement: db.makeSelectStatement(sql: "SELECT * FROM multiple")) + return "SELECT * FROM multiple" } } @@ -368,4 +368,66 @@ class FetchRequestTests: GRDBTestCase { XCTAssertEqual(region.description, "multiple(a)") } } + + func testRequestAsSQLExpression() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT id FROM table1" + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + + let derivedExpression = CustomRequest() > 0 + let sqlRequest: SQLRequest = "SELECT \(derivedExpression)" + let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement + XCTAssertEqual(statement.sql, "SELECT (SELECT id FROM table1) > ?") + } + } + + func testRequestAsSQLCollection() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT id FROM table1" + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + + let derivedExpression = CustomRequest().contains(0) + let sqlRequest: SQLRequest = "SELECT \(derivedExpression)" + let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement + XCTAssertEqual(statement.sql, "SELECT ? IN (SELECT id FROM table1)") + } + } + + func testRequestInterpolation() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + "SELECT id FROM table1" + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + + let sqlRequest: SQLRequest = "SELECT * FROM (\(CustomRequest()))" + let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement + XCTAssertEqual(statement.sql, "SELECT * FROM (SELECT id FROM table1)") + } + } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index 02f1fdce1..8ad00c00d 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -231,6 +231,18 @@ extension SQLLiteralTests { """) XCTAssert(arguments.isEmpty) } + do { + // Existential + let query: SQLLiteral = """ + SELECT \(nil as SQLSelectable?) + """ + + let (sql, arguments) = try query.build(db) + XCTAssertEqual(sql, """ + SELECT NULL + """) + XCTAssert(arguments.isEmpty) + } } } @@ -238,6 +250,7 @@ extension SQLLiteralTests { try makeDatabaseQueue().inDatabase { db in struct Player: TableRecord { } do { + // Non-existential let query: SQLLiteral = """ SELECT * FROM \(Player.self) @@ -251,6 +264,7 @@ extension SQLLiteralTests { XCTAssert(arguments.isEmpty) } do { + // Non-existential let query: SQLLiteral = """ INSERT INTO \(tableOf: Player()) DEFAULT VALUES """ @@ -261,6 +275,18 @@ extension SQLLiteralTests { """) XCTAssert(arguments.isEmpty) } + do { + // Existential + let query: SQLLiteral = """ + INSERT INTO \(tableOf: Player() as TableRecord) DEFAULT VALUES + """ + + let (sql, arguments) = try query.build(db) + XCTAssertEqual(sql, """ + INSERT INTO "player" DEFAULT VALUES + """) + XCTAssert(arguments.isEmpty) + } } }