diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 203f6be68..b8f58b422 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,11 +3,12 @@ ### Pull Request Checklist +- [ ] CONTRIBUTING: You have read https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md - [ ] BRANCH: This pull request is submitted against the `development` branch. - [ ] DOCUMENTATION: Inline documentation has been updated. - [ ] DOCUMENTATION: README.md or another dedicated guide has been updated. - [ ] TESTS: Changes are tested. -- [ ] TESTS: The `make smokeTest` terminal command runs without failure (see https://github.com/groue/GRDB.swift/blob/master/CONTRIBUTING.md). +- [ ] TESTS: The `make smokeTest` terminal command runs without failure. diff --git a/CHANGELOG.md b/CHANGELOG.md index db59def3a..ccbf93269 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 5.x Releases +- `5.18.x` Releases - [5.17.0](#5180) - `5.17.x` Releases - [5.17.0](#5170) - `5.16.x` Releases - [5.16.0](#5160) - `5.15.x` Releases - [5.15.0](#5150) @@ -84,6 +85,20 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 5.18.0 + +Released January 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.17.0...v5.18.0) + +- **New**: [#1075](https://github.com/groue/GRDB.swift/pull/1075) by [@mallman](https://github.com/mallman): Progress-reporting database backups +- **New**: [#1129](https://github.com/groue/GRDB.swift/pull/1129) by [@groue](https://github.com/groue): Detached columns +- **New**: [#1132](https://github.com/groue/GRDB.swift/pull/1132) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.72.2 +- **New**: [#1133](https://github.com/groue/GRDB.swift/pull/1133) by [@groue](https://github.com/groue): Support for STRICT tables +- **Fixed**: [#1120](https://github.com/groue/GRDB.swift/pull/1120) by [@jnross](https://github.com/jnross): Fix typos +- **Fixed**: [#1121](https://github.com/groue/GRDB.swift/pull/1121) by [@byohay](https://github.com/byohay): Quote PROJECT_DIR and SRCROOT environment variables +- **Fixed**: [#1128](https://github.com/groue/GRDB.swift/pull/1128) by [@groue](https://github.com/groue): Deal with authorization callbacks from cursors of FetchableRecord +- **Documentation Update**: A new [Embedding SQL in Query Interface Requests](README.md#embedding-sql-in-query-interface-requests) chapter describes the ways to leverage your SQL skills and extend GRDB apis. + + ## 5.17.0 Released December 14, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.16.0...v5.17.0) @@ -98,6 +113,8 @@ Released December 14, 2021 • [diff](https://github.com/groue/GRDB.swift/com - **Documentation Update**: :star: The [Concurrency Guide](Documentation/Concurrency.md) was updated for the new support for asynchronous Swift. - **Documentation Update**: :star: [GRDBAsyncDemo](Documentation/DemoApps/GRDBAsyncDemo/README.md) is a new SwiftUI demo app that uses the new async apis. - **Documentation Update**: A new FAQ gives hints for avoiding a [Mutation of captured var in concurrently-executing code](README.md##mutation-of-captured-var-in-concurrently-executing-code) compiler error. +- **Documentation Update**: [#1107](https://github.com/groue/GRDB.swift/pull/1107) by [@tcwalther](https://github.com/tcwalther): Fix docstring for Database.create(index: ...) +- **Documentation Update**: [#1110](https://github.com/groue/GRDB.swift/pull/1110) by [@maxhumber](https://github.com/maxhumber): Minor changes to a tip in the README ## 5.16.0 diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 6ddca9107..293d0b4d5 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -891,7 +891,7 @@ struct Author: TableRecord { static let databaseTableName = "writer" } struct Book: TableRecord { - // Replace the defaut "writer" association key with "author" + // Replace the default "writer" association key with "author" static let author = belongsTo(Author.self).forKey("author") } @@ -1034,7 +1034,7 @@ struct Book: TableRecord { static let databaseTableName = "publication" } struct Author: TableRecord { - // Replace the defaut "publications" association key with "books" + // Replace the default "publications" association key with "books" static let books = hasMany(Book.self).forKey("books") } diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index c5b80566e..69d0f5f7e 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -3,7 +3,7 @@ Custom SQLite Builds By default, GRDB uses the version of SQLite that ships with the target operating system. -**You can build GRDB with a custom build of [SQLite 3.33.0](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.37.2](https://www.sqlite.org/changes.html).** A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks). diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 338487166..13015c76e 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -304,7 +304,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/5.17/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.18/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -587,7 +587,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/5.17/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.18/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index 297489ffd..e9d94d81d 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -77,7 +77,7 @@ try dbQueue.read { db in } ``` -See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.17/Structs/DatabaseMigrator.html) for more migrator methods. +See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.18/Structs/DatabaseMigrator.html) for more migrator methods. ## The `eraseDatabaseOnSchemaChange` Option diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index b5a347c38..f440b2a8e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '5.17.0' + s.version = '5.18.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5a1a122d4..d6ab4482e 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -7,6 +7,13 @@ objects = { /* Begin PBXBuildFile section */ + 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */; }; + 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; + 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; + 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ED4BB582731DD25008B127D /* BackupTestCase.swift */; }; 56012B552573EED000B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B562573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; 56012B572573EED100B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */; }; @@ -1266,6 +1273,8 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; + 4ED4BB582731DD25008B127D /* BackupTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = ""; }; @@ -2218,6 +2227,7 @@ 56A238111B9C74A90082EB20 /* Core */ = { isa = PBXGroup; children = ( + 4ED4BB582731DD25008B127D /* BackupTestCase.swift */, 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */, 56DAA2C41DE99D8D006E10C8 /* Cursor */, 56E4F7ED2392E2D000A611F6 /* DatabaseAbortedTransactionTests.swift */, @@ -2324,6 +2334,7 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, + 4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -2350,8 +2361,8 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 5605F1471C672E4000235C62 /* Support */, + 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, ); path = Core; sourceTree = ""; @@ -2861,7 +2872,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; 56EB54FA22C9115E00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2879,7 +2890,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; AAA4DCFA230F1E0600C74B15 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2897,7 +2908,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; /* End PBXShellScriptBuildPhase section */ @@ -2913,6 +2924,7 @@ 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 5656A8202295B12F001FF3FF /* SQLAssociation.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, + 4E13D2F52769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, @@ -3116,6 +3128,7 @@ 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56A2FA3B24424F4700E97D23 /* Export.swift in Sources */, 569BBA4F229170F900478429 /* Inflections+English.swift in Sources */, + 4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */, 5617294F223533F40006E219 /* EncodableRecord.swift in Sources */, 563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, @@ -3347,6 +3360,7 @@ 563B8FA2249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 4ED4BB5A2731DD25008B127D /* BackupTestCase.swift in Sources */, 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, @@ -3581,6 +3595,7 @@ 5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, 563B8FA1249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, + 4ED4BB592731DD25008B127D /* BackupTestCase.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, @@ -3718,6 +3733,7 @@ AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */, 56A2FA3D24424F4800E97D23 /* Export.swift in Sources */, AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */, + 4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */, AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */, 563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */, @@ -3949,6 +3965,7 @@ 563B8FA3249E8ACB007A48C9 /* ValueObservationPrintTests.swift in Sources */, AAA4DD8A230F262000C74B15 /* RecordPrimaryKeyRowIDTests.swift in Sources */, AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */, + 4ED4BB5B2731DD25008B127D /* BackupTestCase.swift in Sources */, AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */, AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */, @@ -4086,6 +4103,7 @@ 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index ec5ecdc3a..a32903377 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -21,9 +21,7 @@ extension RangeReplaceableCollection { /// - parameter cursor: The cursor whose elements feed the collection. public init(_ cursor: C) throws where C.Element == Element { self.init() - while let element = try cursor.next() { - append(element) - } + try cursor.forEach { append($0) } } /// Creates a collection containing the elements of a cursor. @@ -38,9 +36,7 @@ extension RangeReplaceableCollection { public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { self.init() reserveCapacity(minimumCapacity) - while let element = try cursor.next() { - append(element) - } + try cursor.forEach { append($0) } } } @@ -60,7 +56,7 @@ extension Dictionary { throws where Value == [C.Element] { self.init() - while let value = try cursor.next() { + try cursor.forEach { value in try self[keyForValue(value), default: []].append(value) } } @@ -86,7 +82,7 @@ extension Dictionary { throws where Value == [C.Element] { self.init(minimumCapacity: minimumCapacity) - while let value = try cursor.next() { + try cursor.forEach { value in try self[keyForValue(value), default: []].append(value) } } @@ -108,7 +104,7 @@ extension Dictionary { throws where C.Element == (Key, Value) { self.init() - while let (key, value) = try keysAndValues.next() { + try keysAndValues.forEach { key, value in if updateValue(value, forKey: key) != nil { fatalError("Duplicate values for key: '\(String(describing: key))'") } @@ -137,7 +133,7 @@ extension Dictionary { throws where C.Element == (Key, Value) { self.init(minimumCapacity: minimumCapacity) - while let (key, value) = try keysAndValues.next() { + try keysAndValues.forEach { key, value in if updateValue(value, forKey: key) != nil { fatalError("Duplicate values for key: '\(String(describing: key))'") } @@ -155,9 +151,7 @@ extension Set { /// - parameter cursor: A cursor of values to gather into a set. public init(_ cursor: C) throws where C.Element == Element { self.init() - while let element = try cursor.next() { - insert(element) - } + try cursor.forEach { insert($0) } } /// Creates a set containing the elements of a cursor. @@ -172,9 +166,7 @@ extension Set { /// storage buffer. public init(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element { self.init(minimumCapacity: minimumCapacity) - while let element = try cursor.next() { - insert(element) - } + try cursor.forEach { insert($0) } } } @@ -225,6 +217,9 @@ public protocol Cursor: AnyObject { /// Advances to the next element and returns it, or nil if no next element /// exists. Once nil has been returned, all subsequent calls return nil. func next() throws -> Element? + + /// Calls the given closure on each element in the cursor. + func forEach(_ body: (Element) throws -> Void) throws } extension Cursor { @@ -654,12 +649,14 @@ extension Cursor where Element: StringProtocol { /// having the same Element type, hiding the specifics of the underlying /// cursor. public final class AnyCursor: Cursor { - private let element: () throws -> Element? + private let _next: () throws -> Element? + private let _forEach: ((Element) throws -> Void) throws -> Void /// Creates a cursor that wraps a base cursor but whose type depends only on /// the base cursor’s element type public init(_ base: C) where C.Element == Element { - element = base.next + _next = base.next + _forEach = base.forEach } /// Creates a cursor that wraps a base iterator but whose type depends only @@ -676,12 +673,17 @@ public final class AnyCursor: Cursor { } /// Creates a cursor that wraps the given closure in its next() method - public init(_ body: @escaping () throws -> Element?) { - element = body + public init(_ next: @escaping () throws -> Element?) { + _next = next + _forEach = { + while let element = try next() { + try $0(element) + } + } } public func next() throws -> Element? { - try element() + try _next() } } diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 31b546ed9..d71aed13a 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -717,6 +717,9 @@ public struct ColumnInfo: FetchableRecord { public let name: String /// The column data type + /// + /// The casing of this string depends on the SQLite version: make sure you + /// process this string in a case-insensitive way. public let type: String /// True if and only if the column is constrained to be not null. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 1b47e7e90..21ab900c4 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1243,14 +1243,73 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - Backup - func backup( - to dbDest: Database, - afterBackupInit: (() -> Void)? = nil, - afterBackupStep: (() -> Void)? = nil) + /// Copies the database contents into another database. + /// + /// The `backup` method blocks the current thread until the destination + /// database contains the same contents as the source database. + /// + /// Usage: + /// + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.write { sourceDb in + /// try destination.barrierWriteWithoutTransaction { destDb in + /// try sourceDb.backup(to: destDb) + /// } + /// } + /// + /// + /// When you're after progress reporting during backup, you'll want to + /// perform the backup in several steps. Each step copies the number of + /// _database pages_ you specify. See + /// for more information: + /// + /// // Backup with progress reporting + /// try sourceDb.backup( + /// to: destDb, + /// pagesPerStep: ...) + /// { backupProgress in + /// print("Database backup progress:", backupProgress) + /// } + /// + /// The `progress` callback will be called at least once—when + /// `backupProgress.isCompleted == true`. If the callback throws + /// when `backupProgress.isCompleted == false`, the backup is aborted + /// and the error is rethrown. If the callback throws when + /// `backupProgress.isCompleted == true`, backup completion is + /// unaffected and the error is silently ignored. + /// + /// See also `DatabaseReader.backup()`. + /// + /// - parameters: + /// - destDb: The destination database. + /// - pagesPerStep: The number of database pages copied on each backup + /// step. By default, all pages are copied in one single step. + /// - progress: An optional function that is notified of the backup + /// progress. + /// - throws: The error thrown by `progress` if the backup is abandoned, or + /// any `DatabaseError` that would happen while performing the backup. + public func backup( + to destDb: Database, + pagesPerStep: Int32 = -1, + progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { - guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", sqliteConnection, "main") else { - throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage) + try backupInternal( + to: destDb, + pagesPerStep: pagesPerStep, + afterBackupStep: progress) + } + + func backupInternal( + to destDb: Database, + pagesPerStep: Int32 = -1, + afterBackupInit: (() -> Void)? = nil, + afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) + throws + { + guard let backup = sqlite3_backup_init(destDb.sqliteConnection, "main", sqliteConnection, "main") else { + throw DatabaseError(resultCode: destDb.lastErrorCode, message: destDb.lastErrorMessage) } guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else { throw DatabaseError() @@ -1260,14 +1319,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib do { backupLoop: while true { - switch sqlite3_backup_step(backup, -1) { + let rc = sqlite3_backup_step(backup, pagesPerStep) + let totalPageCount = Int(sqlite3_backup_pagecount(backup)) + let remainingPageCount = Int(sqlite3_backup_remaining(backup)) + let progress = DatabaseBackupProgress( + remainingPageCount: remainingPageCount, + totalPageCount: totalPageCount, + isCompleted: rc == SQLITE_DONE) + switch rc { case SQLITE_DONE: - afterBackupStep?() + try? afterBackupStep?(progress) break backupLoop case SQLITE_OK: - afterBackupStep?() + try afterBackupStep?(progress) case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage) } } } catch { @@ -1279,11 +1345,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib case SQLITE_OK: break case let code: - throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage) + throw DatabaseError(resultCode: code, message: destDb.lastErrorMessage) } // The schema of the destination database has changed: - dbDest.clearSchemaCache() + destDb.clearSchemaCache() } } @@ -1471,6 +1537,9 @@ extension Database { /// The `DOUBLE` SQL column type public static let double = ColumnType(rawValue: "DOUBLE") + /// The `REAL` SQL column type + public static let real = ColumnType(rawValue: "REAL") + /// The `NUMERIC` SQL column type public static let numeric = ColumnType(rawValue: "NUMERIC") @@ -1485,6 +1554,9 @@ extension Database { /// The `DATETIME` SQL column type public static let datetime = ColumnType(rawValue: "DATETIME") + + /// The `ANY` SQL column type + public static let any = ColumnType(rawValue: "ANY") } /// An SQLite conflict resolution. diff --git a/GRDB/Core/DatabaseBackupProgress.swift b/GRDB/Core/DatabaseBackupProgress.swift new file mode 100644 index 000000000..cf38f98d2 --- /dev/null +++ b/GRDB/Core/DatabaseBackupProgress.swift @@ -0,0 +1,22 @@ +/// An instance of `DatabaseBackupProgress` is passed to a callback of the +/// `DatabaseReader.backup` or `Database.backup` methods to report +/// database backup progress to the caller. +/// +/// This is an advanced API for expert users. It is based directly on the SQLite +/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html). +public struct DatabaseBackupProgress { + /// Total page count is defined by the `sqlite3_backup_remaining` function + public let remainingPageCount: Int + + /// Total page count is defined by the `sqlite3_backup_pagecount` function + public let totalPageCount: Int + + /// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()` + public var completedPageCount: Int { + totalPageCount - remainingPageCount + } + + /// This property is true if and only if `sqlite3_backup_step()` returns + /// `SQLITE_DONE` + public let isCompleted: Bool +} diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index d027d26cd..35eb51ea7 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -116,17 +116,22 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (29<<8))) public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (30<<8))) public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (31<<8))) + public static let SQLITE_IOERR_DATA = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (32<<8))) + public static let SQLITE_IOERR_CORRUPTFS = ResultCode(rawValue: (SQLITE_IOERR.rawValue | (33<<8))) public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (1<<8))) public static let SQLITE_LOCKED_VTAB = ResultCode(rawValue: (SQLITE_LOCKED.rawValue | (2<<8))) public static let SQLITE_BUSY_RECOVERY = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (1<<8))) public static let SQLITE_BUSY_SNAPSHOT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (2<<8))) + public static let SQLITE_BUSY_TIMEOUT = ResultCode(rawValue: (SQLITE_BUSY.rawValue | (3<<8))) public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (1<<8))) public static let SQLITE_CANTOPEN_ISDIR = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (2<<8))) public static let SQLITE_CANTOPEN_FULLPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (3<<8))) public static let SQLITE_CANTOPEN_CONVPATH = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (4<<8))) public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (5<<8))) /* Not Used */ + public static let SQLITE_CANTOPEN_SYMLINK = ResultCode(rawValue: (SQLITE_CANTOPEN.rawValue | (6<<8))) public static let SQLITE_CORRUPT_VTAB = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (1<<8))) public static let SQLITE_CORRUPT_SEQUENCE = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (2<<8))) + public static let SQLITE_CORRUPT_INDEX = ResultCode(rawValue: (SQLITE_CORRUPT.rawValue | (3<<8))) public static let SQLITE_READONLY_RECOVERY = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (1<<8))) public static let SQLITE_READONLY_CANTLOCK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (2<<8))) public static let SQLITE_READONLY_ROLLBACK = ResultCode(rawValue: (SQLITE_READONLY.rawValue | (3<<8))) @@ -144,11 +149,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible { public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (8<<8))) public static let SQLITE_CONSTRAINT_VTAB = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (9<<8))) public static let SQLITE_CONSTRAINT_ROWID = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (10<<8))) + public static let SQLITE_CONSTRAINT_PINNED = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (11<<8))) + public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode(rawValue: (SQLITE_CONSTRAINT.rawValue | (12<<8))) public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (1<<8))) public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode(rawValue: (SQLITE_NOTICE.rawValue | (2<<8))) public static let SQLITE_WARNING_AUTOINDEX = ResultCode(rawValue: (SQLITE_WARNING.rawValue | (1<<8))) public static let SQLITE_AUTH_USER = ResultCode(rawValue: (SQLITE_AUTH.rawValue | (1<<8))) public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) + public static let SQLITE_OK_SYMLINK = ResultCode(rawValue: (SQLITE_OK.rawValue | (2<<8))) // swiftlint:enable operator_usage_whitespace line_length } @@ -333,17 +341,22 @@ extension DatabaseError { public static let SQLITE_IOERR_BEGIN_ATOMIC = ResultCode.SQLITE_IOERR_BEGIN_ATOMIC public static let SQLITE_IOERR_COMMIT_ATOMIC = ResultCode.SQLITE_IOERR_COMMIT_ATOMIC public static let SQLITE_IOERR_ROLLBACK_ATOMIC = ResultCode.SQLITE_IOERR_ROLLBACK_ATOMIC + public static let SQLITE_IOERR_DATA = ResultCode.SQLITE_IOERR_DATA + public static let SQLITE_IOERR_CORRUPTFS = ResultCode.SQLITE_IOERR_CORRUPTFS public static let SQLITE_LOCKED_SHAREDCACHE = ResultCode.SQLITE_LOCKED_SHAREDCACHE public static let SQLITE_LOCKED_VTAB = ResultCode.SQLITE_LOCKED_VTAB public static let SQLITE_BUSY_RECOVERY = ResultCode.SQLITE_BUSY_RECOVERY public static let SQLITE_BUSY_SNAPSHOT = ResultCode.SQLITE_BUSY_SNAPSHOT + public static let SQLITE_BUSY_TIMEOUT = ResultCode.SQLITE_BUSY_TIMEOUT public static let SQLITE_CANTOPEN_NOTEMPDIR = ResultCode.SQLITE_CANTOPEN_NOTEMPDIR public static let SQLITE_CANTOPEN_ISDIR = ResultCode.SQLITE_CANTOPEN_ISDIR public static let SQLITE_CANTOPEN_FULLPATH = ResultCode.SQLITE_CANTOPEN_FULLPATH public static let SQLITE_CANTOPEN_CONVPATH = ResultCode.SQLITE_CANTOPEN_CONVPATH public static let SQLITE_CANTOPEN_DIRTYWAL = ResultCode.SQLITE_CANTOPEN_DIRTYWAL + public static let SQLITE_CANTOPEN_SYMLINK = ResultCode.SQLITE_CANTOPEN_SYMLINK public static let SQLITE_CORRUPT_VTAB = ResultCode.SQLITE_CORRUPT_VTAB public static let SQLITE_CORRUPT_SEQUENCE = ResultCode.SQLITE_CORRUPT_SEQUENCE + public static let SQLITE_CORRUPT_INDEX = ResultCode.SQLITE_CORRUPT_INDEX public static let SQLITE_READONLY_RECOVERY = ResultCode.SQLITE_READONLY_RECOVERY public static let SQLITE_READONLY_CANTLOCK = ResultCode.SQLITE_READONLY_CANTLOCK public static let SQLITE_READONLY_ROLLBACK = ResultCode.SQLITE_READONLY_ROLLBACK @@ -361,11 +374,14 @@ extension DatabaseError { public static let SQLITE_CONSTRAINT_UNIQUE = ResultCode.SQLITE_CONSTRAINT_UNIQUE public static let SQLITE_CONSTRAINT_VTAB = ResultCode.SQLITE_CONSTRAINT_VTAB public static let SQLITE_CONSTRAINT_ROWID = ResultCode.SQLITE_CONSTRAINT_ROWID + public static let SQLITE_CONSTRAINT_PINNED = ResultCode.SQLITE_CONSTRAINT_PINNED + public static let SQLITE_CONSTRAINT_DATATYPE = ResultCode.SQLITE_CONSTRAINT_DATATYPE public static let SQLITE_NOTICE_RECOVER_WAL = ResultCode.SQLITE_NOTICE_RECOVER_WAL public static let SQLITE_NOTICE_RECOVER_ROLLBACK = ResultCode.SQLITE_NOTICE_RECOVER_ROLLBACK public static let SQLITE_WARNING_AUTOINDEX = ResultCode.SQLITE_WARNING_AUTOINDEX public static let SQLITE_AUTH_USER = ResultCode.SQLITE_AUTH_USER public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode.SQLITE_OK_LOAD_PERMANENTLY + public static let SQLITE_OK_SYMLINK = ResultCode.SQLITE_OK_SYMLINK } extension DatabaseError { diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 515d3c14f..392dcfe4a 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -308,21 +308,68 @@ extension DatabaseReader { /// When the source is a DatabasePool, concurrent writes can happen during /// the backup. Those writes may, or may not, be reflected in the backup, /// but they won't trigger any error. - public func backup(to writer: DatabaseWriter) throws { - try writer.writeWithoutTransaction { dbDest in - try backup(to: dbDest) + /// + /// Usage: + /// + /// let source: DatabaseQueue = ... + /// let destination: DatabaseQueue = ... + /// try source.backup(to: destination) + /// + /// When you're after progress reporting during backup, you'll want to + /// perform the backup in several steps. Each step copies the number of + /// _database pages_ you specify. See + /// for more information: + /// + /// // Backup with progress reporting + /// try source.backup( + /// to: destination, + /// pagesPerStep: ...) + /// { backupProgress in + /// print("Database backup progress:", backupProgress) + /// } + /// + /// The `progress` callback will be called at least once—when + /// `backupProgress.isCompleted == true`. If the callback throws + /// when `backupProgress.isCompleted == false`, the backup is aborted + /// and the error is rethrown. If the callback throws when + /// `backupProgress.isCompleted == true`, backup completion is + /// unaffected and the error is silently ignored. + /// + /// See also `Database.backup()`. + /// + /// - parameters: + /// - writer: The destination database. + /// - pagesPerStep: The number of database pages copied on each backup + /// step. By default, all pages are copied in one single step. + /// - progress: An optional function that is notified of the backup + /// progress. + /// - throws: The error thrown by `progress` if the backup is abandoned, or + /// any `DatabaseError` that would happen while performing the backup. + public func backup( + to writer: DatabaseWriter, + pagesPerStep: Int32 = -1, + progress: ((DatabaseBackupProgress) throws -> Void)? = nil) + throws + { + try writer.writeWithoutTransaction { destDb in + try backup( + to: destDb, + pagesPerStep: pagesPerStep, + afterBackupStep: progress) } } func backup( - to dbDest: Database, + to destDb: Database, + pagesPerStep: Int32 = -1, afterBackupInit: (() -> Void)? = nil, - afterBackupStep: (() -> Void)? = nil) + afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil) throws { try read { dbFrom in - try dbFrom.backup( - to: dbDest, + try dbFrom.backupInternal( + to: destDb, + pagesPerStep: pagesPerStep, afterBackupInit: afterBackupInit, afterBackupStep: afterBackupStep) } diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index d6d1299fb..4bb52256d 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -28,6 +28,28 @@ extension ColumnExpression { public var sqlExpression: SQLExpression { .column(name) } + + /// Returns a "detached column", which is never qualified with any table + /// name in the SQL generated by the query interface. A detached column + /// allows you to refer to an aliased column (`expression AS alias`). + /// + /// For example, see how `Column("total").detached` makes it possible to + /// sort this query, when a raw `Column("total")` could not: + /// + /// // SELECT player.*, + /// // (player.score + player.bonus) AS total, + /// // team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamID + /// // ORDER BY total, player.name + /// // ~~~~~ + /// let request = Player + /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) + /// .including(required: Book.team) + /// .order(Column("total").detached, Column("name")) + public var detached: SQLExpression { + SQL(sql: name.quotedDatabaseIdentifier).sqlExpression + } } #if compiler(>=5.5) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index 8bf1e2fe3..94686e31b 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -189,9 +189,9 @@ public struct SQLExpression { /// If true, (a • b) is a bijective function of a, and a bijective /// function of b. /// - /// `+` and `||` (concat) are bijective. + /// `||` (concat) is bijective. /// - /// `AND`, `OR` and `*` are not. + /// `AND`, `OR`, `+` and `*` are not. let isBijective: Bool /// Creates a binary operator @@ -212,7 +212,7 @@ public struct SQLExpression { sql: "+", neutralValue: 0.databaseValue, strictlyAssociative: false, - bijective: true) + bijective: false) /// The `*` binary operator /// @@ -818,19 +818,6 @@ extension SQLExpression { return nil } - case let .binary(op, lhs, rhs): - guard acceptsBijection && op == .subtract else { - return nil - } - - if lhs.isConstantInRequest { - return try rhs.column(db, for: alias, acceptsBijection: acceptsBijection) - } else if rhs.isConstantInRequest { - return try lhs.column(db, for: alias, acceptsBijection: acceptsBijection) - } else { - return nil - } - case let .associativeBinary(op, expressions): assert(expressions.count > 1) guard acceptsBijection && op.isBijective else { @@ -1834,9 +1821,8 @@ extension SQLSpecificExpressible { // MARK: - SQL Selection Support -/// :nodoc: extension SQLSpecificExpressible { - /// Give the expression the given SQL name. + /// Returns an aliased column. /// /// For example: /// @@ -1846,11 +1832,24 @@ extension SQLSpecificExpressible { /// if let row = try Row.fetchOne(db, request) { /// let area: Int = row["area"] /// } + /// + /// If you need to refer to the aliased column in another part of a request, + /// use `Column(...).detached`. For example: + /// + /// // SELECT (width * height) AS area FROM shape ORDER BY area + /// let area = (Column("width") * Column("height")).forKey("area") + /// let request = Shape + /// .select(area) + /// .order(Column("area").detached) + /// let rows = try Row.fetchCursor(db, request) + /// while let row = try rows.next() { + /// let area: Int = row["area"] + /// } public func forKey(_ key: String) -> SQLSelection { .aliasedExpression(sqlExpression, key) } - /// Give the expression the same SQL name as the coding key. + /// Returns an aliased column with the same name as the coding key. /// /// For example: /// @@ -1868,6 +1867,8 @@ extension SQLSpecificExpressible { /// /// // SELECT width, height, (width * height) AS area FROM shape /// let shapes: [Shape] = try Shape.fetchAll(db) + /// + /// See `forKey(_ key: String)` for more information. public func forKey(_ key: CodingKey) -> SQLSelection { forKey(key.stringValue) } diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index 8150f6acd..6c4785ab9 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -108,7 +108,8 @@ extension SQLOrdering { case .literal: fatalError(""" Ordering literals can't be reversed. \ - To resolve this error, order by expression literals instead. + To resolve this error, order by expression literals instead. \ + For example: order(SQL("(score + bonus)").sqlExpression) """) } } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index b80dbcf92..ae9533480 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -2,6 +2,48 @@ extension Database { // MARK: - Database Schema + // TODO: deprecate just before GRDB 6 + /// Creates a database table. + /// + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("title", .text) + /// t.column("favorite", .boolean).notNull().default(false) + /// t.column("longitude", .double).notNull() + /// t.column("latitude", .double).notNull() + /// } + /// + /// See and + /// + /// + /// - warning: This method is sunsetted. You should prefer + /// `create(table:options:body:)` instead. + /// + /// - parameters: + /// - name: The table name. + /// - temporary: If true, creates a temporary table. + /// - ifNotExists: If false (the default), an error is thrown if the + /// table already exists. Otherwise, the table is created unless it + /// already exists. + /// - withoutRowID: If true, uses WITHOUT ROWID optimization. + /// - body: A closure that defines table columns and constraints. + /// - throws: A DatabaseError whenever an SQLite error occurs. + @_disfavoredOverload + public func create( + table name: String, + temporary: Bool = false, + ifNotExists: Bool = false, + withoutRowID: Bool = false, + body: (TableDefinition) throws -> Void) + throws + { + var options: TableOptions = [] + if temporary { options.insert(.temporary) } + if ifNotExists { options.insert(.ifNotExists) } + if withoutRowID { options.insert(.withoutRowID) } + try create(table: name, options: options, body: body) + } + /// Creates a database table. /// /// try db.create(table: "place") { t in @@ -17,27 +59,19 @@ extension Database { /// /// - parameters: /// - name: The table name. - /// - temporary: If true, creates a temporary table. - /// - ifNotExists: If false (the default), an error is thrown if the - /// table already exists. Otherwise, the table is created unless it - /// already exists. - /// - withoutRowID: If true, uses WITHOUT ROWID optimization. + /// - options: Table creation options. /// - body: A closure that defines table columns and constraints. /// - throws: A DatabaseError whenever an SQLite error occurs. public func create( table name: String, - temporary: Bool = false, - ifNotExists: Bool = false, - withoutRowID: Bool = false, - body: (TableDefinition) -> Void) + options: TableOptions = [], + body: (TableDefinition) throws -> Void) throws { let definition = TableDefinition( name: name, - temporary: temporary, - ifNotExists: ifNotExists, - withoutRowID: withoutRowID) - body(definition) + options: options) + try body(definition) let sql = try definition.sql(self) try execute(sql: sql) } @@ -79,6 +113,46 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } + // TODO: deprecate just before GRDB 6 + /// Creates an index. + /// + /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) + /// + /// SQLite can also index expressions (https://www.sqlite.org/expridx.html) + /// and use specific collations. To create such an index, use a raw SQL + /// query. + /// + /// try db.execute(sql: "CREATE INDEX ...") + /// + /// See + /// + /// - warning: This method is sunsetted. You should prefer + /// `create(index:on:columns:options:condition:)` instead. + /// + /// - parameters: + /// - name: The index name. + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - unique: If true, creates a unique index. + /// - ifNotExists: If true, no error is thrown if index already exists. + /// - condition: If not nil, creates a partial index + /// (see ). + @_disfavoredOverload + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: SQLExpressible? = nil) + throws + { + var options: IndexOptions = [] + if ifNotExists { options.insert(.ifNotExists) } + if unique { options.insert(.unique) } + try create(index: name, on: table, columns: columns, options: options, condition: condition) + } + /// Creates an index. /// /// try db.create(index: "playerByEmail", on: "player", columns: ["email"]) @@ -95,16 +169,14 @@ extension Database { /// - name: The index name. /// - table: The name of the indexed table. /// - columns: The indexed columns. - /// - unique: If true, creates a unique index. - /// - ifNotExists: If true, no error is thrown if index already exists. + /// - options: Index creation options. /// - condition: If not nil, creates a partial index /// (see ). public func create( index name: String, on table: String, columns: [String], - unique: Bool = false, - ifNotExists: Bool = false, + options: IndexOptions = [], condition: SQLExpressible? = nil) throws { @@ -112,8 +184,7 @@ extension Database { name: name, table: table, columns: columns, - unique: unique, - ifNotExists: ifNotExists, + options: options, condition: condition?.sqlExpression) let sql = try definition.sql(self) try execute(sql: sql) @@ -153,6 +224,29 @@ extension Database { } } +/// Table creation options +public struct TableOptions: OptionSet { + /// :nodoc: + public let rawValue: Int + + /// :nodoc: + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the table if it does not already exist. + public static let ifNotExists = TableOptions(rawValue: 1 << 0) + + /// Creates a temporary table. + public static let temporary = TableOptions(rawValue: 1 << 1) + + /// Creates a without rowid table. See + public static let withoutRowID = TableOptions(rawValue: 1 << 2) + +#if GRDBCUSTOMSQLITE + /// Creates a strict table. See + public static let strict = TableOptions(rawValue: 1 << 3) +#endif +} + /// The TableDefinition class lets you define table columns and constraints. /// /// You don't create instances of this class. Instead, you use the Database @@ -200,9 +294,7 @@ public final class TableDefinition { } private let name: String - private let temporary: Bool - private let ifNotExists: Bool - private let withoutRowID: Bool + private let options: TableOptions private var columns: [ColumnItem] = [] private var primaryKeyConstraint: KeyConstraint? private var uniqueKeyConstraints: [KeyConstraint] = [] @@ -210,11 +302,9 @@ public final class TableDefinition { private var checkConstraints: [SQLExpression] = [] private var literalConstraints: [SQL] = [] - init(name: String, temporary: Bool, ifNotExists: Bool, withoutRowID: Bool) { + init(name: String, options: TableOptions) { self.name = name - self.temporary = temporary - self.ifNotExists = ifNotExists - self.withoutRowID = withoutRowID + self.options = options } /// Defines the auto-incremented primary key. @@ -444,11 +534,11 @@ public final class TableDefinition { do { var chunks: [String] = [] chunks.append("CREATE") - if temporary { + if options.contains(.temporary) { chunks.append("TEMPORARY") } chunks.append("TABLE") - if ifNotExists { + if options.contains(.ifNotExists) { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) @@ -549,14 +639,29 @@ public final class TableDefinition { chunks.append("(\(items.joined(separator: ", ")))") } - if withoutRowID { - chunks.append("WITHOUT ROWID") + var tableOptions: [String] = [] + +#if GRDBCUSTOMSQLITE + if options.contains(.strict) { + tableOptions.append("STRICT") } +#endif + + if options.contains(.withoutRowID) { + tableOptions.append("WITHOUT ROWID") + } + + if !tableOptions.isEmpty { + chunks.append(tableOptions.joined(separator: ", ")) + } + statements.append(chunks.joined(separator: " ")) } + var indexOptions: IndexOptions = [] + if options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) } let indexStatements = try columns - .compactMap { $0.columnDefinition?.indexDefinition(in: name, ifNotExists: ifNotExists) } + .compactMap { $0.columnDefinition?.indexDefinition(in: name, options: indexOptions) } .map { try $0.sql(db) } statements.append(contentsOf: indexStatements) return statements.joined(separator: "; ") @@ -680,7 +785,7 @@ public final class TableAlteration { let statement = chunks.joined(separator: " ") statements.append(statement) - if let indexDefinition = column.indexDefinition(in: name, ifNotExists: false) { + if let indexDefinition = column.indexDefinition(in: name) { try statements.append(indexDefinition.sql(db)) } @@ -1143,7 +1248,7 @@ public final class ColumnDefinition { return chunks.joined(separator: " ") } - fileprivate func indexDefinition(in table: String, ifNotExists: Bool) -> IndexDefinition? { + fileprivate func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? { switch index { case .none: return nil case .unique: return nil @@ -1152,29 +1257,42 @@ public final class ColumnDefinition { name: "\(table)_on_\(name)", table: table, columns: [name], - unique: false, - ifNotExists: ifNotExists, + options: options, condition: nil) } } } +/// Table creation options +public struct IndexOptions: OptionSet { + /// :nodoc: + public let rawValue: Int + + /// :nodoc: + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the index if it does not already exist. + public static let ifNotExists = IndexOptions(rawValue: 1 << 0) + + /// Creates a unique index. + public static let unique = IndexOptions(rawValue: 1 << 1) +} + private struct IndexDefinition { let name: String let table: String let columns: [String] - let unique: Bool - let ifNotExists: Bool + let options: IndexOptions let condition: SQLExpression? func sql(_ db: Database) throws -> String { var chunks: [String] = [] chunks.append("CREATE") - if unique { + if options.contains(.unique) { chunks.append("UNIQUE") } chunks.append("INDEX") - if ifNotExists { + if options.contains(.ifNotExists) { chunks.append("IF NOT EXISTS") } chunks.append(name.quotedDatabaseIdentifier) diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 4907d8342..cb6c53f90 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -126,14 +126,14 @@ extension Database { virtualTable tableName: String, ifNotExists: Bool = false, using module: Module, - _ body: ((Module.TableDefinition) -> Void)? = nil) + _ body: ((Module.TableDefinition) throws -> Void)? = nil) throws { // Define virtual table let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists) let definition = module.makeTableDefinition(configuration: configuration) if let body = body { - body(definition) + try body(definition) } // Create virtual table diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 24333e25b..22b274b7c 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -571,6 +571,34 @@ public final class RecordCursor: Cursor { try _statement.database.statementDidFail(_statement, withResultCode: code) } } + + // Specific override in order to deal with https://github.com/groue/GRDB.swift/issues/1124 + /// :nodoc: + public func forEach(_ body: (Record) throws -> Void) throws { + switch _state { + case .busy: + // We can't deal with possible authorizer + fatalError("Not implemented") + case .idle: + if let authorizer = try _statement.database.statementWillExecute(_statement) { + _state = .busy + try _statement.database.withAuthorizer(authorizer) { + while let element = try next() { + try body(element) + } + } + } else { + _state = .busy + while let element = try next() { + try body(element) + } + } + default: + while let element = try next() { + try body(element) + } + } + } } // MARK: - DatabaseDateDecodingStrategy diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 921bf2c8e..6916a2f08 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -7,6 +7,10 @@ objects = { /* Begin PBXBuildFile section */ + 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */; }; + 4E13D2F92769BC230037588C /* DatabaseBackupProgress.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */; }; + 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; + 4ECF777E273AFBAB001685F5 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */; }; 56012B6A2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; 56012B6B2573FAE700B4925B /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */; }; 56012B81257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; }; @@ -772,6 +776,8 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseBackupProgress.swift; sourceTree = ""; }; + 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; 56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = ""; }; 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = ""; }; @@ -1680,6 +1686,7 @@ 56A238111B9C74A90082EB20 /* Core */ = { isa = PBXGroup; children = ( + 4ECF777A273AFB72001685F5 /* BackupTestCase.swift */, 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */, 56DAA2C41DE99D8D006E10C8 /* Cursor */, 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */, @@ -1786,6 +1793,7 @@ 56A238711B9C75030082EB20 /* Database.swift */, 566B91221FA4CF810012D5B0 /* Database+Schema.swift */, 566B91081FA4C3960012D5B0 /* Database+Statements.swift */, + 4E13D2F72769BC230037588C /* DatabaseBackupProgress.swift */, 566B91121FA4C3F50012D5B0 /* DatabaseCollation.swift */, 56A238731B9C75030082EB20 /* DatabaseError.swift */, 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */, @@ -1812,8 +1820,8 @@ 56A238781B9C75030082EB20 /* Statement.swift */, 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */, 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */, - 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, 5605F1471C672E4000235C62 /* Support */, + 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */, ); path = Core; sourceTree = ""; @@ -2227,7 +2235,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; 56EB54FD22C9119B00850069 /* Swiftlint */ = { isa = PBXShellScriptBuildPhase; @@ -2245,7 +2253,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "${PROJECT_DIR}/Scripts/swiftlint.sh\n"; + shellScript = "\"${PROJECT_DIR}/Scripts/swiftlint.sh\"\n"; }; EED476F01CFD0B290026A4EC /* Copy .example configuration files (if no USER customizations exist) */ = { isa = PBXShellScriptBuildPhase; @@ -2343,6 +2351,7 @@ 5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */, + 4E13D2F92769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3A24424F4200E97D23 /* Export.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, @@ -2560,6 +2569,7 @@ 5615B279222B109600061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 4ECF777D273AFBA9001685F5 /* BackupTestCase.swift in Sources */, 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, @@ -2710,6 +2720,7 @@ 5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */, F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */, + 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */, 56A2FA3924424F4200E97D23 /* Export.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, @@ -2927,6 +2938,7 @@ 5615B278222B109600061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, 5698ACA11DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, + 4ECF777E273AFBAB001685F5 /* BackupTestCase.swift in Sources */, 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, diff --git a/Makefile b/Makefile index fed899a6c..4de7e8853 100644 --- a/Makefile +++ b/Makefile @@ -520,10 +520,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.17.0 \ - --module-version 5.17.0 \ + --github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.18.0 \ + --module-version 5.18.0 \ --module GRDB \ - --root-url http://groue.github.io/GRDB.swift/docs/5.17/ \ + --root-url http://groue.github.io/GRDB.swift/docs/5.18/ \ --output Documentation/Reference \ --xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS else diff --git a/README.md b/README.md index 15047136c..a82c87be1 100644 --- a/README.md +++ b/README.md @@ -11,13 +11,13 @@ --- -**Latest release**: December 14, 2021 • [version 5.17.0](https://github.com/groue/GRDB.swift/tree/v5.17.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) +**Latest release**: January 9, 2022 • [version 5.18.0](https://github.com/groue/GRDB.swift/tree/v5.18.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.3+ / Xcode 12+ | Swift version | GRDB version | | -------------- | ----------------------------------------------------------- | -| **Swift 5.3+** | **v5.17.0** | +| **Swift 5.3+** | **v5.18.0** | | Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.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) | @@ -318,7 +318,7 @@ Documentation #### Reference -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.17/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.18/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) #### Getting Started @@ -512,7 +512,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) for more details. ## Database Pools @@ -592,7 +592,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -652,7 +652,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.17/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.18/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. @@ -910,7 +910,7 @@ try dbQueue.read { db in let dictionary = try Dictionary(uniqueKeysWithValues: cursor) ``` -- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.17/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.18/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 @@ -989,7 +989,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.17/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.18/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: @@ -1274,7 +1274,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.17/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1721,7 +1721,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.17/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1833,7 +1833,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.17/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.18/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift insertStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1916,7 +1916,7 @@ See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) > :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so. -For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.17/Classes/Statement.html). +For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.18/Classes/Statement.html). ### Prepared Statements Cache @@ -2659,7 +2659,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.18/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()`. @@ -3099,7 +3099,7 @@ protocol EncodableRecord { } ``` -See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. +See [DatabaseColumnDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseColumnDecodingStrategy.html) and [DatabaseColumnEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseColumnEncodingStrategy.html) to learn about all available strategies. ### Date and UUID Coding Strategies @@ -3121,7 +3121,7 @@ protocol EncodableRecord { } ``` -See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.17/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. +See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.18/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies. There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase). @@ -4134,6 +4134,7 @@ So don't miss the [SQL API](#sqlite-api). - [Expressions](#expressions) - [SQL Operators](#sql-operators) - [SQL Functions](#sql-functions) +- [Embedding SQL in Query Interface Requests] - [Fetching from Requests] - [Fetching by Key](#fetching-by-key) - [Testing for Record Existence](#testing-for-record-existence) @@ -4186,7 +4187,7 @@ SQLite itself has many reference documents about table creation: [CREATE TABLE]( try db.create(table: "example") { t in ... } // CREATE TEMPORARY TABLE example IF NOT EXISTS ( -try db.create(table: "example", temporary: true, ifNotExists: true) { t in ... } +try db.create(table: "example", options: [.temporary, .ifNotExists]) { t in ... } ``` > :bulb: **Tip**: database table names should be singular, and camelCased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, `httpRequest`. @@ -4195,7 +4196,7 @@ try db.create(table: "example", temporary: true, ifNotExists: true) { t in ... } > > :point_up: **Note**: [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables can not be tracked with [Database Observation] tools. -**Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): +**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` and `any`) - see [SQLite data types](https://www.sqlite.org/datatype3.html): ```swift // CREATE TABLE example ( @@ -4334,8 +4335,11 @@ try db.drop(table: "obsolete") Create indexes with the `create(index:)` method: ```swift -// CREATE UNIQUE INDEX byEmail ON users(email) -try db.create(index: "byEmail", on: "users", columns: ["email"], unique: true) +// CREATE INDEX byName ON users(lastName, firstName) +try db.create(index: "byName", on: "users", columns: ["lastName, "firstName"]) + +// CREATE UNIQUE INDEX byEmail IF NOT EXISTS ON users(email) +try db.create(index: "byEmail", on: "users", columns: ["email"], options: [.unique, .ifNotExists]) ``` Relevant SQLite documentation: @@ -4643,7 +4647,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.17/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.18/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4710,7 +4714,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ### SQL Operators -GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators). +GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL operators. - `=`, `<>`, `<`, `<=`, `>`, `>=`, `IS`, `IS NOT` @@ -4943,11 +4947,33 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) ``` +- `AS` + + To give an alias to an expression, use the `forKey` method: + + ```swift + // SELECT (score + bonus) AS total + // FROM player + Player.select((Column("score") + Column("bonus")).forKey("total")) + ``` + + If you need to refer to this aliased column in another place of the request, use a detached column: + + ```swift + // SELECT (score + bonus) AS total + // FROM player + // ORDER BY total + Player + .select((Column("score") + Column("bonus")).forKey("total")) + .order(Column("total").detached) + ``` + + Unlike `Column("total")`, the detached column `Column("total").detached` is never associated to the "player" table, so it is always rendered as `total` in the generated SQL, even when the request involves other tables via an [association](Documentation/AssociationsBasics.md) or a [common table expression]. ### SQL Functions -GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Adding support for missing SQL functions or operators](#adding-support-for-missing-sql-functions-or-operators). +GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions. - `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: @@ -5014,22 +5040,138 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli Player.select(f.apply(nameColumn)) ``` -### Adding support for missing SQL functions or operators +## Embedding SQL in Query Interface Requests -When you spot an SQL function or operator that misses its Swift version, you can define it right into your application code. +You will sometimes want to extend your query interface requests with SQL snippets. This can happen because GRDB does not provide a Swift interface for some SQL function or operator, or because you want to use an SQLite construct that GRDB does not support. -For example, you can add support for the `DATE` function, thanks to [SQL Interpolation]: +Support for extensibility is large, but not unlimited. All the SQL queries built by the query interface request have the shape below. _If you need something else, you'll have to use [raw SQL requests](#sqlite-api)._ -```swift -func date(_ value: SQLSpecificExpressible) -> SQLExpression { - SQL("DATE(\(value))").sqlExpression -} - -// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +```sql +WITH ... -- 1 +SELECT ... -- 2 +FROM ... -- 3 +JOIN ... -- 4 +WHERE ... -- 5 +GROUP BY ... -- 6 +HAVING ... -- 7 +ORDER BY ... -- 8 +LIMIT ... -- 9 ``` -See the [Query Interface Organization] for more information about `SQLSpecificExpressible` and `SQLExpression`. +1. `WITH ...`: see [Common Table Expressions]. + +2. `SELECT ...` + + The selection can be provided as raw SQL: + + ```swift + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let request = Player.select(sql: "IFNULL(name, 'O''Brien'), score") + + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let defaultName = "O'Brien" + let request = Player.select(sql: "IFNULL(name, ?), score", arguments: [suffix]) + ``` + + The selection can be provided with [SQL Interpolation]: + + ```swift + // SELECT IFNULL(name, 'O''Brien'), score FROM player + let defaultName = "O'Brien" + let request = Player.select(literal: "IFNULL(name, \(defaultName)), score") + ``` + + The selection can be provided with a mix of Swift and [SQL Interpolation]: + + ```swift + // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player + let defaultName = "O'Brien" + let displayName: SQL = "IFNULL(\(Column("name")), \(defaultName)) AS displayName" + let request = Player.select(displayName, Column("score")) + ``` + + When the custom SQL snippet should behave as a full-fledged expression, with support for the `+` Swift operator, the `forKey` aliasing method, and all other [SQL Operators](#sql-operators), build an _expression literal_ with the `SQL.sqlExpression` method: + + ```swift + // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player + let defaultName = "O'Brien" + let displayName = SQL("IFNULL(\(Column("name")), \(defaultName))").sqlExpression + let request = Player.select(displayName.forKey("displayName"), Column("score")) + ``` + + Such expression literals allow you to build a reusable support library of SQL functions or operators that are missing from the query interface. For example, you can define a Swift `date` function: + + ```swift + func date(_ value: SQLSpecificExpressible) -> SQLExpression { + SQL("DATE(\(value))").sqlExpression + } + + // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' + let request = Player.filter(date(Column("createdAt")) == "2020-01-23") + ``` + + See the [Query Interface Organization] for more information about `SQLSpecificExpressible` and `SQLExpression`. + +3. `FROM ...`: only one table is supported here. You can not customize this SQL part. + +4. `JOIN ...`: joins are fully controlled by [Associations]. You can not customize this SQL part. + +5. `WHERE ...` + + The WHERE clause can be provided as raw SQL: + + ```swift + // SELECT * FROM player WHERE score >= 1000 + let request = Player.filter(sql: "score >= 1000") + + // SELECT * FROM player WHERE score >= 1000 + let minScore = 1000 + let request = Player.filter(sql: "score >= ?", arguments: [minScore]) + ``` + + The WHERE clause can be provided with [SQL Interpolation]: + + ```swift + // SELECT * FROM player WHERE score >= 1000 + let minScore = 1000 + let request = Player.filter(literal: "score >= \(minScore)") + ``` + + The WHERE clause can be provided with a mix of Swift and [SQL Interpolation]: + + ```swift + // SELECT * FROM player WHERE (score >= 1000) AND (team = 'red') + let minScore = 1000 + let scoreCondition: SQL = "\(Column("score")) >= \(minScore)" + let request = Player.filter(scoreCondition && Column("team") == "red") + ``` + + See `SELECT ...` above for more SQL Interpolation examples. + +6. `GROUP BY ...` + + The GROUP BY clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + +7. `HAVING ...` + + The HAVING clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + +8. `ORDER BY ...` + + The ORDER BY clause can be provided as raw SQL, SQL Interpolation, or a mix of Swift and SQL Interpolation, just as the selection and the WHERE clause (see above). + + In order to support the `desc` and `asc` query interface operators, and the `reversed()` query interface method, you must provide your orderings as _expression literals_ with the `SQL.sqlExpression` method: + + ```swift + // SELECT * FROM "player" + // ORDER BY (score + bonus) ASC, name DESC + let total = SQL("(score + bonus)").sqlExpression + let request = Player + .order(total.desc, Column("name")) + .reversed() + ``` + +9. `LIMIT ...`: use the `limit(_:offset:)` method. You can not customize this SQL part. ## Fetching from Requests @@ -5411,7 +5553,7 @@ try Player.customRequest().fetchAll(db) // [Player] - 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.17/Structs/AnyFetchRequest.html): a type-erased request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.18/Structs/AnyFetchRequest.html): a type-erased request. ## Joined Queries Support @@ -6715,7 +6857,7 @@ DatabaseRegion helps [ValueObservation] and [DatabaseRegionObservation] track ch 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](https://groue.github.io/GRDB.swift/docs/5.17/Structs/DatabaseRegion.html). +For more details, see the [reference](https://groue.github.io/GRDB.swift/docs/5.18/Structs/DatabaseRegion.html). #### The DatabaseRegionConvertible Protocol @@ -7051,6 +7193,42 @@ The `backup` method blocks the current thread until the destination database con When the source is a [database pool](#database-pools), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. +`Database` has an analogous `backup` method. + +```swift +let source: DatabaseQueue = ... // or DatabasePool +let destination: DatabaseQueue = ... // or DatabasePool +try source.write { sourceDb in + try destination.barrierWriteWithoutTransaction { destDb in + try sourceDb.backup(to: destDb) + } +} +``` + +This method allows for the choice of source and destination `Database` handles with which to backup the database. + +### Backup Progress Reporting + +The `backup` methods take optional `pagesPerStep` and `progress` parameters. Together these parameters can be used to track a database backup in progress and abort an incomplete backup. + +When `pagesPerStep` is provided, the database backup is performed in _steps_. At each step, no more than `pagesPerStep` database pages are copied from the source to the destination. The backup proceeds one step at a time until all pages have been copied. + +When a `progress` callback is provided, `progress` is called after every backup step, including the last. Even if a non-default `pagesPerStep` is specified or the backup is otherwise completed in a single step, the `progress` callback will be called. + +```swift +try source.backup( + to: destination, + pagesPerStep: ...) + { backupProgress in + print("Database backup progress:", backupProgress) + } +``` + +### Aborting an Incomplete Backup + +If a call to `progress` throws when `backupProgress.isComplete == false`, the backup will be aborted and the error rethrown. However, if a call to `progress` throws when `backupProgress.isComplete == true`, the backup is unaffected and the error is silently ignored. + +> :warning: **Warning**: Passing non-default values of `pagesPerStep` or `progress` to the backup methods is an advanced API intended to provide additional capabilities to expert users. GRDB's backup API provides a faithful, low-level wrapper to the underlying SQLite online backup API. GRDB's documentation is not a comprehensive substitute for the official SQLite [documentation of their backup API](https://www.sqlite.org/c3ref/backup_finish.html). ## Interrupt a Database @@ -8021,7 +8199,7 @@ When this is the case, there are two possible explanations: try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) ``` -For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.17/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). +For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.18/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp). @@ -8162,7 +8340,7 @@ This chapter has [moved](Documentation/Concurrency.md#database-snapshots). #### DatabaseWriter and DatabaseReader Protocols -This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.17/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.17/Protocols/DatabaseWriter.html). +This chapter was removed. See the references of [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.18/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.18/Protocols/DatabaseWriter.html). #### Asynchronous APIs @@ -8172,6 +8350,9 @@ This chapter has [moved](Documentation/Concurrency.md#synchronous-and-asynchrono This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-accesses). +### Adding support for missing SQL functions or operators + +This chapter was renamed to [Embedding SQL in Query Interface Requests]. [Associations]: Documentation/AssociationsBasics.md [Beyond FetchableRecord]: #beyond-fetchablerecord @@ -8185,6 +8366,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a [Column Names Coding Strategies]: #column-names-coding-strategies [Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies [Fetching from Requests]: #fetching-from-requests +[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests [Full-Text Search]: Documentation/FullTextSearch.md [Migrations]: Documentation/Migrations.md [The Implicit RowID Primary Key]: #the-implicit-rowid-primary-key @@ -8211,7 +8393,7 @@ This chapter has [moved](Documentation/Concurrency.md#safe-and-unsafe-database-a [Sharing a Database]: Documentation/SharingADatabase.md [FAQ]: #faq [Database Observation]: #database-changes-observation -[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.17/Structs/SQLRequest.html +[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.18/Structs/SQLRequest.html [SQL literal]: Documentation/SQLInterpolation.md#sql-literal [Identifiable]: https://developer.apple.com/documentation/swift/identifiable [Query Interface Organization]: Documentation/QueryInterfaceOrganization.md diff --git a/SQLiteCustom/src b/SQLiteCustom/src index ad1fed978..c3d119c87 160000 --- a/SQLiteCustom/src +++ b/SQLiteCustom/src @@ -1 +1 @@ -Subproject commit ad1fed978aef85290d8b2159fed8fa863fe21576 +Subproject commit c3d119c87f51a93882b38fd41b2119259d29f4b8 diff --git a/Scripts/swiftlint.sh b/Scripts/swiftlint.sh index 7781c40d8..02da30ab1 100755 --- a/Scripts/swiftlint.sh +++ b/Scripts/swiftlint.sh @@ -8,7 +8,7 @@ if test -d "/opt/homebrew/bin/"; then fi if which swiftlint >/dev/null; then - swiftlint --config ${SRCROOT}/Scripts/swiftlint.yml + swiftlint --config "${SRCROOT}/Scripts/swiftlint.yml" else echo "warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint" fi diff --git a/Support/Info.plist b/Support/Info.plist index aa81dc9d7..de73120d9 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 5.17.0 + 5.18.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index a6b4afd0f..633a620a4 100644 --- a/TODO.md +++ b/TODO.md @@ -23,6 +23,9 @@ - [ ] Grab all FTS tokens in a string - [ ] GRDB 6: decoding errors - [ ] GRDB 6: conflict resolution in persistence methods +- [ ] GRDB 6: UPSERT +- [ ] GRDB 6: support for RETURNING +- [ ] GRDB 6: allow mutating `update` (for timestamps) - [ ] Long run edition. Use case: user edits the database (CRUD) but the application wants to commmit and the end of the editing session. * Create an edition SQLite connection with an open transaction (a new kind of DatabaseWriter with a save() method) * All other writes will fail with SQLITE_BUSY. Unless they are schedules in a target dispatch queue which is paused during the edition. @@ -37,7 +40,6 @@ - [ ] Support for more kinds of joins: https://github.com/groue/GRDB.swift/issues/740 - [ ] HasAndBelongsToMany: https://github.com/groue/GRDB.swift/issues/711 - [ ] Support UNION https://github.com/groue/GRDB.swift/issues/671 (https://www.sqlite.org/lang_select.html#compound) -- [ ] request.exists(db) as an alternative to fetchOne(db) != nil. Can generate optimized SQL. - [ ] Measure the duration of transactions - [ ] Improve SQL generation for `Player.....fetchCount(db)`, especially with distinct. Try to avoid `SELECT COUNT(*) FROM (SELECT DISTINCT player.* ...)` - [ ] Alternative technique for custom SQLite builds: see the Podfile at https://github.com/CocoaPods/CocoaPods/issues/9104, and https://github.com/clemensg/sqlite3pod @@ -52,7 +54,6 @@ - [ ] CASE x WHEN w1 THEN r1 WHEN w2 THEN r2 ELSE r3 END https://www.sqlite.org/lang_expr.html - [ ] Allow concurrent reads from a snapshot - [ ] Check https://sqlite.org/sqlar.html -- [ ] FTS: prefix queries - [ ] More schema alterations - [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 7adce2aec..ae433327c 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -443,6 +443,8 @@ 5641A1BD24A540D6004967E1 /* PublisherExpectation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5641A19F24A540D6004967E1 /* PublisherExpectation.swift */; }; 564A2026226B89E1001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; + 565A27CC27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; }; + 565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -674,6 +676,7 @@ 564A1F22226B876D001F64F1 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 565A27CB27871FFF00659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTestsEncrypted.framework; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -799,6 +802,7 @@ 56419CAD24A54054004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419D5824A54061004967E1 /* AssociationRowScopeSearchTests.swift */, 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 565A27CB27871FFF00659A62 /* BackupTestCase.swift */, 56419CD424A54057004967E1 /* CGFloatTests.swift */, 56419CD924A54058004967E1 /* ColumnExpressionTests.swift */, 56419D5424A54061004967E1 /* ColumnInfoTests.swift */, @@ -1213,6 +1217,7 @@ 56419E1F24A54062004967E1 /* ValueObservationRecorderTests.swift in Sources */, 56419DA124A54062004967E1 /* EncryptionTests.swift in Sources */, 56419DF124A54062004967E1 /* FoundationNSNullTests.swift in Sources */, + 565A27CC27871FFF00659A62 /* BackupTestCase.swift in Sources */, 56419EEB24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */, 56419E8124A54063004967E1 /* DatabaseReaderTests.swift in Sources */, 56419EDD24A54063004967E1 /* TableDefinitionTests.swift in Sources */, @@ -1437,6 +1442,7 @@ 56419E2024A54062004967E1 /* ValueObservationRecorderTests.swift in Sources */, 56419DA224A54062004967E1 /* EncryptionTests.swift in Sources */, 56419DF224A54062004967E1 /* FoundationNSNullTests.swift in Sources */, + 565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */, 56419EEC24A54063004967E1 /* RecordPersistenceConflictPolicy.swift in Sources */, 56419E8224A54063004967E1 /* DatabaseReaderTests.swift in Sources */, 56419EDE24A54063004967E1 /* TableDefinitionTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index 61f62b11b..1d12cd7c6 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -445,6 +445,8 @@ 564A2151226B8E18001F64F1 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 564A1F6F226B89D6001F64F1 /* Betty.jpeg */; }; 564A2159226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; 564A215A226C8F25001F64F1 /* db.SQLCipher3 in Resources */ = {isa = PBXBuildFile; fileRef = 564A2158226C8F24001F64F1 /* db.SQLCipher3 */; }; + 565A27C927871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; }; + 565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -677,6 +679,7 @@ 564A1F6F226B89D6001F64F1 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 564A2156226B8E18001F64F1 /* GRDBTestsEncrypted.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTestsEncrypted.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564A2158226C8F24001F64F1 /* db.SQLCipher3 */ = {isa = PBXFileReference; lastKnownFileType = file; path = db.SQLCipher3; sourceTree = SOURCE_ROOT; }; + 565A27C827871FE500659A62 /* BackupTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BackupTestCase.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_GRDBTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 6A4788C0F815F6C5E4EBDE12 /* Pods-GRDBTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.debug.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.debug.xcconfig"; sourceTree = ""; }; @@ -803,6 +806,7 @@ 56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */, 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 565A27C827871FE500659A62 /* BackupTestCase.swift */, 56419F6B24A5409A004967E1 /* CGFloatTests.swift */, 56419F6524A54099004967E1 /* ColumnExpressionTests.swift */, 56419F9324A5409D004967E1 /* ColumnInfoTests.swift */, @@ -1219,6 +1223,7 @@ 5641A03624A540A1004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 5641A0AE24A540A1004967E1 /* DatabaseConfigurationTests.swift in Sources */, 5641A0CA24A540A1004967E1 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565A27C927871FE500659A62 /* BackupTestCase.swift in Sources */, 56419FD624A540A1004967E1 /* DatabaseRegionTests.swift in Sources */, 5641A0A824A540A1004967E1 /* JoinSupportTests.swift in Sources */, 5641A0D424A540A1004967E1 /* FoundationUUIDTests.swift in Sources */, @@ -1443,6 +1448,7 @@ 5641A03724A540A1004967E1 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 5641A0AF24A540A1004967E1 /* DatabaseConfigurationTests.swift in Sources */, 5641A0CB24A540A1004967E1 /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, + 565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */, 56419FD724A540A1004967E1 /* DatabaseRegionTests.swift in Sources */, 5641A0A924A540A1004967E1 /* JoinSupportTests.swift in Sources */, 5641A0D524A540A1004967E1 /* FoundationUUIDTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 152c6aa68..03aceea2e 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -2057,7 +2057,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { // Existence check is performed on the primary key. let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in - try db.create(table: "author", withoutRowID: true) { t in + try db.create(table: "author", options: [.withoutRowID]) { t in t.column("a", .text).notNull() t.column("b", .text).notNull() t.primaryKey(["a", "b"]) diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift new file mode 100644 index 000000000..f4474f9b9 --- /dev/null +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -0,0 +1,142 @@ +import XCTest +@testable import GRDB + +class BackupTestCase: GRDBTestCase { + + // A "user" error simply for testing purposes + private class AbandonBackupError: Error {} + + private func setupBackupSource(_ writer: DatabaseWriter) throws -> Int { + try writer.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute(sql: "INSERT INTO items (id) VALUES (0)") + } + + let pageCount: Int = try writer.read { db in + try Int.fetchOne(db, sql: "PRAGMA page_count")! + } + + // pageCount must be greater than 1 to allow for incremental backup testing + XCTAssertGreaterThan(pageCount, 1) + + return pageCount + } + + private func setupBackupDestination(_ writer: DatabaseWriter) throws { + try writer.write { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") + try db.execute(sql: "INSERT INTO items (id) VALUES (1)") + } + } + + func testDatabaseWriterBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + let sourceDbPageCount = try setupBackupSource(source) + try setupBackupDestination(destination) + + XCTAssertThrowsError( + try source.backup(to: destination, pagesPerStep: 1) { progress in + XCTAssertLessThan(progress.completedPageCount, progress.totalPageCount) + XCTAssertFalse(progress.isCompleted) + throw AbandonBackupError() + } + ) + + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) + } + + var progressCount: Int = 1 + var isCompleted: Bool = false + try source.backup(to: destination, pagesPerStep: 1) { progress in + let expectedCompletedPages = progressCount + XCTAssertEqual(expectedCompletedPages, progress.completedPageCount) + if progress.completedPageCount != progress.totalPageCount { + progressCount += 1 + } + if progress.isCompleted { + isCompleted = true + // Should not re-throw + throw AbandonBackupError() + } + } + + XCTAssertEqual(sourceDbPageCount, progressCount) + XCTAssertTrue(isCompleted) + + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 0) + } + + try source.write { db in + try db.execute(sql: "DROP TABLE items") + } + + try source.backup(to: destination) + + try destination.read { db in + XCTAssertFalse(try db.tableExists("items")) + } + } + + func testDatabaseBackup(from source: DatabaseWriter, to destination: DatabaseWriter) throws { + let sourceDbPageCount = try setupBackupSource(source) + try setupBackupDestination(destination) + + try source.write { sourceDb in + try destination.barrierWriteWithoutTransaction { destDb in + XCTAssertThrowsError( + try sourceDb.backup(to: destDb, pagesPerStep: 1) { progress in + XCTAssertLessThan(progress.completedPageCount, progress.totalPageCount) + throw AbandonBackupError() + } + ) + } + } + + // Assert that the items table is as it was before the backup was abandoned. + // Is this a valid assertion? + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) + } + + try source.write { dbSource in + try destination.barrierWriteWithoutTransaction { dbDest in + var progressCount: Int = 1 + var isCompleted: Bool = false + try dbSource.backup(to: dbDest, pagesPerStep: 1) { progress in + let expectedCompletedPages = progressCount + XCTAssertEqual(expectedCompletedPages, progress.completedPageCount) + if progress.completedPageCount != progress.totalPageCount { + progressCount += 1 + } + if progress.isCompleted { + isCompleted = true + // Should not re-throw + throw AbandonBackupError() + } + } + + XCTAssertEqual(sourceDbPageCount, progressCount) + XCTAssertTrue(isCompleted) + } + } + + try destination.read { db in + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) + XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 0) + } + + try source.write { db in + try db.execute(sql: "DROP TABLE items") + } + + try source.backup(to: destination) + + try destination.read { db in + XCTAssertFalse(try db.tableExists("items")) + } + } +} diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index ac28ae801..eb1bdddcf 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -230,4 +230,48 @@ class ColumnExpressionTests: GRDBTestCase { try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"") } } + + func testDetachedColumn() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "t") { t in t.column("a") } + + // Regular columns are qualified + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .order(Column("a")) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom".* FROM "t" "custom" ORDER BY "custom"."a" + """) + } + + // Detached columns are NOT qualified + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .order(Column("a").detached) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom".* FROM "t" "custom" ORDER BY "a" + """) + } + + // Detached columns are quoted + do { + let alias = TableAlias(name: "custom") + let request = Table("t") + .aliased(alias) + .select(Column("a").forKey("order")) + .order(Column("order").detached) + let sql = try request.makePreparedRequest(db).statement.sql + XCTAssertEqual(sql, """ + SELECT "custom"."a" AS "order" FROM "t" "custom" ORDER BY "order" + """) + } + } + } } diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 4799daf1e..31de2168c 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -63,13 +63,13 @@ class ColumnInfoTests: GRDBTestCase { XCTAssertEqual(columns[3].name, "d") XCTAssertEqual(columns[3].isNotNull, false) - XCTAssertEqual(columns[3].type, "int") + XCTAssertEqual(columns[3].type.uppercased(), "INT") // "int" or "INT" depending of SQLite version XCTAssertEqual(columns[3].primaryKeyIndex, 0) XCTAssertEqual(columns[3].defaultValueSQL, "NULL") XCTAssertEqual(columns[4].name, "e") XCTAssertEqual(columns[4].isNotNull, true) - XCTAssertEqual(columns[4].type, "Text") + XCTAssertEqual(columns[4].type.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version XCTAssertEqual(columns[4].primaryKeyIndex, 0) XCTAssertEqual(columns[4].defaultValueSQL, "'foo'") @@ -175,4 +175,25 @@ class ColumnInfoTests: GRDBTestCase { } #endif } + + // Regression test for https://github.com/groue/GRDB.swift/issues/1124 + // See also https://sqlite.org/forum/forumpost/721da02ba2 + func testIssue1124() throws { + class Observer: TransactionObserver { + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidCommit(_ db: Database) { } + func databaseDidRollback(_ db: Database) { } + } + let dbQueue = try makeDatabaseQueue() + dbQueue.add(transactionObserver: Observer(), extent: .databaseLifetime) + try dbQueue.write { db in + try db.execute(sql: """ + CREATE VIRTUAL TABLE t1 USING rtree(id,minX,maxX,minY,maxY); + CREATE TABLE t2 (a); + ALTER TABLE t2 RENAME TO t3; + """) + _ = try db.columns(in: "t1") + } + } } diff --git a/Tests/GRDBTests/DatabasePoolBackupTests.swift b/Tests/GRDBTests/DatabasePoolBackupTests.swift index c59afd57d..12eaac17e 100644 --- a/Tests/GRDBTests/DatabasePoolBackupTests.swift +++ b/Tests/GRDBTests/DatabasePoolBackupTests.swift @@ -1,34 +1,18 @@ -import XCTest -@testable import GRDB +import GRDB -class DatabasePoolBackupTests: GRDBTestCase { - - func testBackup() throws { +class DatabasePoolBackupTests: BackupTestCase { + + func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) - let destination = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) - - try source.write { db in - try db.execute(sql: "CREATE TABLE item (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO item (id) VALUES (NULL)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) - } - - try source.backup(to: destination) - - try destination.read { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM item")!, 1) - } - - try source.write { db in - try db.execute(sql: "DROP TABLE item") - } - - try source.backup(to: destination) - - try destination.read { db in - XCTAssertFalse(try db.tableExists("item")) - } + let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseWriterBackup(from: source, to: destination) + } + + func testDatabaseBackup() throws { + let source: DatabaseWriter = try makeDatabasePool(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabasePool(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseBackup(from: source, to: destination) } // TODO: fix flaky test diff --git a/Tests/GRDBTests/DatabaseQueueBackupTests.swift b/Tests/GRDBTests/DatabaseQueueBackupTests.swift index 8cdde038b..2af8fc5dc 100644 --- a/Tests/GRDBTests/DatabaseQueueBackupTests.swift +++ b/Tests/GRDBTests/DatabaseQueueBackupTests.swift @@ -1,33 +1,17 @@ -import XCTest import GRDB -class DatabaseQueueBackupTests: GRDBTestCase { - - func testBackup() throws { +class DatabaseQueueBackupTests: BackupTestCase { + + func testDatabaseWriterBackup() throws { // SQLCipher can't backup encrypted databases: use a pristine Configuration - let source = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) - let destination = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) - - try source.inDatabase { db in - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - try db.execute(sql: "INSERT INTO items (id) VALUES (NULL)") - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) - } - - try source.backup(to: destination) - - try destination.inDatabase { db in - XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM items")!, 1) - } - - try source.inDatabase { db in - try db.execute(sql: "DROP TABLE items") - } - - try source.backup(to: destination) - - try destination.inDatabase { db in - XCTAssertFalse(try db.tableExists("items")) - } + let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseWriterBackup(from: source, to: destination) + } + + func testDatabaseBackup() throws { + let source: DatabaseWriter = try makeDatabaseQueue(filename: "source.sqlite", configuration: Configuration()) + let destination: DatabaseWriter = try makeDatabaseQueue(filename: "destination.sqlite", configuration: Configuration()) + try testDatabaseBackup(from: source, to: destination) } } diff --git a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift index d4f5050ba..9c2f87f95 100644 --- a/Tests/GRDBTests/SQLExpressionIsConstantTests.swift +++ b/Tests/GRDBTests/SQLExpressionIsConstantTests.swift @@ -27,7 +27,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] * "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] + alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual([alias[Column("a")], "foo".databaseValue].joined(operator: .concat).column(db, for: alias, acceptsBijection: false), nil) @@ -39,7 +39,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { // SQLExpressionBinary try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] - "foo".databaseValue).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: false), nil) try XCTAssertEqual((alias[Column("a")] - alias[Column("b")]).column(db, for: alias, acceptsBijection: true), nil) try XCTAssertEqual((alias[Column("a")] < "foo".databaseValue).column(db, for: alias, acceptsBijection: false), nil) @@ -51,7 +51,7 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual(alias[Column("a")].collating(.binary).column(db, for: alias, acceptsBijection: false), "a") try XCTAssertEqual(alias[Column("a")].collating(.binary).column(db, for: alias, acceptsBijection: true), "a") try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: false), nil) - try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: true), "a") + try XCTAssertEqual((alias[Column("a")] + "foo".databaseValue).collating(.binary).column(db, for: alias, acceptsBijection: true), nil) // SQLExpressionContains try XCTAssertEqual([1, 2, 3].contains(alias[Column("a")]).column(db, for: alias, acceptsBijection: false), nil) @@ -169,8 +169,8 @@ class SQLExpressionIsConstantTests: GRDBTestCase { try XCTAssertEqual((1 == alias[Column("a")]).identifyingColums(db, for: alias), ["a"]) try XCTAssertEqual((-alias[Column("a")] == 1).identifyingColums(db, for: alias), ["a"]) try XCTAssertEqual(((alias[Column("a")] * 2) == 1).identifyingColums(db, for: alias), []) - try XCTAssertEqual(((alias[Column("a")] + 2) == 1).identifyingColums(db, for: alias), ["a"]) - try XCTAssertEqual(((alias[Column("a")] - 2) == 1).identifyingColums(db, for: alias), ["a"]) + try XCTAssertEqual(((alias[Column("a")] + 2) == 1).identifyingColums(db, for: alias), []) + try XCTAssertEqual(((alias[Column("a")] - 2) == 1).identifyingColums(db, for: alias), []) try XCTAssertEqual((alias[SQLExpression.fastPrimaryKey] == 1).identifyingColums(db, for: alias), ["id"]) try XCTAssertEqual((alias[Column("a")] == alias[Column("b")]).identifyingColums(db, for: alias), []) try XCTAssertEqual((TableAlias()[Column("a")] == nil).identifyingColums(db, for: alias), []) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 9b8d146ce..f7b59facf 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -33,6 +33,46 @@ class TableDefinitionTests: GRDBTestCase { ) WITHOUT ROWID """) } + + try dbQueue.inDatabase { db in + try db.create(table: "test2", options: [.temporary, .ifNotExists, .withoutRowID]) { t in + t.column("id", .integer).primaryKey() + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY TABLE IF NOT EXISTS "test2" (\ + "id" INTEGER PRIMARY KEY\ + ) WITHOUT ROWID + """) + } + +#if GRDBCUSTOMSQLITE + try dbQueue.inDatabase { db in + try db.create(table: "test3", options: [.strict, .withoutRowID]) { t in + t.column("id", .integer).primaryKey() + t.column("a", .integer) + t.column("b", .real) + t.column("c", .text) + t.column("d", .blob) + t.column("e", .any) + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test3" (\ + "id" INTEGER PRIMARY KEY, \ + "a" INTEGER, \ + "b" REAL, \ + "c" TEXT, \ + "d" BLOB, \ + "e" ANY\ + ) STRICT, WITHOUT ROWID + """) + + do { + try db.execute(sql: "INSERT INTO test3 (id, a) VALUES (1, 'foo')") + XCTFail("Expected DatabaseError.SQLITE_CONSTRAINT_DATATYPE") + } catch DatabaseError.SQLITE_CONSTRAINT_DATATYPE { + } + } +#endif } func testColumnLiteral() throws { @@ -160,7 +200,7 @@ class TableDefinitionTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in sqlQueries.removeAll() - try db.create(table: "test", ifNotExists: true) { t in + try db.create(table: "test", options: [.ifNotExists]) { t in t.column("a", .integer).indexed() t.column("b", .integer).indexed() } @@ -663,8 +703,11 @@ class TableDefinitionTests: GRDBTestCase { try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\")") + try db.create(index: "test_on_a_b_2", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists]) + assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b_2\" ON \"test\"(\"a\", \"b\")") + // Sanity check - XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b"]) + XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2"]) } } @@ -677,7 +720,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("b", .text) } - try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], unique: true, ifNotExists: true, condition: Column("a") == 1) + try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists], condition: Column("a") == 1) assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1") // Sanity check diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index d1b5a2965..07e60e613 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -312,15 +312,6 @@ class TableRecordDeleteTests: GRDBTestCase { GROUP BY "id") """) } - do { - try Player.all().group(Column.rowID + 1).deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, """ - DELETE FROM "player" WHERE "id" IN (\ - SELECT "id" \ - FROM "player" \ - GROUP BY "rowid" + 1) - """) - } do { try Player.all().group(-Column("id")).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, """