diff --git a/CHANGELOG.md b/CHANGELOG.md index caa4f3eaf..61805f300 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -81,6 +81,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - [#772](https://github.com/groue/GRDB.swift/pull/772): Update the Database Sharing Guide with mention of the persistent WAL mode +### Breaking Changes + +- [#774](https://github.com/groue/GRDB.swift/pull/774): All requests are usable as SQL expressions and collections + ### Fixed - [#773](https://github.com/groue/GRDB.swift/pull/773): Allow subqueries to refer to outer tables diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index d4c148946..57781fe3a 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -334,15 +334,8 @@ The changes can quite impact your application. We'll describe them below, as wel print(sql) // prints "UPDATE player SET name = ? WHERE id = ?" print(arguments) // prints ["O'Brien", 42] ``` - - > :question: This change makes it possible to embed query interface requests as subqueries inside SQLLiteral: - > - > ```swift - > let maximumScore = Player.select(max(Column("score"))) - > let query: SQLLiteral = "SELECT * FROM player WHERE score = (\(maximumScore))" - > ``` -4. In order to extract raw SQL string from a request (SQLRequest or QueryInterfaceRequest), you now need a database connection: +4. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method: ```swift // BEFORE: GRDB 4 @@ -356,18 +349,11 @@ The changes can quite impact your application. We'll describe them below, as wel // NEW: GRDB 5 try dbQueue.read { db in let request = Player.filter(Column("name") == "O'Brien") - let statement = try request.makePreparedRequest(db).statement + let statement = try request.makePreparedRequest(db, forSingleResult: false).statement print(statement.sql) // "SELECT * FROM player WHERE name = ?" print(statement.arguments) // ["O'Brien"] } ``` - - > :question: This change makes it possible to embed query interface requests as subqueries inside SQLRequest: - > - > ```swift - > let maximumScore = Player.select(max(Column("score"))) - > let request: SQLRequest = "SELECT * FROM player WHERE score = (\(maximumScore))" - > ``` 5. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]: @@ -391,28 +377,12 @@ The changes can quite impact your application. We'll describe them below, as wel Player.select(myFunction(Column("name"))) ``` -7. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method: +7. Defining custom `FetchRequest` types is now **discouraged**. + + A future GRDB version will remove the ability to define custom `FetchRequest` types. + + Our suggestion is to refactor your app so that your custom request type is no longer needed: [SQLRequest] and [QueryInterfaceRequest] are now supposed to fully address your needs. If it is not possible, then please [open an issue](https://github.com/groue/GRDB.swift/issues) and describe your particular use case. - ```swift - // BEFORE: GRDB 4 - struct MyRequest: FetchRequest { - func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) { - let statement: SelectStatement = ... - let adapter: RowAdapter? = ... - return (statement, adapter) - } - } - - // NEW: GRDB 5 - struct MyRequest: FetchRequest { - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest - let statement: SelectStatement = ... - let adapter: RowAdapter? = ... - return PreparedRequest(statement: statement, adapter: adapter) - } - } - ``` - 8. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`: ```swift @@ -448,3 +418,5 @@ The changes can quite impact your application. We'll describe them below, as wel [Batch updates]: ../README.md#update-requests [SQL Interpolation]: SQLInterpolation.md [SQLLiteral]: SQLInterpolation.md#sqlliteral +[SQLRequest]: ../README.md#custom-requests +[QueryInterfaceRequest]: ../README.md#requests 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/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 24f9be5da..be75a9d98 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -6,9 +6,9 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?") - /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! - /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! + /// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?") + /// let player1 = try Player.fetchOne(statement, arguments: [1])! + /// let player2 = try Player.fetchOne(statement, arguments: [2])! /// /// - parameter sql: An SQL query. /// - returns: A SelectStatement. @@ -17,6 +17,24 @@ extension Database { try makeSelectStatement(sql: sql, prepFlags: 0) } + // TODO: remove when FetchRequest is a closed protocol. + /// Returns a new prepared statement. + /// + /// let id = 1 + /// let literal: SQLLiteral = "SELECT * FROM player WHERE id = \(id)" + /// let statement = try db.makeSelectStatement(literal: literal) + /// let player = try Player.fetchOne(statement)! + /// + /// - parameter sql: An SQL query. + /// - returns: A SelectStatement. + /// - throws: A DatabaseError whenever SQLite could not parse the sql query. + public func makeSelectStatement(literal: SQLLiteral) throws -> SelectStatement { + let (sql, arguments) = try literal.build(self) + let statement = try makeSelectStatement(sql: sql, prepFlags: 0) + statement.arguments = arguments + return statement + } + /// Returns a new prepared statement that can be reused. /// /// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index f52de9e6a..db259452e 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -11,6 +11,7 @@ public struct PreparedRequest { /// Support for eager loading of hasMany associations. var supplementaryFetch: (([Row]) throws -> Void)? + // TODO: remove when FetchRequest is a closed protocol. /// Creates a PreparedRequest. /// /// - parameter statement: A prepared statement that is ready to @@ -33,8 +34,21 @@ public struct PreparedRequest { self.adapter = adapter self.supplementaryFetch = supplementaryFetch } + + // TODO: remove when FetchRequest is a closed protocol. + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns the request SQL. + /// + /// - parameter context: An SQL generation context. + /// - returns: An SQL string. + public func requestSQL(_ context: SQLGenerationContext) throws -> String { + try SQLLiteral(sql: statement.sql, arguments: statement.arguments).sql(context) + } } +extension PreparedRequest: Refinable { } + // MARK: - FetchRequest /// The protocol for all requests that fetch database rows, and tell how those @@ -45,7 +59,27 @@ public struct PreparedRequest { /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] /// try request.fetchOne(db) // Player? -public protocol FetchRequest: DatabaseRegionConvertible { +/// try request.fetchCount(db) // Int +/// +/// To build a custom FetchRequest, declare a type with the `RowDecoder` +/// associated type, and implement the `requestSQL(_:forSingleResult:)` method +/// with the help of SQLLiteral. +/// +/// For example: +/// +/// struct PlayerRequest: FetchRequest { +/// typealias RowDecoder = Player +/// var id: Int64 +/// func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { +/// let query: SQLLiteral = "SELECT * FROM player WHERE id = \(id)" +/// return try query.sql(context) +/// } +/// } +/// +/// let player = try dbQueue.read { db in +/// try PlayerRequest(id: 42).fetchOne(db) +/// } +public protocol FetchRequest: SQLRequestProtocol, DatabaseRegionConvertible { /// The type that tells how fetched database rows should be interpreted. associatedtype RowDecoder @@ -53,57 +87,79 @@ public protocol FetchRequest: DatabaseRegionConvertible { /// /// - 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. + /// consumed. Implementations can optionally use it to optimize the + /// prepared statement, for example by adding a `LIMIT 1` SQL clause. + /// + /// // Calls makePreparedRequest(db, forSingleResult: true) + /// try request.fetchOne(db) + /// + /// // Calls makePreparedRequest(db, forSingleResult: false) + /// try request.fetchAll(db) /// - returns: A prepared request. func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest /// 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 +174,12 @@ public struct AdaptedFetchRequest: FetchRequest { self.adapter = adapter } + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :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 +209,34 @@ 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) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try _requestSQL(context, singleResult) } /// :nodoc: @@ -167,9 +248,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..97f923c9f 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): @@ -98,7 +98,11 @@ public struct SQLLiteral { return (sql: sql, arguments: context.arguments) } - func sql(_ context: SQLGenerationContext) throws -> String { + // TODO: make internal when FetchRequest is a closed protocol. + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns the literal SQL string given an SQL generation context. + public func sql(_ context: SQLGenerationContext) throws -> String { try elements.map { try $0.sql(context) }.joined() } @@ -231,8 +235,6 @@ extension SQLLiteral: ExpressibleByStringInterpolation { // MARK: - _SQLExpressionLiteral -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// /// SQLExpressionLiteral is an expression built from a raw SQL snippet. /// /// SQLExpressionLiteral(sql: "1 + 2") @@ -249,8 +251,6 @@ private struct _SQLExpressionLiteral: SQLExpression { self.sqlLiteral = sqlLiteral } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String { if wrappedInParenthesis { return try "(\(expressionSQL(context, wrappedInParenthesis: false)))" @@ -258,8 +258,6 @@ private struct _SQLExpressionLiteral: SQLExpression { return try sqlLiteral.sql(context) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: func qualifiedExpression(with alias: TableAlias) -> SQLExpression { sqlLiteral.qualified(with: alias).sqlExpression } diff --git a/GRDB/Core/SQLRequest.swift b/GRDB/Core/SQLRequest.swift index 24792ced1..0fdf988f0 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,14 +99,23 @@ 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 { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :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) @@ -124,37 +133,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..edaa9d290 --- /dev/null +++ b/GRDB/Core/SQLRequestProtocol.swift @@ -0,0 +1,46 @@ +/// The protocol that can generate SQL requests and subqueries. +public protocol SQLRequestProtocol: SQLExpression, SQLCollection { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// 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 it to optimize the + /// generated SQL, for example by adding a `LIMIT 1` SQL clause. + /// - 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..b61de20ee 100644 --- a/GRDB/Fixit/GRDB-5.0.swift +++ b/GRDB/Fixit/GRDB-5.0.swift @@ -200,10 +200,10 @@ extension SQLRequest { where Request: FetchRequest, Request.RowDecoder == RowDecoder { preconditionFailure() } - @available(*, unavailable, message: "Use makePreparedRequest(db).statement.sql instead") + @available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.sql instead") public var sql: String { preconditionFailure() } - @available(*, unavailable, message: "Use makePreparedRequest(db).statement.arguments instead") + @available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.arguments instead") public var arguments: StatementArguments { preconditionFailure() } } diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 100525d00..8b52ac2d2 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,42 @@ extension QueryInterfaceRequest: FetchRequest { } } -extension QueryInterfaceRequest: SelectionRequest { - // MARK: Request Derivation +// MARK: - SQLRequestProtocol + +extension QueryInterfaceRequest: SQLRequestProtocol { + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :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 +229,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 +241,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 +284,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 +325,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 +350,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 +431,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..18f8e303b 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 { @@ -18,9 +17,9 @@ public final class SQLGenerationContext { case context(SQLGenerationContext) } - /// A database connection so that request elements can perform database - /// introspection in order to build their SQL representation. - var db: Database { + // TODO: make internal when FetchRequest is a closed protocol. + /// A database connection. + public var db: Database { switch parent { case let .none(db: db, argumentsSink: _): return db case let .context(context): return context.db @@ -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/README.md b/README.md index b5ae73dcf..6bb5952ac 100644 --- a/README.md +++ b/README.md @@ -4780,48 +4780,7 @@ But you may prefer to bring some elegance back in, and build custom requests: try Player.customRequest().fetchAll(db) // [Player] ``` -- [FetchRequest Protocol](#fetchrequest-protocol) -- [Building Custom Requests](#building-custom-requests) -- [Fetching From Custom Requests](#fetching-from-custom-requests) - - -### FetchRequest Protocol - -**FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted: - -```swift -protocol FetchRequest: DatabaseRegionConvertible { - /// The type that tells how fetched rows should be decoded - associatedtype RowDecoder - - /// Returns a PreparedRequest made of a prepared statement that is ready to - /// be executed, and an eventual row adapter. - func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest - - /// The number of rows fetched by the request. - func fetchCount(_ db: Database) throws -> Int -} -``` - -When the `RowDecoder` associated type is [Row](#fetching-rows), or a [value](#value-queries), or a type that conforms to [FetchableRecord], the request can fetch: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. - -The `makePreparedRequest(_:forSingleResult:)` method accepts a database connection, a `singleResult` hint, and returns a "prepared request" made of a [prepared statement](#prepared-statements) and an optional [row adapter](#row-adapters). Conforming types can use the `singleResult` hint as an optimization opportunity, and return a statement that fetches at most one row, with a `LIMIT` SQL clause, when possible. - -The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. - -The base `DatabaseRegionConvertible` protocol is involved in [database observation](#database-changes-observation). For more information, see [DatabaseRegion], [DatabaseRegionObservation], and [ValueObservation]. - -The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): - -```swift -// A FetchRequest whose RowDecoder associated type is Player: -let request = Player.all() -``` - - -### Building Custom Requests - -**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. +**To build custom requests**, you can use one of the built-in requests or derive requests from other requests. - [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: @@ -4866,36 +4825,7 @@ let request = Player.all() - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. - - -### Fetching From Custom Requests - -A type adopting [FetchRequest](#fetchrequest-protocol) knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [FetchableRecord]): - -```swift -let rowRequest = ... // Some FetchRequest that fetches Row -try request.fetchCursor(db) // A cursor of rows - -let playerRequest = ... // Some FetchRequest that fetches Player -try request.fetchAll(db) // [Player] - -let intRequest = ... // Some FetchRequest that fetches Int -try request.fetchOne(db) // Int? -``` - -For example: - -```swift -let playerRequest = SQLRequest( - sql: "SELECT * FROM player WHERE color = ?" - arguments: [color]) -try request.fetchAll(db) // [Player] -``` - -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. - -The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the [Beyond FetchableRecord] chapter for more information. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -7412,7 +7342,7 @@ You can compile the request into a prepared statement: ```swift try dbQueue.read { db in let request = Player.filter(Column("name") == "O'Brien") - let statement = try request.makePreparedRequest(db).statement + let statement = try request.makePreparedRequest(db, forSingleResult: false).statement print(statement.sql) // "SELECT * FROM player WHERE name = ?" print(statement.arguments) // ["O'Brien"] } diff --git a/TODO.md b/TODO.md index 7f873c6cc..20a199f07 100644 --- a/TODO.md +++ b/TODO.md @@ -16,6 +16,7 @@ ## Features +- [ ] DatabaseMigrator.hasBeenSuperseded(): https://forums.swift.org/t/detect-future-database-migrations/36315/4 - [ ] Subqueries: request.isEmpty / request.exists - [ ] Subqueries: request.count - [ ] Extract one row from a hasMany association (the one with the maximum date, the one with a flag set, etc.) https://stackoverflow.com/questions/43188771/sqlite-join-query-most-recent-posts-by-each-user (failed PR: https://github.com/groue/GRDB.swift/pull/767) diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index a1d19d0eb..c51fe3be1 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -101,11 +101,18 @@ private class UserPersistableRecord2 : PersistableRecord { func encode(to container: inout PersistenceContainer) { } } +// MARK: - SQLRequestProtocol + +private struct UserRowSQLRequest : SQLRequestProtocol { + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { preconditionFailure() } +} + // MARK: - FetchRequest private struct UserRowRequest : FetchRequest { struct CustomType { } typealias RowDecoder = CustomType + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { preconditionFailure() } func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { preconditionFailure() } } diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index 02cc4f246..eecfcb636 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,8 +107,8 @@ 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,15 +134,15 @@ 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" } } } - + let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in // Row @@ -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,166 @@ class FetchRequestTests: GRDBTestCase { XCTAssertEqual(region.description, "multiple(a)") } } + + func testSQLLiteralBasedFetchRequest() throws { + // Here we test that users can implement their own FetchRequest type. + struct CustomRequest : FetchRequest { + typealias RowDecoder = String + + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + let literal: SQLLiteral = "SELECT \("O'Brien")" + return try literal.sql(context) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let value = try CustomRequest().fetchOne(db) + XCTAssertEqual(value, "O'Brien") + XCTAssertEqual(lastSQLQuery, "SELECT 'O''Brien'") + } + } + + func testFetchRequestDerivedFromPreparedRequest() throws { + // Here we test that we can derive requestSQL(_:forSingleResult:) from + // makePreparedRequest(_:forSingleResult:). + // + // This is an upgrade path from GRDB4 to GRDB5. + // + // We also test that the same SQLLiteral can be used in both + // makePreparedRequest() and requestSQL() (see testSQLLiteralBasedFetchRequest) + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try makePreparedRequest(context.db, forSingleResult: singleResult).requestSQL(context) + } + + func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + let literal: SQLLiteral = "SELECT \("O'Brien")" + let statement = try db.makeSelectStatement(literal: literal) + return PreparedRequest(statement: statement) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = CustomRequest() + _ = try SQLRequest("SELECT * FROM (\(request))").fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM (SELECT 'O''Brien')") + } + } + + func testFetchRequestInconsistency() throws { + // What happens when requestSQL(_:forSingleResult:) + // and makePreparedRequest(_:forSingleResult:) do not agree? + struct Table1: TableRecord { } + struct Table2: TableRecord { } + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String { + try Table1.all().requestSQL(context, forSingleResult: singleResult) + } + func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest { + try Table2.all().makePreparedRequest(db, forSingleResult: singleResult) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.autoIncrementedPrimaryKey("id") + } + try db.create(table: "table2") { t in + t.autoIncrementedPrimaryKey("id") + } + + let request = CustomRequest() + + // DatabaseRegionConvertible + let region = try request.databaseRegion(db) + XCTAssertTrue(region.description.contains("table1")) + + // FetchRequest + _ = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"table2\"") + + _ = try request.fetchCount(db) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"table1\")") + + // SQLExpression + _ = try SQLRequest("SELECT \(request == 1)").fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT (SELECT * FROM \"table1\") = 1") + + // SQLCollection + _ = try SQLRequest("SELECT \(request.contains(1))").fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT 1 IN (SELECT * FROM \"table1\")") + + // SQLRequestProtocol + _ = try SQLRequest("SELECT * FROM (\(request))").fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM (SELECT * FROM \"table1\")") + } + } + + 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) + } } }