Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2020-05-11 18:50:35 +02:00
commit e99015bcff
30 files changed
+1079 -648

No files matched your search

+20 -4
View File
@@ -5,13 +5,13 @@ All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
<!--
[Next Release](#next-release)
-->
#### 5.x Releases
- `5.0.0` Betas - [5.0.0-beta](#500-beta)
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2)
#### 4.x Releases
@@ -70,16 +70,32 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
<!--
## Next Release
-->
## 5.0.0-beta.2
Released May 11, 2020 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta...v5.0.0-beta.2)
### Documentation Diff
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) describes the sunsetting of custom `FetchRequest` types.
- The [Sharing a Database](Documentation/SharingADatabase.md) guide has an updated recommendation for opening writer connections to a shared database.
### New
- [#772](https://github.com/groue/GRDB.swift/pull/772): Update the Database Sharing Guide with mention of the persistent WAL mode
- [#775](https://github.com/groue/GRDB.swift/pull/775): DatabaseMigrator can check if it has been superseded
### 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
## 5.0.0-beta
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+9 -37
View File
@@ -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<Player> = "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
+13 -16
View File
@@ -42,7 +42,7 @@ You migrate the database up to the latest version with the `migrate(_:)` method:
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
```
Migrate a database up to a specific version:
Migrate a database up to a specific version (useful for testing):
```swift
try migrator.migrate(dbQueue, upTo: "v2")
@@ -53,27 +53,24 @@ try migrator.migrate(dbQueue, upTo: "v1")
// ^ fatal error: database is already migrated beyond migration "v1"
```
Check if consecutive migrations have been applied:
When several versions of your app are deployed in the wild, you may want to perform extra checks:
```swift
if try dbQueue.read(migrator.hasCompletedMigrations) {
// All migrations have been applied, up to the last one.
}
if try dbQueue.read(migrator.completedMigrations).last == "v2" {
// All migrations up to "v2" have been applied, and no further.
}
if try dbQueue.read(migrator.completedMigrations).contains("v2") {
// All migrations up to "v2" have been applied, and maybe further.
try dbQueue.read { db in
// Readonly apps may want to check if database lacks expected migrations:
if try migrator.hasCompletedMigrations(db) == false {
// database too old
}
// All apps may want to check if database contains unknown (future) migrations:
if try migrator.hasBeenSuperseded(db) {
// database too new
}
}
```
Check if individual migrations have been applied:
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/DatabaseMigrator.html) for more migrator methods.
```swift
if try dbQueue.read(migrator.appliedMigrations).contains("v2") {
// "v2" migration has been applied
}
```
## The `eraseDatabaseOnSchemaChange` Option
+2
View File
@@ -17,6 +17,8 @@ To release a new GRDB version:
- CHANGELOG.md
- GRDB.swift.podspec
- README.md
- Documentation/FullTextSearch.md
- Documentation/Migrations.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
+17 -6
View File
@@ -69,8 +69,14 @@ Since several processes may open the database at the same time, protect the crea
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator.
// the database schema with a DatabaseMigrator, and
// checking if the application can open the file:
try migrator.migrate(dbPool)
if try dbPool.read(migrator.hasBeenSuperseded) {
// Database is too recent
throw /* some error */
}
return dbPool
}
```
@@ -105,12 +111,17 @@ Since several processes may open the database at the same time, protect the crea
configuration.readonly = true
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is correct, for example
// with a DatabaseMigrator.
if try dbPool.read(migrator.hasCompletedMigrations) {
// Check here if the database schema is the expected one,
// for example with a DatabaseMigrator:
return try dbPool.read { db in
if try migrator.hasBeenSuperseded(db) {
// Database is too recent
return nil
} else if try migrator.hasCompletedMigrations(db) == false {
// Database is too old
return nil
}
return dbPool
} else {
return nil
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.0.0-beta'
s.version = '5.0.0-beta.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+10
View File
@@ -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 = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
@@ -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 */,
+21 -3
View File
@@ -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)
+109 -35
View File
@@ -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<Self> {
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<Self> {
AdaptedFetchRequest(self, adapter)
}
}
/// An adapted request.
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
public typealias RowDecoder = Base.RowDecoder
@@ -118,6 +174,12 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: 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)
@@ -146,18 +208,35 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
///
/// An AnyFetchRequest forwards its operations to an underlying request,
/// hiding its specifics.
public struct AnyFetchRequest<T>: FetchRequest {
public typealias RowDecoder = T
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
private let _fetchCount: (Database) throws -> Int
public struct AnyFetchRequest<RowDecoder>: FetchRequest {
// 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: FetchRequest>(_ 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:
@@ -169,9 +248,4 @@ public struct AnyFetchRequest<T>: FetchRequest {
public func fetchCount(_ db: Database) throws -> Int {
try _fetchCount(db)
}
/// :nodoc:
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try _databaseRegion(db)
}
}
+8 -10
View File
@@ -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
}
+17 -39
View File
@@ -1,5 +1,5 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<RowDecoder>: FetchRequest {
public struct SQLRequest<RowDecoder> {
/// 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<RowDecoder>: 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<RowDecoder>: 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) {
+46
View File
@@ -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
}
}
+5 -2
View File
@@ -7,6 +7,9 @@ import UIKit
#endif
extension AnyFetchRequest {
@available(*, unavailable, renamed: "RowDecoder")
typealias T = RowDecoder
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
{ preconditionFailure() }
@@ -197,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() }
}
+35 -19
View File
@@ -170,8 +170,10 @@ public struct DatabaseMigrator {
// MARK: - Querying Migrations
/// Returns the applied migration identifiers, in the same order as
/// registered migrations.
/// Returns the identifiers of registered and applied migrations, in the
/// order of registration.
///
/// See also `appliedIdentifiers(_:)`.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
@@ -180,6 +182,24 @@ public struct DatabaseMigrator {
return migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
}
/// Returns the applied migration identifiers, even unregistered ones.
///
/// See also `appliedMigrations(_:)`.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
do {
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
} catch {
// Rethrow if we can't prove grdb_migrations does not exist yet
if (try? !db.tableExists("grdb_migrations")) ?? false {
return []
}
throw error
}
}
/// Returns the identifiers of completed migrations, of which all previous
/// migrations have been applied.
///
@@ -200,7 +220,19 @@ public struct DatabaseMigrator {
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
try completedMigrations(db).last == migrations.last?.identifier
}
/// Returns whether database contains unknown migration
/// identifiers, which is likely the sign that the database
/// has migrated further than the migrator itself supports.
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
let appliedIdentifiers = try self.appliedIdentifiers(db)
let knownIdentifiers = migrations.map(\.identifier)
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
}
// MARK: - Non public
private mutating func registerMigration(_ migration: Migration) {
@@ -210,22 +242,6 @@ public struct DatabaseMigrator {
migrations.append(migration)
}
/// Returns the applied migration identifiers, even unregistered ones
///
/// - parameter db: A database connection.
/// - throws: An eventual database error.
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
do {
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
} catch {
// Rethrow if we can't prove grdb_migrations does not exist yet
if (try? !db.tableExists("grdb_migrations")) ?? false {
return []
}
throw error
}
}
/// Returns unapplied migration identifier,
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
var expectedMigrations: [Migration] = []
@@ -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<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(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<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(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:
@@ -1,30 +1,49 @@
/// [**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 struct SQLGenerationContext {
/// A database connection so that request elements can perform database
/// introspection in order to build their SQL representation.
let db: Database
public final class SQLGenerationContext {
private enum Parent {
case none(db: Database, argumentsSink: StatementArgumentsSink)
case context(SQLGenerationContext)
}
/// The arguments sink which prevents SQL injection.
let argumentsSink: StatementArgumentsSink
// 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
}
}
/// All arguments gathered so far
/// All gathered arguments
var arguments: StatementArguments { argumentsSink.arguments }
private var resolvedNames: [TableAlias: String]
private var qualifiesColumnsWithTable: Bool
/// Access to the database connection, the arguments sink, and resolved
/// names of table aliases from outer contexts (useful in case of
/// subquery generation).
private let parent: Parent
/// The arguments sink which prevents SQL injection.
private var argumentsSink: StatementArgumentsSink {
switch parent {
case let .none(db: _, argumentsSink: argumentsSink): return argumentsSink
case let .context(context): return context.argumentsSink
}
}
private let resolvedNames: [TableAlias: String]
private let ownAliases: Set<TableAlias>
/// Creates a generation context.
///
@@ -36,14 +55,28 @@ public struct SQLGenerationContext {
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
aliases: [TableAlias] = [])
{
self.db = db
self.argumentsSink = argumentsSink
self.parent = .none(db: db, argumentsSink: argumentsSink)
self.resolvedNames = aliases.resolvedNames
self.qualifiesColumnsWithTable = aliases.count > 1
self.ownAliases = Set(aliases)
}
/// Creates a generation context.
///
/// - parameter parent: A parent context.
/// - parameter aliases: An array of table aliases to disambiguate.
init(
parent: SQLGenerationContext,
aliases: [TableAlias] = [])
{
self.parent = .context(parent)
self.resolvedNames = aliases.resolvedNames
self.ownAliases = Set(aliases)
}
/// 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)
}
@@ -59,15 +92,26 @@ public struct SQLGenerationContext {
if alias.hasUserName {
return alias.identityName
}
if qualifiesColumnsWithTable == false {
return nil
if !ownAliases.contains(alias) {
return resolvedName(for: alias)
}
return resolvedName(for: alias)
if ownAliases.count > 1 {
return resolvedName(for: alias)
}
return nil
}
/// WHERE <resolvedName> MATCH pattern
func resolvedName(for alias: TableAlias) -> String {
resolvedNames[alias] ?? alias.identityName
if let name = resolvedNames[alias] {
return name
}
switch parent {
case .none:
return alias.identityName
case let .context(context):
return context.resolvedName(for: alias)
}
}
/// FROM tableName <alias>
@@ -101,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
@@ -312,7 +356,7 @@ public class TableAlias: Hashable {
public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm {
ordering.qualifiedOrdering(with: self)
}
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(root))
@@ -59,15 +59,11 @@ struct SQLQueryGenerator: Refinable {
self.singleResult = singleResult
}
func sql(
_ db: Database,
argumentsSink: StatementArgumentsSink = StatementArgumentsSink())
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(db, argumentsSink: argumentsSink, aliases: relation.allAliases)
let context = SQLGenerationContext(parent: context, aliases: relation.allAliases)
var sql = "SELECT"
@@ -125,7 +121,7 @@ struct SQLQueryGenerator: Refinable {
var limit = self.limit
if try singleResult && !expectsSingleResult(
db,
context.db,
selection: selection,
filters: filters,
groupExpressions: groupExpressions)
@@ -141,13 +137,25 @@ struct SQLQueryGenerator: Refinable {
return sql
}
// Convenience
func sql(_ context: SQLGenerationContext) throws -> String {
try sql(context.db, argumentsSink: context.argumentsSink)
func makePreparedRequest(_ db: Database) throws -> PreparedRequest {
try PreparedRequest(
statement: makeSelectStatement(db),
adapter: rowAdapter(db))
}
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
try (makeSelectStatement(db), 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 {
@@ -330,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(db, argumentsSink: context.argumentsSink)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -448,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(db, argumentsSink: context.argumentsSink)
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
sql += ")"
let statement = try db.makeUpdateStatement(sql: sql)
@@ -456,21 +464,6 @@ struct SQLQueryGenerator: Refinable {
return statement
}
/// Returns a select statement
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
// Build
let argumentsSink = StatementArgumentsSink()
let sql = try self.sql(db, argumentsSink: argumentsSink)
// Compile & set arguments
let statement = try db.makeSelectStatement(sql: sql)
statement.arguments = argumentsSink.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
@@ -766,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))"
}
}
@@ -1,10 +1,24 @@
/// :nodoc:
extension SQLInterpolation {
// MARK: - TableRecord
/// Appends the table name of the record type.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
public mutating func appendInterpolation<T: TableRecord>(_ table: T.Type) {
public mutating func appendInterpolation<T>(_ table: T.Type)
where T: TableRecord
{
appendLiteral(table.databaseTableName.quotedDatabaseIdentifier)
}
/// Appends the table name of the record type.
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = "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<Player> = "INSERT INTO \(tableOf: player) ..."
public mutating func appendInterpolation<T: TableRecord>(tableOf record: T) {
public mutating func appendInterpolation<T>(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<Player> = "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<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
public mutating func appendInterpolation<T: TableRecord>(columnsOf record: T.Type, tableAlias: String? = nil) {
public mutating func appendInterpolation<T>(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<Player> = """
/// SELECT \(AllColumns()) FROM player
/// """
public mutating func appendInterpolation(_ selection: SQLSelectable) {
public mutating func appendInterpolation<T>(_ 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<Player> = """
/// 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<Player> = """
/// SELECT * FROM player ORDER BY \(Column("name").desc)
/// """
public mutating func appendInterpolation<T>(_ orderingTerm: T)
where T: SQLOrderingTerm
{
elements.append(.orderingTerm(orderingTerm))
}
/// Appends the ordering SQL.
///
/// // SELECT name FROM player ORDER BY name DESC
/// let request: SQLRequest<Player> = """
/// 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<String> = """
/// SELECT \(Column("name")) FROM player
/// """
public mutating func appendInterpolation<T>(_ expressible: T)
where T: SQLExpressible
{
elements.append(.expression(expressible.sqlExpression))
}
/// Appends the expression SQL.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// 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<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(
_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey)
public mutating func appendInterpolation<T>(_ 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<Int> = """
/// SELECT score + \(bonus) FROM player
/// // SELECT name FROM player
/// let request: SQLRequest<String> = """
/// 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<String> = """
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation(_ codingKey: CodingKey) {
appendInterpolation(Column(codingKey.stringValue))
public mutating func appendInterpolation<T>(_ 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<T>(_ expressible: T)
where T: Sequence, T.Element: SQLExpressible, T: SQLExpressible
/// Appends the name of the coding key.
///
/// // SELECT name FROM player
/// let request: SQLRequest<String> = "
/// SELECT \(CodingKey.name) FROM player
/// """
public mutating func appendInterpolation<T>(_ 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<String> = "
/// 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<Int> = "SELECT MAX(score) FROM player"
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subquery))
/// """
public mutating func appendInterpolation<T>(_ 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<Int> = "SELECT MAX(score) FROM player"
///
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
/// let request: SQLRequest<Player> = """
/// 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<Player> = """
/// SELECT * FROM player WHERE id IN \(ids)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element: SQLExpressible {
public mutating func appendInterpolation<T>(_ sequence: T)
where T: Sequence, T.Element: SQLExpressible
{
appendInterpolation(sequence.lazy.map(\.sqlExpression))
}
@@ -142,7 +264,9 @@ extension SQLInterpolation {
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE a IN \(expressions)
/// """
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element == SQLExpression {
public mutating func appendInterpolation<T>(_ 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<Player> = """
/// 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<Int> = "SELECT MAX(score) FROM player"
/// let request: SQLRequest<Player> = """
/// SELECT * FROM player WHERE score = (\(subQuery))
/// """
public mutating func appendInterpolation<RowDecoder>(_ request: SQLRequest<RowDecoder>) {
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<Player> = """
/// SELECT * FROM player WHERE score = (\(subQuery))
/// """
public mutating func appendInterpolation<RowDecoder>(_ request: QueryInterfaceRequest<RowDecoder>) {
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<T>(_ expressible: T)
where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible
{
elements.append(.expression(expressible.sqlExpression))
}
}
+6
View File
@@ -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 = "<group>"; };
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
@@ -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 */,
+3 -3
View File
@@ -391,10 +391,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta \
--module-version 5.0.0-beta \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.2 \
--module-version 5.0.0-beta.2 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+22 -92
View File
@@ -11,13 +11,13 @@
---
**Latest release**: May 2, 2020 • version 5.0.0-beta • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: May 11, 2020 • version 5.0.0-beta.2 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; Swift 5.2+ / Xcode 11.4+
| Swift version | GRDB version |
| ------------- | ----------------------------------------------------------- |
| **Swift 5.2** | **v5.0.0-beta**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| **Swift 5.2** | **v5.0.0-beta.2**, [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0)|
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -264,7 +264,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -478,7 +478,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/Configuration.html) for more details.
## Database Pools
@@ -559,7 +559,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -619,7 +619,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -817,7 +817,7 @@ Both arrays and cursors can iterate over database results. How do you choose one
- **Cursors are granted with direct access to SQLite,** unlike arrays that have to take the time to copy database values. If you look after extra performance, you may prefer cursors over arrays.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -899,7 +899,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1182,7 +1182,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1589,7 +1589,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1703,7 +1703,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -1962,7 +1962,7 @@ row["consumed"] // "Hello"
row["produced"] // nil
```
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below.
To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support).
@@ -2417,7 +2417,7 @@ try Place.fetchAll(db, sql: "SELECT ...", arguments:...) // [Place]
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2796,7 +2796,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -4181,7 +4181,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4780,50 +4780,9 @@ 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)
**To build custom requests**, you can use one of the built-in requests or derive requests from other 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.
- [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:
- [SQLRequest](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example:
```swift
extension Player {
@@ -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<Player>(
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.2/Structs/AnyFetchRequest.html): a type-erased request.
## Joined Queries Support
@@ -6002,7 +5932,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -6012,7 +5942,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7109,7 +7039,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.2/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
@@ -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"]
}
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.0.0-beta</string>
<string>5.0.0-beta.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+3
View File
@@ -16,6 +16,9 @@
## 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)
- [ ] Turn a hasMany to hasOne without first/last : hasMany(Book.self).filter(Column("isBest") /* assume a single book is flagged best */).asOne()
- [ ] Support for more kinds of joins: https://github.com/groue/GRDB.swift/issues/740
@@ -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() }
}
+101 -42
View File
@@ -230,13 +230,7 @@ class DatabaseMigratorTests : GRDBTestCase {
// One migration
migrator.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
}
migrator.registerMigration("1", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
@@ -247,9 +241,7 @@ class DatabaseMigratorTests : GRDBTestCase {
// Two migrations
migrator.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
migrator.registerMigration("2", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
@@ -273,13 +265,7 @@ class DatabaseMigratorTests : GRDBTestCase {
// One migration
migrator.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
}
migrator.registerMigration("1", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
@@ -292,9 +278,7 @@ class DatabaseMigratorTests : GRDBTestCase {
// Two migrations
migrator.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
migrator.registerMigration("2", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
@@ -309,39 +293,114 @@ class DatabaseMigratorTests : GRDBTestCase {
}
}
func testSuperseded() throws {
var migrator = DatabaseMigrator()
// No migration
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
}
// One migration
migrator.registerMigration("1", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
}
// Two migrations
migrator.registerMigration("2", migrate: { _ in })
do {
let dbQueue = try makeDatabaseQueue()
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
try migrator.migrate(dbQueue, upTo: "1")
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
try migrator.migrate(dbQueue, upTo: "2")
try XCTAssertFalse(dbQueue.read(migrator.hasBeenSuperseded))
}
}
func testMergedMigrators() throws {
// Migrate a database
var oldMigrator = DatabaseMigrator()
oldMigrator.registerMigration("1", migrate: { _ in })
oldMigrator.registerMigration("3", migrate: { _ in })
var migrator1 = DatabaseMigrator()
migrator1.registerMigration("1", migrate: { _ in })
migrator1.registerMigration("3", migrate: { _ in })
let dbQueue = try makeDatabaseQueue()
try oldMigrator.migrate(dbQueue)
try migrator1.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read(oldMigrator.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(oldMigrator.completedMigrations), ["1", "3"])
try XCTAssertTrue(dbQueue.read(oldMigrator.hasCompletedMigrations))
try XCTAssertEqual(dbQueue.read(migrator1.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator1.appliedIdentifiers), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator1.completedMigrations), ["1", "3"])
try XCTAssertTrue(dbQueue.read(migrator1.hasCompletedMigrations))
try XCTAssertFalse(dbQueue.read(migrator1.hasBeenSuperseded))
// ---
// A source code merge inserts a migration between "1" and "3"
var newMigrator = DatabaseMigrator()
newMigrator.registerMigration("1", migrate: { _ in })
newMigrator.registerMigration("2", migrate: { _ in })
newMigrator.registerMigration("3", migrate: { _ in })
var migrator2 = DatabaseMigrator()
migrator2.registerMigration("1", migrate: { _ in })
migrator2.registerMigration("2", migrate: { _ in })
migrator2.registerMigration("3", migrate: { _ in })
try XCTAssertEqual(dbQueue.read(newMigrator.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(newMigrator.completedMigrations), ["1"])
try XCTAssertFalse(dbQueue.read(newMigrator.hasCompletedMigrations))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator2.appliedIdentifiers), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator2.completedMigrations), ["1"])
try XCTAssertFalse(dbQueue.read(migrator2.hasCompletedMigrations))
try XCTAssertFalse(dbQueue.read(migrator2.hasBeenSuperseded))
// The new source code migrates the database
try newMigrator.migrate(dbQueue)
try migrator2.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read(oldMigrator.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(oldMigrator.completedMigrations), ["1", "3"])
try XCTAssertTrue(dbQueue.read(oldMigrator.hasCompletedMigrations))
try XCTAssertEqual(dbQueue.read(migrator1.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator1.appliedIdentifiers), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator1.completedMigrations), ["1", "3"])
try XCTAssertTrue(dbQueue.read(migrator1.hasCompletedMigrations))
try XCTAssertTrue(dbQueue.read(migrator1.hasBeenSuperseded))
try XCTAssertEqual(dbQueue.read(newMigrator.appliedMigrations), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(newMigrator.completedMigrations), ["1", "2", "3"])
try XCTAssertTrue(dbQueue.read(newMigrator.hasCompletedMigrations))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator2.appliedIdentifiers), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator2.completedMigrations), ["1", "2", "3"])
try XCTAssertTrue(dbQueue.read(migrator2.hasCompletedMigrations))
try XCTAssertFalse(dbQueue.read(migrator2.hasBeenSuperseded))
// ---
// A source code merge appends a migration
var migrator3 = migrator2
migrator3.registerMigration("4", migrate: { _ in })
try XCTAssertEqual(dbQueue.read(migrator3.appliedMigrations), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator3.appliedIdentifiers), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator3.completedMigrations), ["1", "2", "3"])
try XCTAssertFalse(dbQueue.read(migrator3.hasCompletedMigrations))
try XCTAssertFalse(dbQueue.read(migrator3.hasBeenSuperseded))
// The new source code migrates the database
try migrator3.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read(migrator1.appliedMigrations), ["1", "3"])
try XCTAssertEqual(dbQueue.read(migrator1.appliedIdentifiers), ["1", "2", "3", "4"])
try XCTAssertEqual(dbQueue.read(migrator1.completedMigrations), ["1", "3"])
try XCTAssertTrue(dbQueue.read(migrator1.hasCompletedMigrations))
try XCTAssertTrue(dbQueue.read(migrator1.hasBeenSuperseded))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2", "3"])
try XCTAssertEqual(dbQueue.read(migrator2.appliedIdentifiers), ["1", "2", "3", "4"])
try XCTAssertEqual(dbQueue.read(migrator2.completedMigrations), ["1", "2", "3"])
try XCTAssertTrue(dbQueue.read(migrator2.hasCompletedMigrations))
try XCTAssertTrue(dbQueue.read(migrator2.hasBeenSuperseded))
try XCTAssertEqual(dbQueue.read(migrator3.appliedMigrations), ["1", "2", "3", "4"])
try XCTAssertEqual(dbQueue.read(migrator3.appliedIdentifiers), ["1", "2", "3", "4"])
try XCTAssertEqual(dbQueue.read(migrator3.completedMigrations), ["1", "2", "3", "4"])
try XCTAssertTrue(dbQueue.read(migrator3.hasCompletedMigrations))
try XCTAssertFalse(dbQueue.read(migrator3.hasBeenSuperseded))
}
// Regression test for https://github.com/groue/GRDB.swift/issues/741
@@ -418,7 +477,7 @@ class DatabaseMigratorTests : GRDBTestCase {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer) // <- schema change, because reasons (development)
t.column("score", .integer) // <- schema change
}
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, testFunction(), 1000)")
}
+181 -19
View File
@@ -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<T>: 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<Row>("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<Row>("SELECT \(request == 1)").fetchAll(db)
XCTAssertEqual(lastSQLQuery, "SELECT (SELECT * FROM \"table1\") = 1")
// SQLCollection
_ = try SQLRequest<Row>("SELECT \(request.contains(1))").fetchAll(db)
XCTAssertEqual(lastSQLQuery, "SELECT 1 IN (SELECT * FROM \"table1\")")
// SQLRequestProtocol
_ = try SQLRequest<Row>("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<Row> = "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<Row> = "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<Row> = "SELECT * FROM (\(CustomRequest()))"
let statement = try sqlRequest.makePreparedRequest(db, forSingleResult: false).statement
XCTAssertEqual(statement.sql, "SELECT * FROM (SELECT id FROM table1)")
}
}
}
+1
View File
@@ -100,6 +100,7 @@ class GRDBTestCase: XCTestCase {
}
dbConfiguration.trace = { [unowned self] sql in
#warning("TODO: make it thread-safe")
self.sqlQueries.append(sql)
}
@@ -526,6 +526,42 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
}
}
func testSubqueryWithOuterAlias() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "parent") { t in
t.autoIncrementedPrimaryKey("id")
t.column("parentId", .integer).references("parent")
}
try db.create(table: "child") { t in
t.column("childParentId", .integer).references("parent")
}
}
struct Parent: TableRecord {
static let parent = belongsTo(Parent.self)
}
struct Child: TableRecord { }
do {
let parentAlias = TableAlias()
// Some ugly subquery whose only purpose is to use a table alias
// which requires disambiguation in the parent query.
let subquery = Child.select(sql: "COUNT(*)").filter(Column("childParentId") == parentAlias[Column("id")])
let request = Parent
.joining(optional: Parent.parent.aliased(parentAlias))
.filter(subquery > 1)
XCTAssertEqual(
sql(dbQueue, request),
"""
SELECT "parent1".* FROM "parent" "parent1" \
LEFT JOIN "parent" "parent2" ON "parent2"."id" = "parent1"."parentId" \
WHERE (SELECT COUNT(*) FROM "child" WHERE "childParentId" = "parent2"."id") > 1
""")
}
}
func testNotEqual() throws {
let dbQueue = try makeDatabaseQueue()
+26
View File
@@ -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)
}
}
}