From 4057e3be074d7d5c6f2f8df02537642e87c3cfda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1szl=C3=B3=20Kustra?= Date: Fri, 23 Jun 2023 16:21:58 +0200 Subject: [PATCH 01/28] Use cross-platform ProcessInfo instance property --- GRDB/Migration/DatabaseMigrator.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 2ea85acf6..fe3d84b5f 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -446,7 +446,7 @@ public struct DatabaseMigrator { // // So let's create a "regular" temporary database: let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent(ProcessInfo().globallyUniqueString) + .appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString) defer { try? FileManager().removeItem(at: tmpURL) } From 788887a2b856c178bd320b0673e1f5da9c5f2a8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1szl=C3=B3=20Kustra?= Date: Fri, 23 Jun 2023 16:22:57 +0200 Subject: [PATCH 02/28] Remove selector-based NotificationCenter calls on Linux --- GRDB/Core/DatabasePool.swift | 40 ++++++++++++++++------------------ GRDB/Core/DatabaseQueue.swift | 41 ++++++++++++++++++----------------- 2 files changed, 40 insertions(+), 41 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 1a95430ce..602cea60b 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -13,6 +13,9 @@ public final class DatabasePool { @LockedBox var databaseSnapshotCount = 0 + /// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers. + private var suspensionObservers: [NSObjectProtocol] = [] + // MARK: - Database Information public var configuration: Configuration { @@ -121,6 +124,9 @@ public final class DatabasePool { } deinit { + // Remove block-based Notification observers. + suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:)) + // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error @@ -169,7 +175,7 @@ public final class DatabasePool { } } -// @unchecked because of databaseSnapshotCount and readerPool +// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers extension DatabasePool: @unchecked Sendable { } extension DatabasePool { @@ -345,29 +351,21 @@ extension DatabasePool: DatabaseReader { private func setupSuspension() { if configuration.observesSuspensionNotifications { let center = NotificationCenter.default - center.addObserver( - self, - selector: #selector(DatabasePool.suspend(_:)), - name: Database.suspendNotification, - object: nil) - center.addObserver( - self, - selector: #selector(DatabasePool.resume(_:)), - name: Database.resumeNotification, - object: nil) + suspensionObservers.append(center.addObserver( + forName: Database.suspendNotification, + object: nil, + queue: nil, + using: { [weak self] _ in self?.suspend() } + )) + suspensionObservers.append(center.addObserver( + forName: Database.resumeNotification, + object: nil, + queue: nil, + using: { [weak self] _ in self?.resume() } + )) } } - @objc - private func suspend(_ notification: Notification) { - suspend() - } - - @objc - private func resume(_ notification: Notification) { - resume() - } - // MARK: - Reading from Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 372126391..9912e05c0 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -7,6 +7,9 @@ import UIKit public final class DatabaseQueue { private let writer: SerializedDatabase + /// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers. + private var suspensionObservers: [NSObjectProtocol] = [] + // MARK: - Configuration public var configuration: Configuration { @@ -100,6 +103,9 @@ public final class DatabaseQueue { } deinit { + // Remove block-based Notification observers. + suspensionObservers.forEach(NotificationCenter.default.removeObserver(_:)) + // Undo job done in setupMemoryManagement() // // https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error @@ -108,6 +114,9 @@ public final class DatabaseQueue { } } +// @unchecked because of suspensionObservers +extension DatabaseQueue: @unchecked Sendable { } + extension DatabaseQueue { // MARK: - Memory management @@ -189,29 +198,21 @@ extension DatabaseQueue: DatabaseReader { private func setupSuspension() { if configuration.observesSuspensionNotifications { let center = NotificationCenter.default - center.addObserver( - self, - selector: #selector(DatabaseQueue.suspend(_:)), - name: Database.suspendNotification, - object: nil) - center.addObserver( - self, - selector: #selector(DatabaseQueue.resume(_:)), - name: Database.resumeNotification, - object: nil) + suspensionObservers.append(center.addObserver( + forName: Database.suspendNotification, + object: nil, + queue: nil, + using: { [weak self] _ in self?.suspend() } + )) + suspensionObservers.append(center.addObserver( + forName: Database.resumeNotification, + object: nil, + queue: nil, + using: { [weak self] _ in self?.resume() } + )) } } - @objc - private func suspend(_ notification: Notification) { - suspend() - } - - @objc - private func resume(_ notification: Notification) { - resume() - } - // MARK: - Reading from Database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails From 25b49cba01738fb2569a4ed825b956466417878a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1szl=C3=B3=20Kustra?= Date: Thu, 29 Jun 2023 16:13:19 +0200 Subject: [PATCH 03/28] Add autoreleasepool shim for Linux --- GRDB/Utils/Utils.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index b186d43ae..90e3ca557 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -190,3 +190,7 @@ extension NSLocking { sideEffect?() } } + +#if !canImport(ObjectiveC) +@inlinable func autoreleasepool(invoking body: () throws -> Result) rethrows -> Result { try body() } +#endif From 47d8ef4358d2e6d75e58ef344f10b32c0c6e03e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1szl=C3=B3=20Kustra?= Date: Thu, 29 Jun 2023 16:20:23 +0200 Subject: [PATCH 04/28] Fix the Linux version of sqlite3_trace for SQLite 3.19.3 --- GRDB/Core/Database.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 739124901..86b800328 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -861,7 +861,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib if options.isEmpty || trace == nil { #if os(Linux) - sqlite3_trace(sqliteConnection, nil) + sqlite3_trace(sqliteConnection, nil, nil) #else sqlite3_trace_v2(sqliteConnection, 0, nil, nil) #endif From 59c41c97afa0d1e84bd46cf404ebbc114398dc73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 10:58:09 +0200 Subject: [PATCH 05/28] Clarify the prevention of database access from TransactionObserver callbacks --- GRDB/Core/TransactionObserver.swift | 6 ++++-- GRDB/Documentation.docc/Extension/TransactionObserver.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index e0d18226a..8cddd2984 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -778,7 +778,8 @@ public protocol TransactionObserver: AnyObject { /// - note: The event is only valid for the duration of this method call. /// If you need to keep it longer, store a copy: `event.copy()`. /// - /// - precondition: This method must not access the database. + /// - precondition: This method must not access the observed writer + /// database connection. func databaseDidChange(with event: DatabaseEvent) /// Called when a transaction is about to be committed. @@ -786,7 +787,8 @@ public protocol TransactionObserver: AnyObject { /// The transaction observer has an opportunity to rollback pending changes /// by throwing an error from this method. /// - /// - precondition: This method must not access the database. + /// - precondition: This method must not access the observed writer + /// database connection. /// - throws: The eventual error that rollbacks pending changes. func databaseWillCommit() throws diff --git a/GRDB/Documentation.docc/Extension/TransactionObserver.md b/GRDB/Documentation.docc/Extension/TransactionObserver.md index feaf9f9c2..026833eac 100644 --- a/GRDB/Documentation.docc/Extension/TransactionObserver.md +++ b/GRDB/Documentation.docc/Extension/TransactionObserver.md @@ -97,7 +97,7 @@ do { - Note: All callbacks are called in the writer dispatch queue, and serialized with all database updates. -- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not touch the SQLite database. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument. +- Note: The `databaseDidChange` and `databaseWillCommit` callbacks must not access the observed writer database connection in any way. This limitation does not apply to `databaseDidCommit` and `databaseDidRollback` which can use their database argument. ## Filtering Database Events From 66826288d6ccf8fb39ac2ba30e615a1f469f04e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 12:30:24 +0200 Subject: [PATCH 06/28] Upgrade custom SQLite builds to 3.42.0 --- Documentation/CustomSQLiteBuilds.md | 2 +- SQLiteCustom/src | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index 7b1dc090b..2aa955f5b 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.39.3](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.42.0](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](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver). diff --git a/SQLiteCustom/src b/SQLiteCustom/src index 95bfe16bb..59f4dc65f 160000 --- a/SQLiteCustom/src +++ b/SQLiteCustom/src @@ -1 +1 @@ -Subproject commit 95bfe16bb870450004da151f81394cd5b6a0de8c +Subproject commit 59f4dc65f053482934ad184a88f2394a7dfc2f7b From 2bb904775fe2a1dcae8639223eab2b6664b07d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 12:38:41 +0200 Subject: [PATCH 07/28] CHANGELOG --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index baed700a1..06d781572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,6 +113,10 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## Next Release + +- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) Upgrade custom SQLite builds to 3.42.0 + ## 6.15.1 Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1) From c9d8ce57a774f16bae0816e26be6c0d2a55d93d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 12:44:18 +0200 Subject: [PATCH 08/28] Trigger CI on custom SQLite upgrade --- .github/workflows/CI.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index cbb4b1814..35d8640fb 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -13,6 +13,7 @@ on: - '.github/workflows/**' - 'Makefile' - 'Package.swift' + - 'SQLiteCustom/src' pull_request: paths: - 'GRDB/**' @@ -20,6 +21,7 @@ on: - '.github/workflows/**' - 'Makefile' - 'Package.swift' + - 'SQLiteCustom/src' concurrency: group: ${{ github.ref_name }} From 1577825585409aec1aba147454857b9df59af772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 13:23:08 +0200 Subject: [PATCH 09/28] GitHub CI: test Xcode 14.3.1, macOS 13 --- .github/workflows/CI.yml | 56 +++++++++++++++++++++++++--------------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 35d8640fb..066f4b8bd 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -40,24 +40,32 @@ jobs: fail-fast: false matrix: include: + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + destination: "platform=macOS" + name: "macOS" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + destination: "OS=16.4,name=iPhone 14 Pro" + name: "iOS" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + destination: "OS=16.4,name=Apple TV" + name: "tvOS" - xcode: "Xcode_14.2.app" - runsOn: macOS-12 + runsOn: macOS-13 destination: "platform=macOS" name: "macOS" - xcode: "Xcode_14.2.app" - runsOn: macOS-12 + runsOn: macOS-13 destination: "OS=16.2,name=iPhone 14" name: "iOS" - - xcode: "Xcode_14.2.app" - runsOn: macOS-12 - destination: "OS=16.1,name=Apple TV" - name: "tvOS" - xcode: "Xcode_14.1.app" - runsOn: macOS-12 + runsOn: macOS-13 destination: "platform=macOS" name: "macOS" - xcode: "Xcode_14.1.app" - runsOn: macOS-12 + runsOn: macOS-13 destination: "OS=16.1,name=iPhone 14" name: "iOS" - xcode: "Xcode_14.0.1.app" @@ -82,11 +90,14 @@ jobs: fail-fast: false matrix: include: + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + name: "Xcode 14.3.1" - xcode: "Xcode_14.2.app" - runsOn: macOS-12 + runsOn: macOS-13 name: "Xcode 14.2" - xcode: "Xcode_14.1.app" - runsOn: macOS-12 + runsOn: macOS-13 name: "Xcode 14.1" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 @@ -105,9 +116,12 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.2.app" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + name: "Xcode 14.3.1" + - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 - name: "Xcode 14.2" + name: "Xcode 14.0.1" steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} @@ -122,9 +136,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.2.app" - runsOn: macOS-12 - name: "Xcode 14.2" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + name: "Xcode 14.3.1" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 name: "Xcode 14.0.1" @@ -142,9 +156,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.2.app" - runsOn: macOS-12 - name: "Xcode 14.2" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + name: "Xcode 14.3.1" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 name: "Xcode 14.0.1" @@ -162,9 +176,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.2.app" - runsOn: macOS-12 - name: "Xcode 14.2" + - xcode: "Xcode_14.3.1.app" + runsOn: macOS-13 + name: "Xcode 14.3.1" - xcode: "Xcode_14.0.1.app" runsOn: macOS-12 name: "Xcode 14.0.1" From 2bd080799faa8f96b2a15334e3841dbc401603fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 14:08:32 +0200 Subject: [PATCH 10/28] Test universal xcframework --- .github/workflows/CI.yml | 2 +- Makefile | 41 ++++++++++++++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 066f4b8bd..443234b51 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -185,5 +185,5 @@ jobs: steps: - uses: actions/checkout@v3 - name: ${{ matrix.name }} - run: make test_archive_GRDBOSX_xcframework + run: make test_universal_xcframework \ No newline at end of file diff --git a/Makefile b/Makefile index a794a98b2..4d5da809e 100644 --- a/Makefile +++ b/Makefile @@ -75,7 +75,7 @@ test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framew test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framework_GRDBtvOS test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted -test_archive: test_archive_GRDBOSX_xcframework +test_archive: test_universal_xcframework test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint test_CocoaPodsLint: test_CocoaPodsLint_GRDB test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo @@ -219,22 +219,51 @@ test_SPM: $(SWIFT) build -c release set -o pipefail && $(SWIFT) test --parallel -test_archive_GRDBOSX_xcframework: +test_universal_xcframework: rm -rf Tests/products mkdir Tests/products $(XCODEBUILD) archive \ -project GRDB.xcodeproj \ -scheme GRDB \ - -configuration Release \ + -destination "generic/platform=iOS" \ + OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ + GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ + -archivePath "$(PWD)/Tests/products/GRDB-iOS.xcarchive" \ + SKIP_INSTALL=NO \ + BUILD_LIBRARY_FOR_DISTRIBUTION=YES + $(XCODEBUILD) archive \ + -project GRDB.xcodeproj \ + -scheme GRDB \ + -destination "generic/platform=iOS Simulator" \ + OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ + GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ + -archivePath "$(PWD)/Tests/products/GRDB-iOS_Simulator.xcarchive" \ + SKIP_INSTALL=NO \ + BUILD_LIBRARY_FOR_DISTRIBUTION=YES + $(XCODEBUILD) archive \ + -project GRDB.xcodeproj \ + -scheme GRDB \ -destination "generic/platform=macOS" \ OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ - -archivePath "$(PWD)/Tests/products/GRDB.xcarchive" \ + -archivePath "$(PWD)/Tests/products/GRDB-macOS.xcarchive" \ + SKIP_INSTALL=NO \ + BUILD_LIBRARY_FOR_DISTRIBUTION=YES + $(XCODEBUILD) archive \ + -project GRDB.xcodeproj \ + -scheme GRDB \ + -destination "generic/platform=macOS,variant=Mac Catalyst" \ + OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \ + GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \ + -archivePath "$(PWD)/Tests/products/GRDB-Mac_Catalyst.xcarchive" \ SKIP_INSTALL=NO \ BUILD_LIBRARY_FOR_DISTRIBUTION=YES $(XCODEBUILD) -create-xcframework \ - -framework '$(PWD)/Tests/products/GRDB.xcarchive/Products/Library/Frameworks/GRDB.framework' \ - -output '$(PWD)/Tests/products/GRDB.xcframework' + -archive '$(PWD)/Tests/products/GRDB-iOS.xcarchive' -framework GRDB.framework \ + -archive '$(PWD)/Tests/products/GRDB-iOS_Simulator.xcarchive' -framework GRDB.framework \ + -archive '$(PWD)/Tests/products/GRDB-macOS.xcarchive' -framework GRDB.framework \ + -archive '$(PWD)/Tests/products/GRDB-Mac_Catalyst.xcarchive' -framework GRDB.framework \ + -output '$(PWD)/Tests/products/GRDB.xcframework' test_install_manual: $(XCODEBUILD) \ From 5fca5fdabfaa69a12762b7c1f61ebdf0751cad9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 14:12:12 +0200 Subject: [PATCH 11/28] Force MACOSX_DEPLOYMENT_TARGET on SQLCipher CocoaPods tests Workaround for https://github.com/CocoaPods/CocoaPods/issues/11839 --- Tests/CocoaPods/SQLCipher3/Podfile | 3 +++ Tests/CocoaPods/SQLCipher4/Podfile | 3 +++ 2 files changed, 6 insertions(+) diff --git a/Tests/CocoaPods/SQLCipher3/Podfile b/Tests/CocoaPods/SQLCipher3/Podfile index c8066b3ae..6d99439cf 100644 --- a/Tests/CocoaPods/SQLCipher3/Podfile +++ b/Tests/CocoaPods/SQLCipher3/Podfile @@ -17,6 +17,9 @@ end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| + # Workaround for Xcode 14.3+ + # https://github.com/CocoaPods/CocoaPods/issues/11839 + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13' config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end diff --git a/Tests/CocoaPods/SQLCipher4/Podfile b/Tests/CocoaPods/SQLCipher4/Podfile index d8cd6ce44..008d26d86 100644 --- a/Tests/CocoaPods/SQLCipher4/Podfile +++ b/Tests/CocoaPods/SQLCipher4/Podfile @@ -17,6 +17,9 @@ end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| + # Workaround for Xcode 14.3+ + # https://github.com/CocoaPods/CocoaPods/issues/11839 + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13' config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end From 7d487039868565f5fbb3dda2f0f3412cac0b574f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 14:53:54 +0200 Subject: [PATCH 12/28] CHANGELOG --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 06d781572..f3faad82b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -116,6 +116,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release - **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) Upgrade custom SQLite builds to 3.42.0 +- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) GitHub CI: test Xcode 14.3.1, macOS 13 ## 6.15.1 From f113963d31e7f1cb8f5bacbb5f5c6517668f0ba5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1szl=C3=B3=20Kustra?= Date: Fri, 7 Jul 2023 11:05:17 +0200 Subject: [PATCH 13/28] Remove obsolete SQLite trace logic, as min SQLite version is 3.19.3 --- GRDB/Core/Database.swift | 97 ++++++++++------------------------------ 1 file changed, 24 insertions(+), 73 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 86b800328..829d2de16 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -860,31 +860,16 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib self.trace = trace if options.isEmpty || trace == nil { - #if os(Linux) - sqlite3_trace(sqliteConnection, nil, nil) - #else sqlite3_trace_v2(sqliteConnection, 0, nil, nil) - #endif return } - // sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0 - // http://www.sqlite.org/changes.html#version_3_14 - #if os(Linux) - let dbPointer = Unmanaged.passUnretained(self).toOpaque() - sqlite3_trace(sqliteConnection, { (dbPointer, sql) in - guard let sql = sql.map(String.init(cString:)) else { return } - let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() - db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql)))) - }, dbPointer) - #else let dbPointer = Unmanaged.passUnretained(self).toOpaque() sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql) return SQLITE_OK }, dbPointer) - #endif } // Precondition: configuration.trace != nil @@ -900,26 +885,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib case SQLITE_TRACE_STMT: if let sqliteStatement = p, let unexpandedSQL = x { let statement = TraceEvent.Statement( - impl: .trace_v2( - sqliteStatement: OpaquePointer(sqliteStatement), - unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), - sqlite3_expanded_sql: sqlite3_expanded_sql, - publicStatementArguments: configuration.publicStatementArguments)) + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)), + sqlite3_expanded_sql: sqlite3_expanded_sql, + publicStatementArguments: configuration.publicStatementArguments) trace(TraceEvent.statement(statement)) } case SQLITE_TRACE_PROFILE: if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) { let statement = TraceEvent.Statement( - impl: .trace_v2( - sqliteStatement: OpaquePointer(sqliteStatement), - unexpandedSQL: nil, - sqlite3_expanded_sql: sqlite3_expanded_sql, - publicStatementArguments: configuration.publicStatementArguments)) + sqliteStatement: OpaquePointer(sqliteStatement), + unexpandedSQL: nil, + sqlite3_expanded_sql: sqlite3_expanded_sql, + publicStatementArguments: configuration.publicStatementArguments) let duration = TimeInterval(durationP.pointee) / 1.0e9 - #if !os(Linux) trace(TraceEvent.profile(statement: statement, duration: duration)) - #endif } default: break @@ -1897,13 +1878,11 @@ extension Database { /// Trace event code: `SQLITE_TRACE_STMT`. public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT) - #if !os(Linux) /// The option that reports executed statements and the estimated /// duration that the statement took to run. /// /// Trace event code: `SQLITE_TRACE_PROFILE`. public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE) - #endif } /// A trace event. @@ -1914,17 +1893,11 @@ extension Database { /// Information about an executed statement. public struct Statement: CustomStringConvertible { - enum Impl { - case trace_v1(String) - case trace_v2( - sqliteStatement: SQLiteStatement, - unexpandedSQL: UnsafePointer?, - sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer?, - publicStatementArguments: Bool) // See Configuration.publicStatementArguments - } - var impl: Impl + var sqliteStatement: SQLiteStatement + var unexpandedSQL: UnsafePointer? + var sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer? + var publicStatementArguments: Bool // See Configuration.publicStatementArguments - #if !os(Linux) /// The executed SQL, where bound parameters are not expanded. /// /// For example: @@ -1932,21 +1905,11 @@ extension Database { /// ```sql /// SELECT * FROM player WHERE email = ? /// ``` - public var sql: String { _sql } - #endif - - var _sql: String { - switch impl { - case .trace_v1: - // Likely a GRDB bug: this api is not supposed to be available - fatalError("Unavailable statement SQL") - - case let .trace_v2(sqliteStatement, unexpandedSQL, _, _): - if let unexpandedSQL { - return String(cString: unexpandedSQL).trimmedSQLStatement - } else { - return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement - } + public var sql: String { + if let unexpandedSQL { + return String(cString: unexpandedSQL).trimmedSQLStatement + } else { + return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement } } @@ -1962,30 +1925,18 @@ extension Database { /// information from leaking in unexpected locations, so use this /// property with care. public var expandedSQL: String { - switch impl { - case let .trace_v1(expandedSQL): - return expandedSQL - - case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql, _): - guard let cString = sqlite3_expanded_sql(sqliteStatement) else { - return "" - } - defer { sqlite3_free(cString) } - return String(cString: cString).trimmedSQLStatement + guard let cString = sqlite3_expanded_sql(sqliteStatement) else { + return "" } + defer { sqlite3_free(cString) } + return String(cString: cString).trimmedSQLStatement } public var description: String { - switch impl { - case let .trace_v1(expandedSQL): + if publicStatementArguments { return expandedSQL - - case let .trace_v2(_, _, _, publicStatementArguments): - if publicStatementArguments { - return expandedSQL - } else { - return _sql - } + } else { + return sql } } } From ee0d3e43e03dd9a4e6b374c4d5745c008f810098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 13:11:12 +0200 Subject: [PATCH 14/28] iOS 17: Update date formatter tests so that it does not depend on the space before AM/PM iOS 17 has changed that space --- .../GRDBTests/DatabaseDateEncodingStrategyTests.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 06d11d07b..98b1ab605 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -36,7 +36,7 @@ private enum StrategyFormatted: StrategyProvider { formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0)! formatter.dateStyle = .full - formatter.timeStyle = .medium + formatter.timeStyle = .none return formatter }()) } @@ -199,10 +199,10 @@ extension DatabaseDateEncodingStrategyTests { try testNullEncoding(strategy: StrategyFormatted.self) for (date, value) in zip(testedDates, [ - "Saturday, December 20, 1969 at 1:39:05 PM", - "Friday, January 2, 1970 at 10:17:36 AM", - "Monday, January 1, 2001 at 12:00:00 AM", - "Tuesday, January 2, 2001 at 10:17:36 AM", + "Saturday, December 20, 1969", + "Friday, January 2, 1970", + "Monday, January 1, 2001", + "Tuesday, January 2, 2001", ]) { try test(strategy: StrategyFormatted.self, encodesDate: date, as: value) } } } From 89dd42640342b23720afcd91f6a988421002e148 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 15:16:06 +0200 Subject: [PATCH 15/28] CHANGELOG --- CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f3faad82b..eecfc5856 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,8 +115,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release -- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) Upgrade custom SQLite builds to 3.42.0 -- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) GitHub CI: test Xcode 14.3.1, macOS 13 +- **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes +- **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0 +- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13 ## 6.15.1 From 08fbd82ead587a2c7376bacc94aebb260017318f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Jun 2023 20:18:00 +0200 Subject: [PATCH 16/28] Rename StatementArgumentsSink.forRawSQL to literalValues --- GRDB/QueryInterface/SQL/SQLExpression.swift | 2 +- .../SQLGeneration/SQLGenerationContext.swift | 12 +++++++++--- Tests/GRDBTests/SQLExpressionLiteralTests.swift | 2 +- 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index fa8d1db7c..b781ccf4d 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -848,7 +848,7 @@ extension SQLExpression { /// /// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'"" func quotedSQL(_ db: Database) throws -> String { - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) return try sql(context) } diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index 7f7724ccd..cc865de97 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -172,15 +172,21 @@ class StatementArgumentsSink { private(set) var arguments: StatementArguments private let rawSQL: Bool - /// A sink which does not accept any arguments. - static let forRawSQL = StatementArgumentsSink(rawSQL: true) + /// A sink which turns all argument values into SQL literals. + /// + /// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the + /// `WHERE name = 'O''Brien'` SQL. + static let literalValues = StatementArgumentsSink(rawSQL: true) private init(rawSQL: Bool) { self.arguments = [] self.rawSQL = rawSQL } - /// A sink which accepts arguments + /// A sink which turns all argument values into `?` SQL parameters. + /// + /// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the + /// `WHERE name = ?` SQL. convenience init() { self.init(rawSQL: false) } diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index 5d80056b0..510b6196d 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -20,7 +20,7 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithoutArguments() throws { try DatabaseQueue().inDatabase { db in let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) let sql = try expression.sql(context, wrappedInParenthesis: true) XCTAssert(context.arguments.isEmpty) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") From bebb751b3c40b528e87cea70e9aec82bb5732dab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Jun 2023 20:20:52 +0200 Subject: [PATCH 17/28] Create and drop view --- GRDB/Documentation.docc/DatabaseSchema.md | 7 + .../SQLInterpolation+QueryInterface.swift | 9 ++ .../Schema/TableDefinition.swift | 130 +++++++++++++++++- Tests/GRDBTests/TableDefinitionTests.swift | 95 +++++++++++++ 4 files changed, 238 insertions(+), 3 deletions(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 35636c104..a106c591d 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -372,6 +372,13 @@ extension Team: TableRecord { - ``TableOptions`` - ``VirtualTableModule`` +### Database Views + +- ``Database/create(view:options:columns:as:)`` +- ``Database/create(view:options:columns:asLiteral:)`` +- ``Database/drop(view:)`` +- ``ViewOptions`` + ### Database Indexes - ``Database/create(indexOn:columns:options:condition:)`` diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index 6f2bbb419..eb161ab8b 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -38,6 +38,15 @@ extension SQLInterpolation { appendInterpolation(type(of: record)) } + /// Appends a quoted identifier. + /// + /// // INSERT INTO "group" ... + /// let tableName = "group" + /// let request: SQLRequest = "INSERT INTO \(identifier: tableName) ..." + public mutating func appendInterpolation(identifier: String) { + appendLiteral(identifier.quotedDatabaseIdentifier) + } + /// Appends the table name of the record. /// /// // INSERT INTO player ... diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 911fa8094..66a18645c 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -320,6 +320,117 @@ extension Database { try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") } + /// Creates a database view. + /// + /// You can create a view with an ``SQLRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", as: SQLRequest(literal: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// You can also create a view with a ``QueryInterfaceRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create( + /// view: "hero", + /// as: Player.filter(Column("isHero") == true)) + /// ``` + /// + /// When creating views in , it is not recommended to + /// use record types defined in the application. Instead of the `Player` + /// record type, prefer `Table("player")`: + /// + /// ```swift + /// // RECOMMENDED IN MIGRATIONS + /// try db.create( + /// view: "hero", + /// as: Table("player").filter(Column("isHero") == true)) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - request: The request that feeds the view. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + as request: SQLSubqueryable) + throws { + var literal: SQL = "CREATE " + + if options.contains(.temporary) { + literal += "TEMPORARY " + } + + literal += "VIEW " + + if options.contains(.ifNotExists) { + literal += "IF NOT EXISTS " + } + + literal += "\(identifier: name) " + + if let columns { + literal += "(" + literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ") + literal += ") " + } + + literal += "AS \(request)" + + // CREATE VIEW does not support arguments, so make sure we use + // literal values. + let context = SQLGenerationContext(self, argumentsSink: .literalValues) + let sql = try literal.sql(context) + try execute(sql: sql) + } + + /// Creates a database view. + /// + /// For example: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", asLiteral: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - sqlLiteral: An `SQL` literal. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + asLiteral sqlLiteral: SQL) + throws { + try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral)) + } + + /// Deletes a database view. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(view name: String) throws { + try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)") + } + /// Creates an index. /// /// For example: @@ -554,6 +665,19 @@ public struct TableOptions: OptionSet { #endif } +/// View creation options +public struct ViewOptions: OptionSet { + public let rawValue: Int + + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the view if it does not already exist. + public static let ifNotExists = ViewOptions(rawValue: 1 << 0) + + /// Creates a temporary view. + public static let temporary = ViewOptions(rawValue: 1 << 1) +} + /// A `TableDefinition` lets you define the components of a database table. /// /// See the documentation of the `Database` @@ -628,7 +752,7 @@ public final class TableDefinition { case let .definition(def): return try def.sql(db, tableName: tableName, primaryKeyColumns: primaryKeyColumns) case let .literal(sqlLiteral): - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) return try sqlLiteral.sql(context) } } @@ -1212,7 +1336,7 @@ public final class TableDefinition { } for literal in literalConstraints { - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) try items.append(literal.sql(context)) } @@ -1439,7 +1563,7 @@ public final class TableAlteration { chunks.append("ALTER TABLE") chunks.append(name.quotedDatabaseIdentifier) chunks.append("ADD COLUMN") - let context = SQLGenerationContext(db, argumentsSink: .forRawSQL) + let context = SQLGenerationContext(db, argumentsSink: .literalValues) try chunks.append(sqlLiteral.sql(context)) let statement = chunks.joined(separator: " ") statements.append(statement) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index dc8db3832..9b73b2a57 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -1033,4 +1033,99 @@ class TableDefinitionTests: GRDBTestCase { assertEqualSQL(lastSQLQuery!, "REINDEX swiftLocalizedCompare") } } + + func testCreateView() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + do { + let request = SQLRequest(literal: """ + SELECT * FROM player WHERE name = \("O'Brien") + """) + try db.create(view: "view1", as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view1" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + let request = Table("player").filter(Column("name") == "O'Brien") + try db.create(view: "view2", as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view2" AS SELECT * FROM "player" WHERE "name" = 'O''Brien' + """) + } + + do { + let sql: SQL = """ + SELECT * FROM player WHERE name = \("O'Brien") + """ + try db.create(view: "view3", asLiteral: sql) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view3" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + } + } + + func testCreateViewOptions() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + let request = SQLRequest(literal: """ + SELECT * FROM player WHERE name = \("O'Brien") + """) + + do { + try db.create(view: "view1", options: .ifNotExists, as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW IF NOT EXISTS "view1" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view2", options: .temporary, as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY VIEW "view2" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view3", options: [.temporary, .ifNotExists], as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE TEMPORARY VIEW IF NOT EXISTS "view3" AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + + do { + try db.create(view: "view4", columns: ["a", "b", "c"], as: request) + assertEqualSQL(lastSQLQuery!, """ + CREATE VIEW "view4" ("a", "b", "c") AS SELECT * FROM player WHERE name = 'O''Brien' + """) + } + } + } + + func testDropView() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(view: "test", as: SQLRequest(literal: "SELECT 'test', 42")) + XCTAssertTrue(try db.viewExists("test")) + XCTAssertEqual(try db.columns(in: "test").count, 2) + + try db.drop(view: "test") + assertEqualSQL(lastSQLQuery!, "DROP VIEW \"test\"") + XCTAssertFalse(try db.viewExists("test")) + } + } } From 82d3af48c3a9776b4fb02731775fc3c8a9784a2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 22 Jun 2023 20:51:37 +0200 Subject: [PATCH 18/28] CHANGELOG --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index eecfc5856..350e1e0cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -115,10 +115,12 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: ## Next Release +- **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views - **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes - **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0 - **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13 + ## 6.15.1 Released June 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.0...v6.15.1) From 337528225263758a8942f6944225e46a8d73ccc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 2 Jul 2023 18:07:00 +0200 Subject: [PATCH 19/28] Update outdated documentation about views --- GRDB/Documentation.docc/DatabaseSchema.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index a106c591d..2469c6539 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -16,7 +16,7 @@ try db.create(table: "player") { t in When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in . -Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating views or triggers, for example). +Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example). When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. From c64784048523663f9e361a1dd4d169feacd57960 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 6 Jul 2023 08:18:51 +0200 Subject: [PATCH 20/28] PrimaryKeyInfo exposes column types --- GRDB/Core/Database+Schema.swift | 47 +++++++++++++++-------- Tests/GRDBTests/PrimaryKeyInfoTests.swift | 25 ++++++++++++ 2 files changed, 55 insertions(+), 17 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 1a8984f97..b19342cce 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -354,13 +354,13 @@ extension Database { // FIXME: We ignore the exception, and consider all INTEGER primary // keys as aliases for the rowid: if pkColumn.type.uppercased() == "INTEGER" { - primaryKey = .rowID(pkColumn.name) + primaryKey = .rowID(pkColumn) } else { - primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table)) + primaryKey = try .regular([pkColumn], tableHasRowID: tableHasRowID(table)) } default: // Multi-columns primary key - primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table)) + primaryKey = try .regular(pkColumns, tableHasRowID: tableHasRowID(table)) } schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name) @@ -1150,22 +1150,22 @@ public struct PrimaryKeyInfo { /// An INTEGER PRIMARY KEY column that aliases the Row ID. /// Associated string is the column name. - case rowID(String) + case rowID(ColumnInfo) /// Any primary key, but INTEGER PRIMARY KEY. /// Associated strings are column names. - case regular(columns: [String], tableHasRowID: Bool) + case regular(columnInfos: [ColumnInfo], tableHasRowID: Bool) } private let impl: Impl - static func rowID(_ column: String) -> PrimaryKeyInfo { - PrimaryKeyInfo(impl: .rowID(column)) + static func rowID(_ columnInfo: ColumnInfo) -> PrimaryKeyInfo { + PrimaryKeyInfo(impl: .rowID(columnInfo)) } - static func regular(_ columns: [String], tableHasRowID: Bool) -> PrimaryKeyInfo { - assert(!columns.isEmpty) - return PrimaryKeyInfo(impl: .regular(columns: columns, tableHasRowID: tableHasRowID)) + static func regular(_ columnInfos: [ColumnInfo], tableHasRowID: Bool) -> PrimaryKeyInfo { + assert(!columnInfos.isEmpty) + return PrimaryKeyInfo(impl: .regular(columnInfos: columnInfos, tableHasRowID: tableHasRowID)) } static let hiddenRowID = PrimaryKeyInfo(impl: .hiddenRowID) @@ -1175,21 +1175,34 @@ public struct PrimaryKeyInfo { switch impl { case .hiddenRowID: return [Column.rowID.name] - case let .rowID(column): - return [column] - case let .regular(columns: columns, tableHasRowID: _): - return columns + case let .rowID(columnInfo): + return [columnInfo.name] + case let .regular(columnInfos: columnInfos, tableHasRowID: _): + return columnInfos.map(\.name) } } + /// The columns in the primary key. Nil if the primary key is the + /// hidden rowID. Never empty otherwise. + var columnInfos: [ColumnInfo]? { + switch impl { + case .hiddenRowID: + return nil + case let .rowID(columnInfo): + return [columnInfo] + case let .regular(columnInfos: columnInfos, tableHasRowID: _): + return columnInfos + } + } + /// When not nil, the name of the column that contains the /// `INTEGER PRIMARY KEY`. public var rowIDColumn: String? { switch impl { case .hiddenRowID: return nil - case .rowID(let column): - return column + case .rowID(let columnInfo): + return columnInfo.name case .regular: return nil } @@ -1216,7 +1229,7 @@ public struct PrimaryKeyInfo { return true case .rowID: return true - case let .regular(columns: _, tableHasRowID: tableHasRowID): + case let .regular(columnInfos: _, tableHasRowID: tableHasRowID): return tableHasRowID } } diff --git a/Tests/GRDBTests/PrimaryKeyInfoTests.swift b/Tests/GRDBTests/PrimaryKeyInfoTests.swift index e6e8fd271..5fb96d506 100644 --- a/Tests/GRDBTests/PrimaryKeyInfoTests.swift +++ b/Tests/GRDBTests/PrimaryKeyInfoTests.swift @@ -37,6 +37,7 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT)") let primaryKey = try db.primaryKey("items") + XCTAssertNil(primaryKey.columnInfos) XCTAssertEqual(primaryKey.columns, [Column.rowID.name]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertTrue(primaryKey.isRowID) @@ -49,6 +50,22 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)") let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) + XCTAssertEqual(primaryKey.columns, ["id"]) + XCTAssertEqual(primaryKey.rowIDColumn, "id") + XCTAssertTrue(primaryKey.isRowID) + XCTAssertTrue(primaryKey.tableHasRowID) + } + } + + func testIntegerPrimaryKey2() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute(sql: "CREATE TABLE items (id INTEGER, name TEXT, PRIMARY KEY (id))") + let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["id"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"]) XCTAssertEqual(primaryKey.columns, ["id"]) XCTAssertEqual(primaryKey.rowIDColumn, "id") XCTAssertTrue(primaryKey.isRowID) @@ -61,6 +78,8 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY)") let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["name"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT"]) XCTAssertEqual(primaryKey.columns, ["name"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) @@ -73,6 +92,8 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b))") let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["a", "b"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT", "INTEGER"]) XCTAssertEqual(primaryKey.columns, ["a", "b"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) @@ -85,6 +106,8 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (name TEXT PRIMARY KEY) WITHOUT ROWID") let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["name"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT"]) XCTAssertEqual(primaryKey.columns, ["name"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) @@ -97,6 +120,8 @@ class PrimaryKeyInfoTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE items (a TEXT, b INTEGER, PRIMARY KEY (a,b)) WITHOUT ROWID") let primaryKey = try db.primaryKey("items") + XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["a", "b"]) + XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["TEXT", "INTEGER"]) XCTAssertEqual(primaryKey.columns, ["a", "b"]) XCTAssertNil(primaryKey.rowIDColumn) XCTAssertFalse(primaryKey.isRowID) From dd85e699e21b9df4fcb6a29bdfc8a09120efb69c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 8 Jul 2023 11:51:57 +0200 Subject: [PATCH 21/28] Help handling of columns with no declared type --- GRDB/Core/Database+Schema.swift | 14 ++++++++++++++ GRDB/Core/Database.swift | 1 + Tests/GRDBTests/ColumnInfoTests.swift | 21 ++++++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index b19342cce..bc3f9c4b7 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -858,8 +858,22 @@ public struct ColumnInfo: FetchableRecord { /// /// The casing of this string depends on the SQLite version: make sure you /// process this string in a case-insensitive way. + /// + /// The type is the empty string when the column has no declared type. public let type: String + /// The column data type (nil when the column has no declared type). + /// + /// The casing of the raw value depends on the SQLite version: make sure + /// you process the result in a case-insensitive way. + var columnType: Database.ColumnType? { + if type.isEmpty { + return nil + } else { + return Database.ColumnType(rawValue: type) + } + } + /// A boolean value indicating if the column is constrained to be not null. public let isNotNull: Bool diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 829d2de16..266155cbb 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1782,6 +1782,7 @@ extension Database { /// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.) public let rawValue: String + // TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank). /// Creates an SQL column type. public init(rawValue: String) { self.rawValue = rawValue diff --git a/Tests/GRDBTests/ColumnInfoTests.swift b/Tests/GRDBTests/ColumnInfoTests.swift index 87b759d7c..1f596ca91 100644 --- a/Tests/GRDBTests/ColumnInfoTests.swift +++ b/Tests/GRDBTests/ColumnInfoTests.swift @@ -19,77 +19,96 @@ class ColumnInfoTests: GRDBTestCase { i DATETIME DEFAULT CURRENT_TIMESTAMP, j DATE DEFAULT (DATETIME('now', 'localtime')), "" fooéı👨👨🏿🇫🇷🇨🇮, + untyped, PRIMARY KEY(c, a) ) """) let columns = try db.columns(in: "t") - XCTAssertEqual(columns.count, 11) + XCTAssertEqual(columns.count, 12) XCTAssertEqual(columns[0].name, "a") XCTAssertEqual(columns[0].isNotNull, false) XCTAssertEqual(columns[0].type, "INT") + XCTAssertEqual(columns[0].columnType?.rawValue, "INT") XCTAssertEqual(columns[0].primaryKeyIndex, 2) XCTAssertNil(columns[0].defaultValueSQL) XCTAssertEqual(columns[1].name, "b") XCTAssertEqual(columns[1].isNotNull, false) XCTAssertEqual(columns[1].type, "TEXT") + XCTAssertEqual(columns[1].columnType?.rawValue, "TEXT") XCTAssertEqual(columns[1].primaryKeyIndex, 0) XCTAssertNil(columns[1].defaultValueSQL) XCTAssertEqual(columns[2].name, "c") XCTAssertEqual(columns[2].isNotNull, false) XCTAssertEqual(columns[2].type, "VARCHAR(10)") + XCTAssertEqual(columns[2].columnType?.rawValue, "VARCHAR(10)") XCTAssertEqual(columns[2].primaryKeyIndex, 1) XCTAssertNil(columns[2].defaultValueSQL) XCTAssertEqual(columns[3].name, "d") XCTAssertEqual(columns[3].isNotNull, false) XCTAssertEqual(columns[3].type.uppercased(), "INT") // "int" or "INT" depending of SQLite version + XCTAssertEqual(columns[3].columnType?.rawValue.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.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version + XCTAssertEqual(columns[4].columnType?.rawValue.uppercased(), "TEXT") // "Text" or "TEXT" depending of SQLite version XCTAssertEqual(columns[4].primaryKeyIndex, 0) XCTAssertEqual(columns[4].defaultValueSQL, "'foo'") XCTAssertEqual(columns[5].name, "fooéı👨👨🏿🇫🇷🇨🇮") XCTAssertEqual(columns[5].isNotNull, false) XCTAssertEqual(columns[5].type, "INT") + XCTAssertEqual(columns[5].columnType?.rawValue, "INT") XCTAssertEqual(columns[5].primaryKeyIndex, 0) XCTAssertEqual(columns[5].defaultValueSQL, "0") XCTAssertEqual(columns[6].name, "g") XCTAssertEqual(columns[6].isNotNull, false) XCTAssertEqual(columns[6].type, "INT") + XCTAssertEqual(columns[6].columnType?.rawValue, "INT") XCTAssertEqual(columns[6].primaryKeyIndex, 0) XCTAssertEqual(columns[6].defaultValueSQL, "1e6") XCTAssertEqual(columns[7].name, "h") XCTAssertEqual(columns[7].isNotNull, false) XCTAssertEqual(columns[7].type, "REAL") + XCTAssertEqual(columns[7].columnType?.rawValue, "REAL") XCTAssertEqual(columns[7].primaryKeyIndex, 0) XCTAssertEqual(columns[7].defaultValueSQL, "1.0") XCTAssertEqual(columns[8].name, "i") XCTAssertEqual(columns[8].isNotNull, false) XCTAssertEqual(columns[8].type, "DATETIME") + XCTAssertEqual(columns[8].columnType?.rawValue, "DATETIME") XCTAssertEqual(columns[8].primaryKeyIndex, 0) XCTAssertEqual(columns[8].defaultValueSQL, "CURRENT_TIMESTAMP") XCTAssertEqual(columns[9].name, "j") XCTAssertEqual(columns[9].isNotNull, false) XCTAssertEqual(columns[9].type, "DATE") + XCTAssertEqual(columns[9].columnType?.rawValue, "DATE") XCTAssertEqual(columns[9].primaryKeyIndex, 0) XCTAssertEqual(columns[9].defaultValueSQL, "DATETIME('now', 'localtime')") XCTAssertEqual(columns[10].name, "") XCTAssertEqual(columns[10].isNotNull, false) XCTAssertEqual(columns[10].type, "fooéı👨👨🏿🇫🇷🇨🇮") + XCTAssertEqual(columns[10].columnType?.rawValue, "fooéı👨👨🏿🇫🇷🇨🇮") XCTAssertEqual(columns[10].primaryKeyIndex, 0) XCTAssertNil(columns[10].defaultValueSQL) + + XCTAssertEqual(columns[11].name, "untyped") + XCTAssertEqual(columns[11].isNotNull, false) + XCTAssertEqual(columns[11].type, "") + XCTAssertNil(columns[11].columnType) + XCTAssertEqual(columns[11].primaryKeyIndex, 0) + XCTAssertNil(columns[11].defaultValueSQL) } } From 349253e1962bf827a4598c32e0914bb959040630 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 11:37:24 +0200 Subject: [PATCH 22/28] Failing tests for ForeignKeyDefinition --- GRDB.xcodeproj/project.pbxproj | 4 + GRDBCustom.xcodeproj/project.pbxproj | 4 + .../GRDBTests.xcodeproj/project.pbxproj | 6 + .../GRDBTests.xcodeproj/project.pbxproj | 48 + .../GRDBTests/ForeignKeyDefinitionTests.swift | 1550 +++++++++++++++++ Tests/GRDBTests/TableDefinitionTests.swift | 55 +- 6 files changed, 1662 insertions(+), 5 deletions(-) create mode 100644 Tests/GRDBTests/ForeignKeyDefinitionTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 8fd0332e0..13d88f449 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -202,6 +202,7 @@ 56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; }; 56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; }; 56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; }; + 568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; }; 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568D13182207213E00674B58 /* SQLQueryGenerator.swift */; }; 568EB71929211E0800E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */; }; 568EB71E2921234800E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */; }; @@ -621,6 +622,7 @@ 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; 56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; + 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 568D13182207213E00674B58 /* SQLQueryGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQueryGenerator.swift; sourceTree = ""; }; 568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; }; 568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; @@ -1009,6 +1011,7 @@ 56012B542573EED000B4925B /* CommonTableExpressionTests.swift */, 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, + 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 563EF45221631E21007DAACD /* QueryInterfacePromiseTests.swift */, @@ -1963,6 +1966,7 @@ 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */, 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */, + 568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index eb60e2f27..c46f3455f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -200,6 +200,7 @@ 56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; }; 56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; }; 56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; }; + 568C3F7D2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */; }; 568EB71C2921232200E59445 /* DatabaseSnapshotPool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */; }; 568EB7202921235E00E59445 /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */; }; 568ECB0D25D904CA00B71526 /* SQLSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568ECB0C25D904CA00B71526 /* SQLSelection.swift */; }; @@ -645,6 +646,7 @@ 56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = ""; }; 56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = ""; }; 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; + 568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPool.swift; sourceTree = ""; }; 568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = ""; }; @@ -1027,6 +1029,7 @@ 56012B682573FAE600B4925B /* CommonTableExpressionTests.swift */, 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, + 568C3F7B2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 563EF45521631E3E007DAACD /* QueryInterfacePromiseTests.swift */, @@ -2224,6 +2227,7 @@ 56419C8124A51D6E004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */, 561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */, 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, + 568C3F7D2A5AB2D500A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5698AD011DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, F3BA80B51CFB2FCA003DC1BA /* DatabaseQueueInMemoryTests.swift in Sources */, 56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 778e2e8ab..bc0906d61 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -445,6 +445,8 @@ 565A27CD27871FFF00659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27CB27871FFF00659A62 /* BackupTestCase.swift */; }; 567B23172A29BFA400C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; }; 567B23182A29BFA500C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23162A29BFA400C61174 /* Issue1383.sqlite */; }; + 568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; + 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; @@ -679,6 +681,7 @@ 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 = ""; }; 567B23162A29BFA400C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; + 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -877,6 +880,7 @@ 56419CB724A54055004967E1 /* FetchRequestTests.swift */, 56419D5B24A54061004967E1 /* FilterCursorTests.swift */, 56419D4B24A54060004967E1 /* FlattenCursorTests.swift */, + 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */, 56419CF124A54059004967E1 /* ForeignKeyInfoTests.swift */, 56419D2E24A5405E004967E1 /* FoundationDataTests.swift */, 56419D6624A54062004967E1 /* FoundationDateComponentsTests.swift */, @@ -1209,6 +1213,7 @@ 56419DC124A54062004967E1 /* FoundationNSDateTests.swift in Sources */, 56419EC524A54063004967E1 /* FlattenCursorTests.swift in Sources */, 56419E9D24A54063004967E1 /* StatementArgumentsTests.swift in Sources */, + 568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A1AA24A540D6004967E1 /* Recorder.swift in Sources */, 56419D7B24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56419D6B24A54062004967E1 /* DatabaseQueueTests.swift in Sources */, @@ -1434,6 +1439,7 @@ 56419DC224A54062004967E1 /* FoundationNSDateTests.swift in Sources */, 56419EC624A54063004967E1 /* FlattenCursorTests.swift in Sources */, 56419E9E24A54063004967E1 /* StatementArgumentsTests.swift in Sources */, + 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A1AB24A540D6004967E1 /* Recorder.swift in Sources */, 56419D7C24A54062004967E1 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56419D6C24A54062004967E1 /* DatabaseQueueTests.swift in Sources */, diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index a8948c5e7..46926ec6d 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -447,6 +447,22 @@ 565A27CA27871FE500659A62 /* BackupTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565A27C827871FE500659A62 /* BackupTestCase.swift */; }; 567B231A2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; }; 567B231B2A29BFE100C61174 /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 567B23192A29BFE100C61174 /* Issue1383.sqlite */; }; + 568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; + 568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; }; + 568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; }; + 568C3F8C2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; }; + 568C3F8D2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */; }; + 568C3F8E2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */; }; + 568C3F8F2A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */; }; + 568C3F902A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */; }; + 568C3F912A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */; }; + 568C3F922A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */; }; + 568C3F932A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */; }; + 568C3F942A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */; }; + 568C3F952A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */; }; + 568C3F962A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */; }; + 568C3F972A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; + 568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; @@ -682,6 +698,14 @@ 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 = ""; }; 567B23192A29BFE100C61174 /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = ""; }; + 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; + 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = ""; }; + 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = ""; }; + 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = ""; }; + 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CommonTableExpressionTests.swift; sourceTree = ""; }; + 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifierTests.swift; sourceTree = ""; }; + 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; + 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; 56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; @@ -811,14 +835,17 @@ 56419F9A24A5409D004967E1 /* AssociationPrefetchingCodableRecordTests.swift */, 56419F2224A54095004967E1 /* AssociationPrefetchingFetchableRecordTests.swift */, 56419F8F24A5409C004967E1 /* AssociationPrefetchingObservationTests.swift */, + 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */, 56419F1E24A54094004967E1 /* AssociationPrefetchingRowTests.swift */, 56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */, 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */, 565A27C827871FE500659A62 /* BackupTestCase.swift */, + 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */, 56419F6B24A5409A004967E1 /* CGFloatTests.swift */, 56419F6524A54099004967E1 /* ColumnExpressionTests.swift */, 56419F9324A5409D004967E1 /* ColumnInfoTests.swift */, + 568C3F872A5AB3A800A2309D /* CommonTableExpressionTests.swift */, 56419F5424A54098004967E1 /* CompilationProtocolTests.swift */, 56419F8024A5409B004967E1 /* CompilationSubClassTests.swift */, 56419FBF24A540A0004967E1 /* CursorTests.swift */, @@ -826,6 +853,7 @@ 56419F9D24A5409D004967E1 /* DatabaseAfterNextTransactionCommitTests.swift */, 56419F8A24A5409C004967E1 /* DatabaseAggregateTests.swift */, 56419FBB24A540A0004967E1 /* DatabaseCollationTests.swift */, + 568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */, 56419F7024A5409A004967E1 /* DatabaseConfigurationTests.swift */, 56419F2324A54095004967E1 /* DatabaseCursorTests.swift */, 56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */, @@ -853,6 +881,7 @@ 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */, 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */, 56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */, + 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */, 56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */, 56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */, 56419F7324A5409A004967E1 /* DatabaseTests.swift */, @@ -881,10 +910,12 @@ 56419EFD24A54093004967E1 /* FetchRequestTests.swift */, 56419FAD24A5409F004967E1 /* FilterCursorTests.swift */, 56419FAE24A5409F004967E1 /* FlattenCursorTests.swift */, + 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */, 56419F7224A5409A004967E1 /* ForeignKeyInfoTests.swift */, 56419FC524A540A1004967E1 /* FoundationDataTests.swift */, 56419F2524A54095004967E1 /* FoundationDateComponentsTests.swift */, 56419F1124A54093004967E1 /* FoundationDateTests.swift */, + 568C3F862A5AB3A800A2309D /* FoundationDecimalTests.swift */, 56419F9F24A5409E004967E1 /* FoundationNSDataTests.swift */, 56419FB224A5409F004967E1 /* FoundationNSDateTests.swift */, 56419F8124A5409B004967E1 /* FoundationNSDecimalNumberTests.swift */, @@ -931,6 +962,7 @@ 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */, 56419F2124A54094004967E1 /* RecordEditedTests.swift */, 56419F4824A54097004967E1 /* RecordInitializersTests.swift */, + 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */, 56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */, 56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */, 56419F5124A54098004967E1 /* RecordPersistenceConflictPolicy.swift */, @@ -1203,6 +1235,7 @@ 5641A0A424A540A1004967E1 /* CGFloatTests.swift in Sources */, 5641A0F824A540A1004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 5641A01C24A540A1004967E1 /* PrefixCursorTests.swift in Sources */, + 568C3F8D2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 56419FEE24A540A1004967E1 /* DatabasePoolCollationTests.swift in Sources */, 5641A15424A540A2004967E1 /* DataMemoryTests.swift in Sources */, 5641A0D224A540A1004967E1 /* AssociationHasOneThroughSQLTests.swift in Sources */, @@ -1212,9 +1245,11 @@ 5641A17C24A540C7004967E1 /* Prefix.swift in Sources */, 5641A17E24A540C7004967E1 /* Map.swift in Sources */, 5641A0F024A540A1004967E1 /* FTS4RecordTests.swift in Sources */, + 568C3F972A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */, 5641A0BA24A540A1004967E1 /* PrefixWhileCursorTests.swift in Sources */, 5641A0B624A540A1004967E1 /* DatabasePoolTests.swift in Sources */, 5641A0B424A540A1004967E1 /* DatabaseTests.swift in Sources */, + 568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A06024A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 5641A0C624A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */, 5641A03424A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */, @@ -1264,14 +1299,17 @@ 5641A02224A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */, 5641A12624A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */, 5641A13024A540A1004967E1 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, + 568C3F8F2A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */, 56419FFE24A540A1004967E1 /* FTS5TokenizerTests.swift in Sources */, 5641A0FA24A540A1004967E1 /* FetchableRecordTests.swift in Sources */, 5641A09424A540A1004967E1 /* ValueObservationCountTests.swift in Sources */, 5641A0EA24A540A1004967E1 /* RowFromDictionaryLiteralTests.swift in Sources */, 5641A09224A540A1004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 5641A04E24A540A1004967E1 /* RecordUniqueIndexTests.swift in Sources */, + 568C3F912A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */, 5641A12824A540A1004967E1 /* FilterCursorTests.swift in Sources */, 5641A0CE24A540A1004967E1 /* CompilationSubClassTests.swift in Sources */, + 568C3F952A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */, 5641A0DE24A540A1004967E1 /* QueryInterfaceExpressionsTests.swift in Sources */, 5641A0C424A540A1004967E1 /* MapCursorTests.swift in Sources */, 5641A06E24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, @@ -1326,6 +1364,7 @@ 5641A05024A540A1004967E1 /* FTS3PatternTests.swift in Sources */, 5641A17024A540C7004967E1 /* Recorder.swift in Sources */, 5641A11024A540A1004967E1 /* Row+FoundationTests.swift in Sources */, + 568C3F932A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */, 56419FC824A540A1004967E1 /* FetchRequestTests.swift in Sources */, 56419FDC24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 5641A0B224A540A1004967E1 /* ForeignKeyInfoTests.swift in Sources */, @@ -1352,6 +1391,7 @@ 5641A0B024A540A1004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 5641A00A24A540A1004967E1 /* AssociationPrefetchingRowTests.swift in Sources */, 5641A0B824A540A1004967E1 /* FTS5CustomTokenizerTests.swift in Sources */, + 568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */, 5641A04824A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */, 5641A07824A540A1004967E1 /* DropFirstCursorTests.swift in Sources */, 5641A13224A540A1004967E1 /* FoundationNSDateTests.swift in Sources */, @@ -1428,6 +1468,7 @@ 5641A0A524A540A1004967E1 /* CGFloatTests.swift in Sources */, 5641A0F924A540A1004967E1 /* RecordPrimaryKeyNoneTests.swift in Sources */, 5641A01D24A540A1004967E1 /* PrefixCursorTests.swift in Sources */, + 568C3F8E2A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift in Sources */, 56419FEF24A540A1004967E1 /* DatabasePoolCollationTests.swift in Sources */, 5641A15524A540A2004967E1 /* DataMemoryTests.swift in Sources */, 5641A0D324A540A1004967E1 /* AssociationHasOneThroughSQLTests.swift in Sources */, @@ -1437,9 +1478,11 @@ 5641A17D24A540C7004967E1 /* Prefix.swift in Sources */, 5641A17F24A540C7004967E1 /* Map.swift in Sources */, 5641A0F124A540A1004967E1 /* FTS4RecordTests.swift in Sources */, + 568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */, 5641A0BB24A540A1004967E1 /* PrefixWhileCursorTests.swift in Sources */, 5641A0B724A540A1004967E1 /* DatabasePoolTests.swift in Sources */, 5641A0B524A540A1004967E1 /* DatabaseTests.swift in Sources */, + 568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */, 5641A06124A540A1004967E1 /* AssociationChainRowScopesTests.swift in Sources */, 5641A0C724A540A1004967E1 /* FetchableRecordDecodableTests.swift in Sources */, 5641A03524A540A1004967E1 /* RowFromDictionaryTests.swift in Sources */, @@ -1489,14 +1532,17 @@ 5641A02324A540A1004967E1 /* ValueObservationFetchTests.swift in Sources */, 5641A12724A540A1004967E1 /* DatabasePoolSchemaCacheTests.swift in Sources */, 5641A13124A540A1004967E1 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, + 568C3F902A5AB3A800A2309D /* FoundationDecimalTests.swift in Sources */, 56419FFF24A540A1004967E1 /* FTS5TokenizerTests.swift in Sources */, 5641A0FB24A540A1004967E1 /* FetchableRecordTests.swift in Sources */, 5641A09524A540A1004967E1 /* ValueObservationCountTests.swift in Sources */, 5641A0EB24A540A1004967E1 /* RowFromDictionaryLiteralTests.swift in Sources */, 5641A09324A540A1004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */, 5641A04F24A540A1004967E1 /* RecordUniqueIndexTests.swift in Sources */, + 568C3F922A5AB3A800A2309D /* CommonTableExpressionTests.swift in Sources */, 5641A12924A540A1004967E1 /* FilterCursorTests.swift in Sources */, 5641A0CF24A540A1004967E1 /* CompilationSubClassTests.swift in Sources */, + 568C3F962A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift in Sources */, 5641A0DF24A540A1004967E1 /* QueryInterfaceExpressionsTests.swift in Sources */, 5641A0C524A540A1004967E1 /* MapCursorTests.swift in Sources */, 5641A06F24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */, @@ -1551,6 +1597,7 @@ 5641A05124A540A1004967E1 /* FTS3PatternTests.swift in Sources */, 5641A17124A540C7004967E1 /* Recorder.swift in Sources */, 5641A11124A540A1004967E1 /* Row+FoundationTests.swift in Sources */, + 568C3F942A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift in Sources */, 56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */, 56419FDD24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */, 5641A0B324A540A1004967E1 /* ForeignKeyInfoTests.swift in Sources */, @@ -1577,6 +1624,7 @@ 5641A0B124A540A1004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */, 5641A00B24A540A1004967E1 /* AssociationPrefetchingRowTests.swift in Sources */, 5641A0B924A540A1004967E1 /* FTS5CustomTokenizerTests.swift in Sources */, + 568C3F8C2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */, 5641A04924A540A1004967E1 /* DatabaseValueConversionTests.swift in Sources */, 5641A07924A540A1004967E1 /* DropFirstCursorTests.swift in Sources */, 5641A13324A540A1004967E1 /* FoundationNSDateTests.swift in Sources */, diff --git a/Tests/GRDBTests/ForeignKeyDefinitionTests.swift b/Tests/GRDBTests/ForeignKeyDefinitionTests.swift new file mode 100644 index 000000000..d6bacfc5a --- /dev/null +++ b/Tests/GRDBTests/ForeignKeyDefinitionTests.swift @@ -0,0 +1,1550 @@ +import XCTest +@testable import GRDB + +class ForeignKeyDefinitionTests: GRDBTestCase { + func testTable_belongsTo_hiddenRowID_plain() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + // Custom names + t.belongsTo("customParent", inTable: "parent") + t.belongsTo("customCountry", inTable: "country") + t.belongsTo("customTeam", inTable: "teams") + t.belongsTo("customPerson", inTable: "people") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(9), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentId" INTEGER REFERENCES "parent"("rowid"), \ + "COUNTRYId" INTEGER REFERENCES "COUNTRY"("rowid"), \ + "teamId" INTEGER REFERENCES "teams"("rowid"), \ + "peopleId" INTEGER REFERENCES "people"("rowid"), \ + "customParentId" INTEGER REFERENCES "parent"("rowid"), \ + "customCountryId" INTEGER REFERENCES "country"("rowid"), \ + "customTeamId" INTEGER REFERENCES "teams"("rowid"), \ + "customPersonId" INTEGER REFERENCES "people"("rowid"), \ + "b"\ + ) + """, + """ + CREATE INDEX "child_on_parentId" ON "child"("parentId") + """, + """ + CREATE INDEX "child_on_COUNTRYId" ON "child"("COUNTRYId") + """, + """ + CREATE INDEX "child_on_teamId" ON "child"("teamId") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + """ + CREATE INDEX "child_on_customParentId" ON "child"("customParentId") + """, + """ + CREATE INDEX "child_on_customCountryId" ON "child"("customCountryId") + """, + """ + CREATE INDEX "child_on_customTeamId" ON "child"("customTeamId") + """, + """ + CREATE INDEX "child_on_customPersonId" ON "child"("customPersonId") + """, + ]) + } + } + + func testTable_belongsTo_hiddenRowID_ifNotExists() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child", options: .ifNotExists) { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + t.column("b") + } + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE IF NOT EXISTS "child" (\ + "a", \ + "parentId" INTEGER REFERENCES "parent"("rowid"), \ + "COUNTRYId" INTEGER REFERENCES "COUNTRY"("rowid"), \ + "teamId" INTEGER REFERENCES "teams"("rowid"), \ + "peopleId" INTEGER REFERENCES "people"("rowid"), \ + "b") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_parentId" ON "child"("parentId") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_COUNTRYId" ON "child"("COUNTRYId") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_teamId" ON "child"("teamId") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_hiddenRowID_unique() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").unique() + // Modified case of table name + t.belongsTo("COUNTRY").unique() + // Singularized table name + t.belongsTo("team").unique() + // Raw plural table name + t.belongsTo("people").unique() + t.column("b") + } + XCTAssertEqual(lastSQLQuery, """ + CREATE TABLE "child" (\ + "a", \ + "parentId" INTEGER UNIQUE REFERENCES "parent"("rowid"), \ + "COUNTRYId" INTEGER UNIQUE REFERENCES "COUNTRY"("rowid"), \ + "teamId" INTEGER UNIQUE REFERENCES "teams"("rowid"), \ + "peopleId" INTEGER UNIQUE REFERENCES "people"("rowid"), \ + "b") + """) + } + } + + func testTable_belongsTo_hiddenRowID_notIndexed() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", indexed: false) + // Modified case of table name + t.belongsTo("COUNTRY", indexed: false) + // Singularized table name + t.belongsTo("team", indexed: false) + // Raw plural table name + t.belongsTo("people", indexed: false) + t.column("b") + } + XCTAssertEqual(lastSQLQuery, """ + CREATE TABLE "child" (\ + "a", \ + "parentId" INTEGER REFERENCES "parent"("rowid"), \ + "COUNTRYId" INTEGER REFERENCES "COUNTRY"("rowid"), \ + "teamId" INTEGER REFERENCES "teams"("rowid"), \ + "peopleId" INTEGER REFERENCES "people"("rowid"), \ + "b") + """) + } + } + + func testTable_belongsTo_hiddenRowID_notNull() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").notNull() + // Modified case of table name + t.belongsTo("COUNTRY").notNull() + // Singularized table name + t.belongsTo("team").notNull() + // Raw plural table name + t.belongsTo("people").notNull() + t.column("b") + } + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentId" INTEGER NOT NULL REFERENCES "parent"("rowid"), \ + "COUNTRYId" INTEGER NOT NULL REFERENCES "COUNTRY"("rowid"), \ + "teamId" INTEGER NOT NULL REFERENCES "teams"("rowid"), \ + "peopleId" INTEGER NOT NULL REFERENCES "people"("rowid"), \ + "b") + """, + """ + CREATE INDEX "child_on_parentId" ON "child"("parentId") + """, + """ + CREATE INDEX "child_on_COUNTRYId" ON "child"("COUNTRYId") + """, + """ + CREATE INDEX "child_on_teamId" ON "child"("teamId") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_hiddenRowID_foreignKeyOptions() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "parent") { t in + t.column("name", .text) + } + + try db.create(table: "country") { t in + t.column("name", .text) + } + + try db.create(table: "teams") { t in + t.column("name", .text) + } + + try db.create(table: "people") { t in + t.column("name", .text) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Modified case of table name + t.belongsTo("COUNTRY", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Singularized table name + t.belongsTo("team", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Raw plural table name + t.belongsTo("people", onDelete: .cascade, onUpdate: .setNull, deferred: true) + t.column("b") + } + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentId" INTEGER REFERENCES "parent"("rowid") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "COUNTRYId" INTEGER REFERENCES "COUNTRY"("rowid") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "teamId" INTEGER REFERENCES "teams"("rowid") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "peopleId" INTEGER REFERENCES "people"("rowid") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "b") + """, + """ + CREATE INDEX "child_on_parentId" ON "child"("parentId") + """, + """ + CREATE INDEX "child_on_COUNTRYId" ON "child"("COUNTRYId") + """, + """ + CREATE INDEX "child_on_teamId" ON "child"("teamId") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_hiddenRowID_autoreference_singular() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "employee") { t in + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employee") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employee" (\ + "a", \ + "employeeId" INTEGER REFERENCES "employee"("rowid"), \ + "customId" INTEGER REFERENCES "employee"("rowid"), \ + "b"\ + ) + """, + """ + CREATE INDEX "employee_on_employeeId" ON "employee"("employeeId") + """, + """ + CREATE INDEX "employee_on_customId" ON "employee"("customId") + """ + ]) + } + } + + func testTable_belongsTo_hiddenRowID_autoreference_plural() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "employees") { t in + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employees") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employees" (\ + "a", \ + "employeeId" INTEGER REFERENCES "employees"("rowid"), \ + "customId" INTEGER REFERENCES "employees"("rowid"), \ + "b"\ + ) + """, + """ + CREATE INDEX "employees_on_employeeId" ON "employees"("employeeId") + """, + """ + CREATE INDEX "employees_on_customId" ON "employees"("customId") + """ + ]) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_plain() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + // Custom names + t.belongsTo("customParent", inTable: "parent") + t.belongsTo("customCountry", inTable: "country") + t.belongsTo("customTeam", inTable: "teams") + t.belongsTo("customPerson", inTable: "people") + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(9), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentPrimaryKey" TEXT REFERENCES "parent"("primaryKey"), \ + "COUNTRYCode" CUSTOM TYPE REFERENCES "COUNTRY"("code"), \ + "teamPrimaryKey" INTEGER REFERENCES "teams"("primaryKey"), \ + "peopleId" INTEGER REFERENCES "people"("id"), \ + "customParentPrimaryKey" TEXT REFERENCES "parent"("primaryKey"), \ + "customCountryCode" CUSTOM TYPE REFERENCES "country"("code"), \ + "customTeamPrimaryKey" INTEGER REFERENCES "teams"("primaryKey"), \ + "customPersonId" INTEGER REFERENCES "people"("id"), \ + "e"\ + ) + """, + """ + CREATE INDEX "child_on_parentPrimaryKey" ON "child"("parentPrimaryKey") + """, + """ + CREATE INDEX "child_on_COUNTRYCode" ON "child"("COUNTRYCode") + """, + """ + CREATE INDEX "child_on_teamPrimaryKey" ON "child"("teamPrimaryKey") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + """ + CREATE INDEX "child_on_customParentPrimaryKey" ON "child"("customParentPrimaryKey") + """, + """ + CREATE INDEX "child_on_customCountryCode" ON "child"("customCountryCode") + """, + """ + CREATE INDEX "child_on_customTeamPrimaryKey" ON "child"("customTeamPrimaryKey") + """, + """ + CREATE INDEX "child_on_customPersonId" ON "child"("customPersonId") + """, + ]) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_ifNotExists() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child", options: .ifNotExists) { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE IF NOT EXISTS "child" (\ + "a", \ + "parentPrimaryKey" TEXT REFERENCES "parent"("primaryKey"), \ + "COUNTRYCode" CUSTOM TYPE REFERENCES "COUNTRY"("code"), \ + "teamPrimaryKey" INTEGER REFERENCES "teams"("primaryKey"), \ + "peopleId" INTEGER REFERENCES "people"("id"), \ + "e"\ + ) + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_parentPrimaryKey" ON "child"("parentPrimaryKey") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_COUNTRYCode" ON "child"("COUNTRYCode") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_teamPrimaryKey" ON "child"("teamPrimaryKey") + """, + """ + CREATE INDEX IF NOT EXISTS "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_unique() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").unique() + // Modified case of table name + t.belongsTo("COUNTRY").unique() + // Singularized table name + t.belongsTo("team").unique() + // Raw plural table name + t.belongsTo("people").unique() + t.column("e") + } + + XCTAssertEqual(lastSQLQuery, """ + CREATE TABLE "child" (\ + "a", \ + "parentPrimaryKey" TEXT UNIQUE REFERENCES "parent"("primaryKey"), \ + "COUNTRYCode" CUSTOM TYPE UNIQUE REFERENCES "COUNTRY"("code"), \ + "teamPrimaryKey" INTEGER UNIQUE REFERENCES "teams"("primaryKey"), \ + "peopleId" INTEGER UNIQUE REFERENCES "people"("id"), \ + "e"\ + ) + """) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_notIndexed() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", indexed: false) + // Modified case of table name + t.belongsTo("COUNTRY", indexed: false) + // Singularized table name + t.belongsTo("team", indexed: false) + // Raw plural table name + t.belongsTo("people", indexed: false) + t.column("e") + } + + XCTAssertEqual(lastSQLQuery, """ + CREATE TABLE "child" (\ + "a", \ + "parentPrimaryKey" TEXT REFERENCES "parent"("primaryKey"), \ + "COUNTRYCode" CUSTOM TYPE REFERENCES "COUNTRY"("code"), \ + "teamPrimaryKey" INTEGER REFERENCES "teams"("primaryKey"), \ + "peopleId" INTEGER REFERENCES "people"("id"), \ + "e"\ + ) + """) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_notNull() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").notNull() + // Modified case of table name + t.belongsTo("COUNTRY").notNull() + // Singularized table name + t.belongsTo("team").notNull() + // Raw plural table name + t.belongsTo("people").notNull() + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentPrimaryKey" TEXT NOT NULL REFERENCES "parent"("primaryKey"), \ + "COUNTRYCode" CUSTOM TYPE NOT NULL REFERENCES "COUNTRY"("code"), \ + "teamPrimaryKey" INTEGER NOT NULL REFERENCES "teams"("primaryKey"), \ + "peopleId" INTEGER NOT NULL REFERENCES "people"("id"), \ + "e"\ + ) + """, + """ + CREATE INDEX "child_on_parentPrimaryKey" ON "child"("parentPrimaryKey") + """, + """ + CREATE INDEX "child_on_COUNTRYCode" ON "child"("COUNTRYCode") + """, + """ + CREATE INDEX "child_on_teamPrimaryKey" ON "child"("teamPrimaryKey") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_foreignKeyOptions() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.primaryKey("primaryKey", .text) + } + + // Custom type + try db.create(table: "country") { t in + t.primaryKey("code", .init(rawValue: "CUSTOM TYPE")) + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey("primaryKey", .integer) + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey("id", .integer) + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Modified case of table name + t.belongsTo("COUNTRY", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Singularized table name + t.belongsTo("team", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Raw plural table name + t.belongsTo("people", onDelete: .cascade, onUpdate: .setNull, deferred: true) + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentPrimaryKey" TEXT REFERENCES "parent"("primaryKey") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "COUNTRYCode" CUSTOM TYPE REFERENCES "COUNTRY"("code") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "teamPrimaryKey" INTEGER REFERENCES "teams"("primaryKey") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "peopleId" INTEGER REFERENCES "people"("id") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + "e"\ + ) + """, + """ + CREATE INDEX "child_on_parentPrimaryKey" ON "child"("parentPrimaryKey") + """, + """ + CREATE INDEX "child_on_COUNTRYCode" ON "child"("COUNTRYCode") + """, + """ + CREATE INDEX "child_on_teamPrimaryKey" ON "child"("teamPrimaryKey") + """, + """ + CREATE INDEX "child_on_peopleId" ON "child"("peopleId") + """, + ]) + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_autoreference_singular() throws { + try makeDatabaseQueue().inDatabase { db in + do { + sqlQueries.removeAll() + try db.create(table: "employee") { t in + t.autoIncrementedPrimaryKey("id") + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employee") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employee" (\ + "id" INTEGER PRIMARY KEY AUTOINCREMENT, \ + "a", \ + "employeeId" INTEGER REFERENCES "employee"("id"), \ + "customId" INTEGER REFERENCES "employee"("id"), \ + "b"\ + ) + """, + """ + CREATE INDEX "employee_on_employeeId" ON "employee"("employeeId") + """, + """ + CREATE INDEX "employee_on_customId" ON "employee"("customId") + """ + ]) + } + + do { + sqlQueries.removeAll() + try db.create(table: "node") { t in + t.primaryKey { t.column("code") } + t.column("a") + t.belongsTo("node") + t.belongsTo("custom", inTable: "node") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "node" (\ + "code" NOT NULL, \ + "a", \ + "nodeCode" REFERENCES "node"("code"), \ + "customCode" REFERENCES "node"("code"), \ + "b", \ + PRIMARY KEY ("code")\ + ) + """, + """ + CREATE INDEX "node_on_nodeCode" ON "node"("nodeCode") + """, + """ + CREATE INDEX "node_on_customCode" ON "node"("customCode") + """ + ]) + } + } + } + + func testTable_belongsTo_singleColumnPrimaryKey_autoreference_plural() throws { + try makeDatabaseQueue().inDatabase { db in + do { + sqlQueries.removeAll() + try db.create(table: "employees") { t in + t.autoIncrementedPrimaryKey("id") + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employees") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employees" (\ + "id" INTEGER PRIMARY KEY AUTOINCREMENT, \ + "a", \ + "employeeId" INTEGER REFERENCES "employees"("id"), \ + "customId" INTEGER REFERENCES "employees"("id"), \ + "b"\ + ) + """, + """ + CREATE INDEX "employees_on_employeeId" ON "employees"("employeeId") + """, + """ + CREATE INDEX "employees_on_customId" ON "employees"("customId") + """ + ]) + } + + do { + sqlQueries.removeAll() + try db.create(table: "nodes") { t in + t.primaryKey { t.column("code") } + t.column("a") + t.belongsTo("node") + t.belongsTo("custom", inTable: "nodes") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "nodes" (\ + "code" NOT NULL, \ + "a", \ + "nodeCode" REFERENCES "nodes"("code"), \ + "customCode" REFERENCES "nodes"("code"), \ + "b", \ + PRIMARY KEY ("code")\ + ) + """, + """ + CREATE INDEX "nodes_on_nodeCode" ON "nodes"("nodeCode") + """, + """ + CREATE INDEX "nodes_on_customCode" ON "nodes"("customCode") + """ + ]) + } + } + } + + func testTable_belongsTo_compositePrimaryKey_plain() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + // Custom names + t.belongsTo("customParent", inTable: "parent") + t.belongsTo("customCountry", inTable: "country") + t.belongsTo("customTeam", inTable: "teams") + t.belongsTo("customPerson", inTable: "people") + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(9), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentA" TEXT, \ + "parentB" CUSTOM TYPE, \ + "parentC", \ + "COUNTRYLeft" TEXT, \ + "COUNTRYRight" INTEGER, \ + "teamTop" TEXT, \ + "teamBottom" INTEGER, \ + "peopleMin" TEXT, \ + "peopleMax" INTEGER, \ + "customParentA" TEXT, \ + "customParentB" CUSTOM TYPE, \ + "customParentC", \ + "customCountryLeft" TEXT, \ + "customCountryRight" INTEGER, \ + "customTeamTop" TEXT, \ + "customTeamBottom" INTEGER, \ + "customPersonMin" TEXT, \ + "customPersonMax" INTEGER, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right"), \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max"), \ + FOREIGN KEY ("customParentA", "customParentB", "customParentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("customCountryLeft", "customCountryRight") REFERENCES "country"("left", "right"), \ + FOREIGN KEY ("customTeamTop", "customTeamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("customPersonMin", "customPersonMax") REFERENCES "people"("min", "max")\ + ) + """, + """ + CREATE INDEX "index_child_on_parentA_parentB_parentC" ON "child"("parentA", "parentB", "parentC") + """, + """ + CREATE INDEX "index_child_on_COUNTRYLeft_COUNTRYRight" ON "child"("COUNTRYLeft", "COUNTRYRight") + """, + """ + CREATE INDEX "index_child_on_teamTop_teamBottom" ON "child"("teamTop", "teamBottom") + """, + """ + CREATE INDEX "index_child_on_peopleMin_peopleMax" ON "child"("peopleMin", "peopleMax") + """, + """ + CREATE INDEX "index_child_on_customParentA_customParentB_customParentC" ON "child"("customParentA", "customParentB", "customParentC") + """, + """ + CREATE INDEX "index_child_on_customCountryLeft_customCountryRight" ON "child"("customCountryLeft", "customCountryRight") + """, + """ + CREATE INDEX "index_child_on_customTeamTop_customTeamBottom" ON "child"("customTeamTop", "customTeamBottom") + """, + """ + CREATE INDEX "index_child_on_customPersonMin_customPersonMax" ON "child"("customPersonMin", "customPersonMax") + """, + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_ifNotExists() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child", options: .ifNotExists) { t in + t.column("a") + t.belongsTo("parent") + // Modified case of table name + t.belongsTo("COUNTRY") + // Singularized table name + t.belongsTo("team") + // Raw plural table name + t.belongsTo("people") + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE IF NOT EXISTS "child" (\ + "a", \ + "parentA" TEXT, \ + "parentB" CUSTOM TYPE, \ + "parentC", \ + "COUNTRYLeft" TEXT, \ + "COUNTRYRight" INTEGER, \ + "teamTop" TEXT, \ + "teamBottom" INTEGER, \ + "peopleMin" TEXT, \ + "peopleMax" INTEGER, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right"), \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max")\ + ) + """, + """ + CREATE INDEX IF NOT EXISTS "index_child_on_parentA_parentB_parentC" ON "child"("parentA", "parentB", "parentC") + """, + """ + CREATE INDEX IF NOT EXISTS "index_child_on_COUNTRYLeft_COUNTRYRight" ON "child"("COUNTRYLeft", "COUNTRYRight") + """, + """ + CREATE INDEX IF NOT EXISTS "index_child_on_teamTop_teamBottom" ON "child"("teamTop", "teamBottom") + """, + """ + CREATE INDEX IF NOT EXISTS "index_child_on_peopleMin_peopleMax" ON "child"("peopleMin", "peopleMax") + """, + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_unique() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").unique() + // Modified case of table name + t.belongsTo("COUNTRY").unique() + // Singularized table name + t.belongsTo("team").unique() + // Raw plural table name + t.belongsTo("people").unique() + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentA" TEXT, \ + "parentB" CUSTOM TYPE, \ + "parentC", \ + "COUNTRYLeft" TEXT, \ + "COUNTRYRight" INTEGER, \ + "teamTop" TEXT, \ + "teamBottom" INTEGER, \ + "peopleMin" TEXT, \ + "peopleMax" INTEGER, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right"), \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max")\ + ) + """, + """ + CREATE UNIQUE INDEX "index_child_on_parentA_parentB_parentC" ON "child"("parentA", "parentB", "parentC") + """, + """ + CREATE UNIQUE INDEX "index_child_on_COUNTRYLeft_COUNTRYRight" ON "child"("COUNTRYLeft", "COUNTRYRight") + """, + """ + CREATE UNIQUE INDEX "index_child_on_teamTop_teamBottom" ON "child"("teamTop", "teamBottom") + """, + """ + CREATE UNIQUE INDEX "index_child_on_peopleMin_peopleMax" ON "child"("peopleMin", "peopleMax") + """, + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_notIndexed() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", indexed: false) + // Modified case of table name + t.belongsTo("COUNTRY", indexed: false) + // Singularized table name + t.belongsTo("team", indexed: false) + // Raw plural table name + t.belongsTo("people", indexed: false) + t.column("e") + } + + XCTAssertEqual(lastSQLQuery, """ + CREATE TABLE "child" (\ + "a", \ + "parentA" TEXT, \ + "parentB" CUSTOM TYPE, \ + "parentC", \ + "COUNTRYLeft" TEXT, \ + "COUNTRYRight" INTEGER, \ + "teamTop" TEXT, \ + "teamBottom" INTEGER, \ + "peopleMin" TEXT, \ + "peopleMax" INTEGER, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right"), \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max")\ + ) + """) + } + } + + func testTable_belongsTo_compositePrimaryKey_notNull() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent").notNull() + // Modified case of table name + t.belongsTo("COUNTRY").notNull() + // Singularized table name + t.belongsTo("team").notNull() + // Raw plural table name + t.belongsTo("people").notNull() + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentA" TEXT NOT NULL, \ + "parentB" CUSTOM TYPE NOT NULL, \ + "parentC" NOT NULL, \ + "COUNTRYLeft" TEXT NOT NULL, \ + "COUNTRYRight" INTEGER NOT NULL, \ + "teamTop" TEXT NOT NULL, \ + "teamBottom" INTEGER NOT NULL, \ + "peopleMin" TEXT NOT NULL, \ + "peopleMax" INTEGER NOT NULL, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c"), \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right"), \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom"), \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max")\ + ) + """, + """ + CREATE INDEX "index_child_on_parentA_parentB_parentC" ON "child"("parentA", "parentB", "parentC") + """, + """ + CREATE INDEX "index_child_on_COUNTRYLeft_COUNTRYRight" ON "child"("COUNTRYLeft", "COUNTRYRight") + """, + """ + CREATE INDEX "index_child_on_teamTop_teamBottom" ON "child"("teamTop", "teamBottom") + """, + """ + CREATE INDEX "index_child_on_peopleMin_peopleMax" ON "child"("peopleMin", "peopleMax") + """, + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_foreignKeyOptions() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parent") { t in + t.column("a", .text) + t.column("b", .init(rawValue: "CUSTOM TYPE")) // Custom type + t.column("c") // No declared type + t.primaryKey(["a", "b", "c"]) + } + + try db.create(table: "country") { t in + t.primaryKey { + t.column("left", .text) + t.column("right", .integer) + } + } + + // Plural table + try db.create(table: "teams") { t in + t.primaryKey { + t.column("top", .text) + t.column("bottom", .integer) + } + } + + // Plural table + try db.create(table: "people") { t in + t.primaryKey { + t.column("min", .text) + t.column("max", .integer) + } + } + + sqlQueries.removeAll() + try db.create(table: "child") { t in + t.column("a") + t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Modified case of table name + t.belongsTo("COUNTRY", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Singularized table name + t.belongsTo("team", onDelete: .cascade, onUpdate: .setNull, deferred: true) + // Raw plural table name + t.belongsTo("people", onDelete: .cascade, onUpdate: .setNull, deferred: true) + t.column("e") + } + + XCTAssertEqual(sqlQueries.suffix(5), [ + """ + CREATE TABLE "child" (\ + "a", \ + "parentA" TEXT, \ + "parentB" CUSTOM TYPE, \ + "parentC", \ + "COUNTRYLeft" TEXT, \ + "COUNTRYRight" INTEGER, \ + "teamTop" TEXT, \ + "teamBottom" INTEGER, \ + "peopleMin" TEXT, \ + "peopleMax" INTEGER, \ + "e", \ + FOREIGN KEY ("parentA", "parentB", "parentC") REFERENCES "parent"("a", "b", "c") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + FOREIGN KEY ("COUNTRYLeft", "COUNTRYRight") REFERENCES "COUNTRY"("left", "right") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + FOREIGN KEY ("teamTop", "teamBottom") REFERENCES "teams"("top", "bottom") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED, \ + FOREIGN KEY ("peopleMin", "peopleMax") REFERENCES "people"("min", "max") ON DELETE CASCADE ON UPDATE SET NULL DEFERRABLE INITIALLY DEFERRED\ + ) + """, + """ + CREATE INDEX "index_child_on_parentA_parentB_parentC" ON "child"("parentA", "parentB", "parentC") + """, + """ + CREATE INDEX "index_child_on_COUNTRYLeft_COUNTRYRight" ON "child"("COUNTRYLeft", "COUNTRYRight") + """, + """ + CREATE INDEX "index_child_on_teamTop_teamBottom" ON "child"("teamTop", "teamBottom") + """, + """ + CREATE INDEX "index_child_on_peopleMin_peopleMax" ON "child"("peopleMin", "peopleMax") + """, + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_autoreference_singular() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "employee") { t in + t.primaryKey { + t.column("left") + t.column("right") + } + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employee") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employee" (\ + "left" NOT NULL, \ + "right" NOT NULL, \ + "a", \ + "employeeLeft", \ + "employeeRight", \ + "customLeft", \ + "customRight", \ + "b", \ + PRIMARY KEY ("left", "right"), \ + FOREIGN KEY ("employeeLeft", "employeeRight") REFERENCES "employee"("left", "right"), \ + FOREIGN KEY ("customLeft", "customRight") REFERENCES "employee"("left", "right")\ + ) + """, + """ + CREATE INDEX "index_employee_on_employeeLeft_employeeRight" ON "employee"("employeeLeft", "employeeRight") + """, + """ + CREATE INDEX "index_employee_on_customLeft_customRight" ON "employee"("customLeft", "customRight") + """ + ]) + } + } + + func testTable_belongsTo_compositePrimaryKey_autoreference_plural() throws { + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "employees") { t in + t.primaryKey { + t.column("left") + t.column("right") + } + t.column("a") + t.belongsTo("employee") + t.belongsTo("custom", inTable: "employees") + t.column("b") + } + + XCTAssertEqual(sqlQueries.suffix(3), [ + """ + CREATE TABLE "employees" (\ + "left" NOT NULL, \ + "right" NOT NULL, \ + "a", \ + "employeeLeft", \ + "employeeRight", \ + "customLeft", \ + "customRight", \ + "b", \ + PRIMARY KEY ("left", "right"), \ + FOREIGN KEY ("employeeLeft", "employeeRight") REFERENCES "employees"("left", "right"), \ + FOREIGN KEY ("customLeft", "customRight") \ + REFERENCES "employees"("left", "right")\ + ) + """, + """ + CREATE INDEX "index_employees_on_employeeLeft_employeeRight" ON "employees"("employeeLeft", "employeeRight") + """, + """ + CREATE INDEX "index_employees_on_customLeft_customRight" ON "employees"("customLeft", "customRight") + """ + ]) + } + } + + func testTable_belongsTo_as_primary_key() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "composite") { t in + t.primaryKey { + t.column("a", .text) + t.column("b", .text) + } + } + try db.create(table: "simple") { t in + t.autoIncrementedPrimaryKey("id") + } + + do { + try db.create(table: "compositeChild") { t in + t.primaryKey { + t.belongsTo("composite") + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "compositeChild" (\ + "compositeA" TEXT NOT NULL, \ + "compositeB" TEXT NOT NULL, \ + PRIMARY KEY ("compositeA", "compositeB"), \ + FOREIGN KEY ("compositeA", "compositeB") REFERENCES "composite"("a", "b")\ + ) + """) + } + + do { + try db.create(table: "simpleChild") { t in + t.primaryKey { + t.belongsTo("simple") + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "simpleChild" (\ + "simpleId" INTEGER NOT NULL REFERENCES "simple"("id"), \ + PRIMARY KEY ("simpleId")\ + ) + """) + } + + do { + try db.create(table: "complex") { t in + t.primaryKey { + t.column("a") + t.belongsTo("composite") + t.belongsTo("simple") + t.column("b") + } + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "complex" (\ + "a" NOT NULL, \ + "compositeA" TEXT NOT NULL, \ + "compositeB" TEXT NOT NULL, \ + "simpleId" INTEGER NOT NULL REFERENCES "simple"("id"), \ + "b" NOT NULL, \ + PRIMARY KEY ("a", "compositeA", "compositeB", "simpleId", "b"), \ + FOREIGN KEY ("compositeA", "compositeB") REFERENCES "composite"("a", "b")\ + ) + """) + } + } + } + + func testTable_invalid_belongsTo_as_primary_key() throws { + try makeDatabaseQueue().inDatabase { db in + do { + // Invalid circular definition + try db.create(table: "player") { t in + t.primaryKey { + t.belongsTo("player") + } + } + XCTFail("Expected error") + } catch { } + } + } +} diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 9b73b2a57..cad002a0b 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -678,11 +678,22 @@ class TableDefinitionTests: GRDBTestCase { try db.create(table: "test4") { t in t.column("parent", .integer).references("test4") } - assertEqualSQL( - lastSQLQuery!, - ("CREATE TABLE \"test4\" (" + - "\"parent\" INTEGER REFERENCES \"test4\"(\"rowid\")" + - ")") as String) + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test4" (\ + "parent" INTEGER REFERENCES "test4"("rowid")\ + ) + """) + + try db.create(table: "test5") { t in + t.column("parent", .integer) + t.foreignKey(["parent"], references: "test5") + } + assertEqualSQL(lastSQLQuery!, """ + CREATE TABLE "test5" (\ + "parent" INTEGER, \ + FOREIGN KEY ("parent") REFERENCES "test5"("rowid")\ + ) + """) } } @@ -732,6 +743,40 @@ class TableDefinitionTests: GRDBTestCase { } } + func testAlterTableAddAutoReferencingForeignKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + try db.create(table: "hiddenRowIdTable") { t in + t.column("a", .text) + } + + sqlQueries.removeAll() + try db.alter(table: "hiddenRowIdTable") { t in + t.add(column: "ref").references("hiddenRowIdTable") + } + XCTAssertEqual(lastSQLQuery, """ + ALTER TABLE "hiddenRowIdTable" ADD COLUMN "ref" REFERENCES "hiddenRowIdTable"("rowid") + """) + } + + do { + try db.create(table: "explicitPrimaryKey") { t in + t.primaryKey("code", .text) + t.column("a", .text) + } + + sqlQueries.removeAll() + try db.alter(table: "explicitPrimaryKey") { t in + t.add(column: "ref").references("explicitPrimaryKey") + } + XCTAssertEqual(lastSQLQuery, """ + ALTER TABLE "explicitPrimaryKey" ADD COLUMN "ref" REFERENCES "explicitPrimaryKey"("code") + """) + } + } + } + func testAlterTableAddColumnInvalidatesSchemaCache() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From 7a0a354d2244e03974f01969086cd57f088002d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 11:37:57 +0200 Subject: [PATCH 23/28] Implement ForeignKeyDefinition --- GRDB.xcodeproj/project.pbxproj | 36 + .../SQLGeneration/SQLColumnGenerator.swift | 145 ++ .../SQLGeneration/SQLIndexGenerator.swift | 40 + .../SQLTableAlterationGenerator.swift | 84 + .../SQLGeneration/SQLTableGenerator.swift | 476 ++++ .../Schema/ColumnDefinition.swift | 567 +++++ .../Schema/Database+SchemaDefinition.swift | 651 ++++++ .../Schema/ForeignKeyDefinition.swift | 106 + .../Schema/IndexDefinition.swift | 26 + .../Schema/TableAlteration.swift | 163 ++ .../Schema/TableDefinition.swift | 2010 ++--------------- GRDBCustom.xcodeproj/project.pbxproj | 36 + 12 files changed, 2556 insertions(+), 1784 deletions(-) create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift create mode 100644 GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift create mode 100644 GRDB/QueryInterface/Schema/ColumnDefinition.swift create mode 100644 GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift create mode 100644 GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift create mode 100644 GRDB/QueryInterface/Schema/IndexDefinition.swift create mode 100644 GRDB/QueryInterface/Schema/TableAlteration.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 13d88f449..78de977bb 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -94,6 +94,7 @@ 563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */; }; 563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */; }; 563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; + 563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; }; 563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; }; 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; }; 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; }; @@ -380,6 +381,14 @@ 56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; }; 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; }; + 56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */; }; + 56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */; }; + 56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */; }; + 56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */; }; + 56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */; }; + 56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */; }; + 56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */; }; + 56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */; }; 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; 56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; }; 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; }; @@ -494,6 +503,7 @@ 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = ""; }; 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = ""; }; 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; + 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = ""; }; 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; @@ -787,6 +797,14 @@ 56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; 56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; + 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = ""; }; + 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = ""; }; + 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = ""; }; + 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = ""; }; + 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = ""; }; + 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = ""; }; + 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = ""; }; + 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = ""; }; 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; @@ -1175,6 +1193,11 @@ 5656A8142295AF75001FF3FF /* Schema */ = { isa = PBXGroup; children = ( + 56F89DF62A57EAA9002FE2AA /* ColumnDefinition.swift */, + 56F89E012A57EB87002FE2AA /* Database+SchemaDefinition.swift */, + 56F89DFB2A57EAEA002FE2AA /* ForeignKeyDefinition.swift */, + 56F89DFD2A57EB19002FE2AA /* IndexDefinition.swift */, + 56F89DFF2A57EB5C002FE2AA /* TableAlteration.swift */, 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */, 5698AC771DA37DCB0056AF8C /* VirtualTableModule.swift */, ); @@ -1184,8 +1207,12 @@ 5656A8162295AFD6001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( + 56F89E0D2A57EC2B002FE2AA /* SQLColumnGenerator.swift */, 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, + 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */, 568D13182207213E00674B58 /* SQLQueryGenerator.swift */, + 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */, + 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -2055,6 +2082,7 @@ 563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */, 564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */, 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 56F89DFE2A57EB19002FE2AA /* IndexDefinition.swift in Sources */, 566B91131FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 5605F1591C672E4000235C62 /* CGFloat.swift in Sources */, 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2074,6 +2102,7 @@ 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */, + 56F89E022A57EB87002FE2AA /* Database+SchemaDefinition.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, @@ -2087,6 +2116,8 @@ 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */, + 56F89E0C2A57EC16002FE2AA /* SQLTableGenerator.swift in Sources */, + 56F89DFC2A57EAEA002FE2AA /* ForeignKeyDefinition.swift in Sources */, 56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, @@ -2106,6 +2137,7 @@ 5657AB0F1D10899D006283EF /* URL.swift in Sources */, 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, + 56F89E152A585C0B002FE2AA /* SQLTableAlterationGenerator.swift in Sources */, 56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */, @@ -2121,6 +2153,7 @@ 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, + 56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */, 5611620825757583007AAF99 /* JoinAssociation.swift in Sources */, 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */, @@ -2128,8 +2161,10 @@ 568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56894FB72606589700268F4D /* Decimal.swift in Sources */, + 56F89E002A57EB5C002FE2AA /* TableAlteration.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */, + 56F89E0E2A57EC2B002FE2AA /* SQLColumnGenerator.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, @@ -2150,6 +2185,7 @@ 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56E9FADA221053DD00C703A8 /* SQL.swift in Sources */, 56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */, + 563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56781B0B243F86E600650A83 /* Refinable.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, diff --git a/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift new file mode 100644 index 000000000..d8754514c --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLColumnGenerator.swift @@ -0,0 +1,145 @@ +enum SQLColumnGenerator { + case columnDefinition(ColumnDefinition) + case columnLiteral(SQL) + + /// - parameter tableName: The name of the table that contains + /// the column. + /// - parameter primaryKeyColumns: A closure that returns the + /// primary key columns in the table that contains the column. If + /// the result is nil, the primary key is the hidden rowID. + func sql( + _ db: Database, + tableName: String, + primaryKeyColumns: () throws -> [SQLColumnDescriptor]?) + throws -> String + { + switch self { + case let .columnDefinition(column): + return try columnSQL( + db, column: column, + tableName: tableName, + primaryKeyColumns: primaryKeyColumns) + + case let .columnLiteral(sqlLiteral): + let context = SQLGenerationContext(db, argumentsSink: .literalValues) + return try sqlLiteral.sql(context) + } + } + + private func columnSQL( + _ db: Database, + column: ColumnDefinition, + tableName: String, + primaryKeyColumns: () throws -> [SQLColumnDescriptor]?) + throws -> String + { + var chunks: [String] = [] + chunks.append(column.name.quotedDatabaseIdentifier) + + if let type = column.type { + chunks.append(type.rawValue) + } + + if let (conflictResolution, autoincrement) = column.primaryKey { + chunks.append("PRIMARY KEY") + if let conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + if autoincrement { + chunks.append("AUTOINCREMENT") + } + } + + switch column.notNullConflictResolution { + case .none: + break + case .abort: + chunks.append("NOT NULL") + case let conflictResolution?: + chunks.append("NOT NULL ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + + switch column.indexing { + case .none: + break + case .unique(let conflictResolution): + switch conflictResolution { + case .abort: + chunks.append("UNIQUE") + default: + chunks.append("UNIQUE ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + case .index: + break + } + + for checkConstraint in column.checkConstraints { + try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))") + } + + if let defaultExpression = column.defaultExpression { + try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))") + } + + if let collationName = column.collationName { + chunks.append("COLLATE") + chunks.append(collationName) + } + + for constraint in column.foreignKeyConstraints { + chunks.append("REFERENCES") + if let column = constraint.destinationColumn { + // explicit referenced column names + chunks.append(""" + \(constraint.destinationTable.quotedDatabaseIdentifier)\ + (\(column.quotedDatabaseIdentifier)) + """) + } else { + // implicit reference to primary key + let pkColumns: [String] + + if constraint.destinationTable.lowercased() == tableName.lowercased() { + // autoreference + let primaryKeyColumns = try primaryKeyColumns() ?? [.rowID] + pkColumns = primaryKeyColumns.map(\.name) + } else { + pkColumns = try db.primaryKey(constraint.destinationTable).columns + } + + chunks.append(""" + \(constraint.destinationTable.quotedDatabaseIdentifier)\ + (\(pkColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))) + """) + } + + if let deleteAction = constraint.deleteAction { + chunks.append("ON DELETE") + chunks.append(deleteAction.rawValue) + } + if let updateAction = constraint.updateAction { + chunks.append("ON UPDATE") + chunks.append(updateAction.rawValue) + } + if constraint.isDeferred { + chunks.append("DEFERRABLE INITIALLY DEFERRED") + } + } + + if let constraint = column.generatedColumnConstraint { + try chunks.append("GENERATED ALWAYS AS (\(constraint.expression.quotedSQL(db)))") + let qualificationLiteral: String + switch constraint.qualification { + case .stored: + qualificationLiteral = "STORED" + case .virtual: + qualificationLiteral = "VIRTUAL" + } + chunks.append(qualificationLiteral) + } + + return chunks.joined(separator: " ") + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift new file mode 100644 index 000000000..35d3662ff --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLIndexGenerator.swift @@ -0,0 +1,40 @@ +struct SQLIndexGenerator { + let name: String + let table: String + let columns: [String] + let options: IndexOptions + let condition: SQLExpression? + + func sql(_ db: Database) throws -> String { + var chunks: [String] = [] + chunks.append("CREATE") + if options.contains(.unique) { + chunks.append("UNIQUE") + } + chunks.append("INDEX") + if options.contains(.ifNotExists) { + chunks.append("IF NOT EXISTS") + } + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("ON") + chunks.append(""" + \(table.quotedDatabaseIdentifier)(\ + \(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ + ) + """) + if let condition { + try chunks.append("WHERE \(condition.quotedSQL(db))") + } + return chunks.joined(separator: " ") + } +} + +extension SQLIndexGenerator { + init(index: IndexDefinition) { + name = index.name + table = index.table + columns = index.columns + options = index.options + condition = index.condition + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift new file mode 100644 index 000000000..030dfddb4 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLTableAlterationGenerator.swift @@ -0,0 +1,84 @@ +struct SQLTableAlterationGenerator { + private enum TableAlterationKind { + case addColumn(SQLColumnGenerator) + case addIndex(SQLIndexGenerator) + case renameColumn(old: String, new: String) + case dropColumn(String) + } + + private var name: String + private var alterations: [TableAlterationKind] = [] + + func sql(_ db: Database) throws -> String { + var statements: [String] = [] + + for alteration in alterations { + switch alteration { + case let .addColumn(column): + var chunks: [String] = [] + chunks.append("ALTER TABLE") + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("ADD COLUMN") + let sql = try column.sql(db, tableName: name, primaryKeyColumns: { + try db.primaryKey(name).columnInfos.map { columnInfos in + columnInfos.map { SQLColumnDescriptor($0) } + } + }) + chunks.append(sql) + let statement = chunks.joined(separator: " ") + statements.append(statement) + + case let .addIndex(index): + try statements.append(index.sql(db)) + + case let .renameColumn(oldName, newName): + var chunks: [String] = [] + chunks.append("ALTER TABLE") + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("RENAME COLUMN") + chunks.append(oldName.quotedDatabaseIdentifier) + chunks.append("TO") + chunks.append(newName.quotedDatabaseIdentifier) + let statement = chunks.joined(separator: " ") + statements.append(statement) + + case let .dropColumn(column): + var chunks: [String] = [] + chunks.append("ALTER TABLE") + chunks.append(name.quotedDatabaseIdentifier) + chunks.append("DROP COLUMN") + chunks.append(column.quotedDatabaseIdentifier) + let statement = chunks.joined(separator: " ") + statements.append(statement) + } + } + + return statements.joined(separator: "; ") + } +} + +extension SQLTableAlterationGenerator { + init(_ tableAlteration: TableAlteration) { + self.name = tableAlteration.name + self.alterations = [] + + for alteration in tableAlteration.alterations { + switch alteration { + case let .add(column): + alterations.append(.addColumn(.columnDefinition(column))) + if let indexDefinition = column.indexDefinition(in: name) { + alterations.append(.addIndex(SQLIndexGenerator(index: indexDefinition))) + } + + case let .addColumnLiteral(sql): + alterations.append(.addColumn(.columnLiteral(sql))) + + case let .rename(old: oldName, new: newName): + alterations.append(.renameColumn(old: oldName, new: newName)) + + case let .drop(column): + alterations.append(.dropColumn(column)) + } + } + } +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift new file mode 100644 index 000000000..69cd9de15 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/SQLTableGenerator.swift @@ -0,0 +1,476 @@ +struct SQLTableGenerator { + var name: String + var options: TableOptions + var columnGenerators: [SQLColumnGenerator] + /// Used for auto-referencing foreign keys: we need to know the columns + /// of the primary key before they exist in the database schema, hence + /// the name of "forward" primary key columns. + /// + /// If nil, the primary key is the hidden rowID. + var forwardPrimaryKeyColumns: [SQLColumnDescriptor]? + var primaryKeyConstraint: KeyConstraint? + var uniqueKeyConstraints: [KeyConstraint] + var foreignKeyConstraints: [SQLForeignKeyConstraint] + var checkConstraints: [SQLExpression] + var literalConstraints: [SQL] + var indexGenerators: [SQLIndexGenerator] + + struct KeyConstraint { + var columns: [String] + var conflictResolution: Database.ConflictResolution? + } + + func sql(_ db: Database) throws -> String { + var statements: [String] = [] + + do { + var chunks: [String] = [] + chunks.append("CREATE") + if options.contains(.temporary) { + chunks.append("TEMPORARY") + } + chunks.append("TABLE") + if options.contains(.ifNotExists) { + chunks.append("IF NOT EXISTS") + } + chunks.append(name.quotedDatabaseIdentifier) + + do { + var items: [String] = [] + try items.append(contentsOf: columnGenerators.map { + try $0.sql(db, tableName: name, primaryKeyColumns: { forwardPrimaryKeyColumns }) + }) + + if let constraint = primaryKeyConstraint { + var chunks: [String] = [] + chunks.append("PRIMARY KEY") + chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") + if let conflictResolution = constraint.conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joined(separator: " ")) + } + + for constraint in uniqueKeyConstraints { + var chunks: [String] = [] + chunks.append("UNIQUE") + chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") + if let conflictResolution = constraint.conflictResolution { + chunks.append("ON CONFLICT") + chunks.append(conflictResolution.rawValue) + } + items.append(chunks.joined(separator: " ")) + } + + for constraint in foreignKeyConstraints { + var chunks: [String] = [] + chunks.append("FOREIGN KEY") + chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") + chunks.append("REFERENCES") + if let destinationColumns = constraint.destinationColumns { + chunks.append(""" + \(constraint.destinationTable.quotedDatabaseIdentifier)(\ + \(destinationColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ + ) + """) + } else if constraint.destinationTable.lowercased() == name.lowercased() { + // autoreference + let forwardPrimaryKeyColumns = forwardPrimaryKeyColumns ?? [.rowID] + chunks.append(""" + \(constraint.destinationTable.quotedDatabaseIdentifier)(\ + \(forwardPrimaryKeyColumns.map(\.name.quotedDatabaseIdentifier).joined(separator: ", "))\ + ) + """) + } else { + let primaryKey = try db.primaryKey(constraint.destinationTable) + chunks.append(""" + \(constraint.destinationTable.quotedDatabaseIdentifier)(\ + \(primaryKey.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ + ) + """) + } + if let deleteAction = constraint.deleteAction { + chunks.append("ON DELETE") + chunks.append(deleteAction.rawValue) + } + if let updateAction = constraint.updateAction { + chunks.append("ON UPDATE") + chunks.append(updateAction.rawValue) + } + if constraint.isDeferred { + chunks.append("DEFERRABLE INITIALLY DEFERRED") + } + items.append(chunks.joined(separator: " ")) + } + + for checkExpression in checkConstraints { + var chunks: [String] = [] + try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))") + items.append(chunks.joined(separator: " ")) + } + + for literal in literalConstraints { + let context = SQLGenerationContext(db, argumentsSink: .literalValues) + try items.append(literal.sql(context)) + } + + chunks.append("(\(items.joined(separator: ", ")))") + } + + var tableOptions: [String] = [] + +#if GRDBCUSTOMSQLITE || GRDBCIPHER + if options.contains(.strict) { + tableOptions.append("STRICT") + } +#else + if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+ + 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: " ")) + } + + let indexStatements = try indexGenerators.map { try $0.sql(db) } + statements.append(contentsOf: indexStatements) + return statements.joined(separator: "; ") + } + + private struct ForeignKeyGenerator { + var columnNames: [String] + var columnGenerators: [SQLColumnGenerator] + var foreignKeyConstraint: SQLForeignKeyConstraint? + var indexGenerator: SQLIndexGenerator? + } +} + +extension SQLTableGenerator { + init(_ db: Database, table: TableDefinition) throws { + var indexOptions: IndexOptions = [] + if table.options.contains(.ifNotExists) { indexOptions.insert(.ifNotExists) } + + func makeKeyConstraint( + _ db: Database, + constraint: TableDefinition.KeyConstraint, + forwardPrimaryKey: SQLPrimaryKeyDescriptor) + throws -> SQLTableGenerator.KeyConstraint + { + try SQLTableGenerator.KeyConstraint( + columns: constraint.components.flatMap { component -> [String] in + switch component { + case let .columnName(columnName): + return [columnName] + case let .columnDefinition(column): + return [column.name] + case let .foreignKeyDefinition(foreignKey): + return try Self.makeForeignKeyGenerator( + db, foreignKey: foreignKey, + originTable: table.name, + forwardPrimaryKey: forwardPrimaryKey, + indexOptions: indexOptions).columnNames + } + }, + conflictResolution: constraint.conflictResolution) + } + + var forwardPrimaryKeyColumns: [SQLColumnDescriptor]? + if let primaryKeyConstraint = table.primaryKeyConstraint { + forwardPrimaryKeyColumns = try Self.forwardPrimaryKeyColumns( + db, primaryKeyConstraint: primaryKeyConstraint, + originTable: table.name) + } else { + for component in table.columnComponents { + if case let .columnDefinition(column) = component, column.primaryKey != nil { + forwardPrimaryKeyColumns = [SQLColumnDescriptor(column)] + break + } + } + } + let forwardPrimaryKey = SQLPrimaryKeyDescriptor( + tableName: table.name, + primaryKeyColumns: forwardPrimaryKeyColumns) + + var columnGenerators: [SQLColumnGenerator] = [] + var foreignKeyConstraints: [SQLForeignKeyConstraint] = [] + var indexGenerators: [SQLIndexGenerator] = [] + + for component in table.columnComponents { + switch component { + case let .columnDefinition(column): + columnGenerators.append(.columnDefinition(column)) + + case let .columnLiteral(sql): + columnGenerators.append(.columnLiteral(sql)) + + case let .foreignKeyDefinition(foreignKey): + let fkGenerator = try Self.makeForeignKeyGenerator( + db, foreignKey: foreignKey, + originTable: table.name, + forwardPrimaryKey: forwardPrimaryKey, + indexOptions: indexOptions) + columnGenerators.append(contentsOf: fkGenerator.columnGenerators) + if let indexGenerator = fkGenerator.indexGenerator { + indexGenerators.append(indexGenerator) + } + if let foreignKeyConstraint = fkGenerator.foreignKeyConstraint { + foreignKeyConstraints.append(foreignKeyConstraint) + } + + case let .foreignKeyConstraint(constraint): + foreignKeyConstraints.append(constraint) + } + } + + for columnGenerator in columnGenerators { + if case let .columnDefinition(column) = columnGenerator, + let index = column.indexDefinition(in: table.name, options: indexOptions) + { + indexGenerators.append(SQLIndexGenerator(index: index)) + } + } + + try self.init( + name: table.name, + options: table.options, + columnGenerators: columnGenerators, + forwardPrimaryKeyColumns: forwardPrimaryKeyColumns, + primaryKeyConstraint: table.primaryKeyConstraint.map { + try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey) + }, + uniqueKeyConstraints: table.uniqueKeyConstraints.map { + try makeKeyConstraint(db, constraint: $0, forwardPrimaryKey: forwardPrimaryKey) + }, + foreignKeyConstraints: foreignKeyConstraints, + checkConstraints: table.checkConstraints, + literalConstraints: table.literalConstraints, + indexGenerators: indexGenerators) + } + + private static func forwardPrimaryKeyColumns( + _ db: Database, + primaryKeyConstraint: TableDefinition.KeyConstraint, + originTable: String) + throws -> [SQLColumnDescriptor]? + { + var forwardPrimaryKeyColumns: [SQLColumnDescriptor] = [] + for component in primaryKeyConstraint.components { + switch component { + case let .columnDefinition(column): + forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column)) + case let .foreignKeyDefinition(foreignKey): + let fkGenerator = try makeForeignKeyGenerator( + db, foreignKey: foreignKey, + originTable: originTable, + forwardPrimaryKey: nil, // not known yet, since we're building it + indexOptions: []) + for columnGenerator in fkGenerator.columnGenerators { + switch columnGenerator { + case let .columnDefinition(column): + forwardPrimaryKeyColumns.append(SQLColumnDescriptor(column)) + case .columnLiteral: + // Unknown column name + return nil + } + } + case let .columnName(name): + forwardPrimaryKeyColumns.append(SQLColumnDescriptor(name: name, type: nil)) + } + } + return forwardPrimaryKeyColumns + } + + private static func makeForeignKeyGenerator( + _ db: Database, + foreignKey: ForeignKeyDefinition, + originTable: String, + forwardPrimaryKey: SQLPrimaryKeyDescriptor?, + indexOptions: IndexOptions) + throws -> ForeignKeyGenerator + { + let destinationPrimaryKey: SQLPrimaryKeyDescriptor + + if let table = foreignKey.table { + if let forwardPrimaryKey, + originTable.lowercased() == table.lowercased() + { + // autoreference + destinationPrimaryKey = forwardPrimaryKey + } else { + destinationPrimaryKey = try foreignKey.primaryKey(db) + } + } else { + if let forwardPrimaryKey, + originTable.singularized.lowercased() == foreignKey.name.singularized.lowercased() + { + // autoreference + destinationPrimaryKey = forwardPrimaryKey + } else { + destinationPrimaryKey = try foreignKey.primaryKey(db) + } + } + + guard let primaryKeyColumns = destinationPrimaryKey.primaryKeyColumns else { + // Destination table has an hidden rowID primary key + let columnName = foreignKey.name + "Id" + let column = ColumnDefinition(name: columnName, type: .integer).references( + destinationPrimaryKey.tableName, + onDelete: foreignKey.deleteAction, + onUpdate: foreignKey.updateAction, + deferred: foreignKey.isDeferred) + if let notNullConflictResolution = foreignKey.notNullConflictResolution { + column.notNull(onConflict: notNullConflictResolution) + } + switch foreignKey.indexing { + case nil: + break + case .index: + column.indexed() + case .unique: + column.unique() + } + return ForeignKeyGenerator( + columnNames: [columnName], + columnGenerators: [SQLColumnGenerator.columnDefinition(column)], + foreignKeyConstraint: nil, + indexGenerator: nil) + } + + assert(!primaryKeyColumns.isEmpty) + let columnNames = primaryKeyColumns.map { + foreignKey.name + $0.name.uppercasingFirstCharacter + } + + if primaryKeyColumns.count == 1 { + // Destination table has a single column primary key + let pkColumn = primaryKeyColumns[0] + let columnName = columnNames[0] + let column = ColumnDefinition(name: columnName, type: pkColumn.type).references( + destinationPrimaryKey.tableName, + column: pkColumn.name, + onDelete: foreignKey.deleteAction, + onUpdate: foreignKey.updateAction, + deferred: foreignKey.isDeferred) + + if let notNullConflictResolution = foreignKey.notNullConflictResolution { + column.notNull(onConflict: notNullConflictResolution) + } + + switch foreignKey.indexing { + case nil: + break + case .index: + column.indexed() + case .unique: + column.unique() + } + + return ForeignKeyGenerator( + columnNames: [columnName], + columnGenerators: [SQLColumnGenerator.columnDefinition(column)], + foreignKeyConstraint: nil, + indexGenerator: nil) + } else { + // Destination table has a composite primary key + let columnGenerators = zip(primaryKeyColumns, columnNames).map { pkColumn, columnName in + let column = ColumnDefinition(name: columnName, type: pkColumn.type) + if let notNullConflictResolution = foreignKey.notNullConflictResolution { + column.notNull(onConflict: notNullConflictResolution) + } + return SQLColumnGenerator.columnDefinition(column) + } + + let foreignKeyConstraint = SQLForeignKeyConstraint( + columns: columnNames, + destinationTable: destinationPrimaryKey.tableName, + destinationColumns: nil, + deleteAction: foreignKey.deleteAction, + updateAction: foreignKey.updateAction, + isDeferred: foreignKey.isDeferred) + + let indexGenerator: SQLIndexGenerator? + switch foreignKey.indexing { + case nil: + indexGenerator = nil + case .index: + indexGenerator = SQLIndexGenerator( + name: Database.defaultIndexName(on: originTable, columns: columnNames), + table: originTable, + columns: columnNames, + options: indexOptions, + condition: nil) + case .unique: + indexGenerator = SQLIndexGenerator( + name: Database.defaultIndexName(on: originTable, columns: columnNames), + table: originTable, + columns: columnNames, + options: indexOptions.union([.unique]), + condition: nil) + } + + return ForeignKeyGenerator( + columnNames: columnNames, + columnGenerators: columnGenerators, + foreignKeyConstraint: foreignKeyConstraint, + indexGenerator: indexGenerator) + } + } +} + +struct SQLColumnDescriptor { + static let rowID = SQLColumnDescriptor(name: Column.rowID.name, type: .integer) + + var name: String + var type: Database.ColumnType? +} + +extension SQLColumnDescriptor { + init(_ column: ColumnInfo) { + self.init( + name: column.name, + type: column.columnType) + } + + init(_ column: ColumnDefinition) { + self.init(name: column.name, type: column.type) + } +} + +struct SQLForeignKeyConstraint { + var columns: [String] + var destinationTable: String + var destinationColumns: [String]? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var isDeferred: Bool +} + +struct SQLPrimaryKeyDescriptor { + /// The name of the forward-declared table + var tableName: String + + /// If nil, the primary key is the hidden rowID. + var primaryKeyColumns: [SQLColumnDescriptor]? +} + +extension SQLPrimaryKeyDescriptor { + static func find(_ db: Database, table: String) throws -> Self { + let columnInfos = try db.primaryKey(table).columnInfos + return SQLPrimaryKeyDescriptor( + tableName: table, + primaryKeyColumns: columnInfos.map { columnInfos in + columnInfos.map { SQLColumnDescriptor($0) } + }) + + } +} diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift new file mode 100644 index 000000000..9ca39370d --- /dev/null +++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift @@ -0,0 +1,567 @@ +/// Describes a database column. +/// +/// You get instances of `ColumnDefinition` when you create or alter a database +/// tables. For example: +/// +/// ```swift +/// try db.create(table: "player") { t in +/// t.column("name", .text) // ColumnDefinition +/// } +/// +/// try db.alter(table: "player") { t in +/// t.add(column: "score", .integer) // ColumnDefinition +/// } +/// ``` +/// +/// See ``TableDefinition/column(_:_:)`` and ``TableAlteration/add(column:_:)``. +/// +/// Related SQLite documentation: +/// +/// - +/// - +/// +/// ## Topics +/// +/// ### Foreign Keys +/// +/// - ``references(_:column:onDelete:onUpdate:deferred:)`` +/// +/// ### Indexes +/// +/// - ``indexed()`` +/// - ``unique(onConflict:)`` +/// +/// ### Default value +/// +/// - ``defaults(to:)`` +/// - ``defaults(sql:)`` +/// +/// ### Collations +/// +/// - ``collate(_:)-4dljx`` +/// - ``collate(_:)-9ywza`` +/// +/// ### Generated Columns +/// +/// - ``generatedAs(_:_:)`` +/// - ``generatedAs(sql:_:)`` +/// - ``GeneratedColumnQualification`` +/// +/// ### Other Constraints +/// +/// - ``check(_:)`` +/// - ``check(sql:)`` +/// - ``notNull(onConflict:)`` +/// +/// ### Sunsetted Methods +/// +/// Those are legacy interfaces that are preserved for backwards compatibility. +/// Their use is not recommended. +/// +/// - ``primaryKey(onConflict:autoincrement:)`` +public final class ColumnDefinition { + enum Indexing { + case index + case unique(Database.ConflictResolution) + } + + struct ForeignKeyConstraint { + var destinationTable: String + var destinationColumn: String? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var isDeferred: Bool + } + + /// The kind of a generated column. + /// + /// Related SQLite documentation: + public enum GeneratedColumnQualification { + /// A `VIRTUAL` generated column. + case virtual + /// A `STORED` generated column. + case stored + } + + struct GeneratedColumnConstraint { + var expression: SQLExpression + var qualification: GeneratedColumnQualification + } + + let name: String + let type: Database.ColumnType? + var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? + var indexing: Indexing? + var notNullConflictResolution: Database.ConflictResolution? + var checkConstraints: [SQLExpression] = [] + var foreignKeyConstraints: [ForeignKeyConstraint] = [] + var defaultExpression: SQLExpression? + var collationName: String? + var generatedColumnConstraint: GeneratedColumnConstraint? + + init(name: String, type: Database.ColumnType?) { + self.name = name + self.type = type + } + + /// Adds a primary key constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id TEXT NOT NULL PRIMARY KEY + /// // ) + /// try db.create(table: "player") { t in + /// t.primaryKey("id", .text) + /// } + /// ``` + /// + /// - important: Make sure you add a not null constraint on your primary key + /// column, as in the above example, or SQLite will allow null values. + /// See + /// for more information. + /// + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer + /// ``TableDefinition/primaryKey(_:_:onConflict:)`` + /// instead. + /// + /// - parameters: + /// - conflictResolution: An optional ``Database/ConflictResolution``. + /// - autoincrement: If true, the primary key is autoincremented. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func primaryKey( + onConflict conflictResolution: Database.ConflictResolution? = nil, + autoincrement: Bool = false) + -> Self + { + primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) + return self + } + + /// Adds a not null constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT NOT NULL + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).notNull() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + notNullConflictResolution = conflictResolution ?? .abort + return self + } + + /// Adds a unique constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT UNIQUE + /// // ) + /// try db.create(table: "player") { t in + /// t.column("email", .text).unique() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + indexing = .unique(conflictResolution ?? .abort) + return self + } + + /// Adds an index. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player(email TEXT); + /// // CREATE INDEX player_on_email ON player(email); + /// try db.create(table: "player") { t in + /// t.column("email", .text).indexed() + /// } + /// ``` + /// + /// The name of the created index is `_on_`, where `table` + /// and `column` are the names of the table and the column. See the + /// example above. + /// + /// See also ``unique(onConflict:)``. + /// + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func indexed() -> Self { + if case .none = indexing { + self.indexing = .index + } + return self + } + + /// Adds a check constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check { length($0) > 0 } + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter condition: A closure whose argument is a ``Column`` that + /// represents the defined column, and returns the expression to check. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func check(_ condition: (Column) -> any SQLExpressible) -> Self { + checkConstraints.append(condition(Column(name)).sqlExpression) + return self + } + + /// Adds a check constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // name TEXT CHECK (LENGTH(name) > 0) + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).check(sql: "LENGTH(name) > 0") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter sql: An SQL snippet. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func check(sql: String) -> Self { + checkConstraints.append(SQL(sql: sql).sqlExpression) + return self + } + + /// Defines the default value. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT DEFAULT 'Anonymous' + /// // ) + /// try db.create(table: "player") { t in + /// t.column("name", .text).defaults(to: "Anonymous") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter value: A ``DatabaseValueConvertible`` value. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func defaults(to value: some DatabaseValueConvertible) -> Self { + defaultExpression = value.sqlExpression + return self + } + + /// Defines the default value. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP + /// // ) + /// try db.create(table: "player") { t in + /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter sql: An SQL snippet. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func defaults(sql: String) -> Self { + defaultExpression = SQL(sql: sql).sqlExpression + return self + } + + /// Defines the default collation. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // email TEXT COLLATE NOCASE + /// // ) + /// try db.create(table: "player") { t in + /// t.column("email", .text).collate(.nocase) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter collation: A ``Database/CollationName``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func collate(_ collation: Database.CollationName) -> Self { + collationName = collation.rawValue + return self + } + + /// Defines the default collation. + /// + /// For example: + /// + /// ```swift + /// try db.create(table: "player") { t in + /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter collation: A ``DatabaseCollation``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func collate(_ collation: DatabaseCollation) -> Self { + collationName = collation.name + return self + } + +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - sql: An SQL expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func generatedAs( + sql: String, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + let expression = SQL(sql: sql).sqlExpression + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression, + qualification: qualification) + return self + } + + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - expression: The generated expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func generatedAs( + _ expression: some SQLExpressible, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression.sqlExpression, + qualification: qualification) + return self + } +#else + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - sql: An SQL expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) + @discardableResult + public func generatedAs( + sql: String, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + let expression = SQL(sql: sql).sqlExpression + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression, + qualification: qualification) + return self + } + + /// Defines the column as a generated column. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // score INTEGER NOT NULL, + /// // bonus INTEGER NOT NULL, + /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("score", .integer).notNull() + /// t.column("bonus", .integer).notNull() + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - expression: The generated expression. + /// - qualification: The generated column's qualification, which + /// defaults to ``GeneratedColumnQualification/virtual``. + /// - returns: `self` so that you can further refine the column definition. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) + @discardableResult + public func generatedAs( + _ expression: some SQLExpressible, + _ qualification: GeneratedColumnQualification = .virtual) + -> Self + { + generatedColumnConstraint = GeneratedColumnConstraint( + expression: expression.sqlExpression, + qualification: qualification) + return self + } +#endif + + /// Adds a foreign key constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE book( + /// // authorId INTEGER REFERENCES author(id) ON DELETE CASCADE + /// // ) + /// try db.create(table: "book") { t in + /// t.column("authorId", .integer).references("author", onDelete: .cascade) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - table: The referenced table. + /// - column: The referenced column in the referenced table. If not + /// specified, the column of the primary key of the referenced table + /// is used. + /// - deleteAction: Optional action when the referenced row is deleted. + /// - updateAction: Optional action when the referenced row is updated. + /// - isDeferred: A boolean value indicating whether the foreign key + /// constraint is deferred. + /// See . + /// - returns: `self` so that you can further refine the column definition. + @discardableResult + public func references( + _ table: String, + column: String? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred isDeferred: Bool = false) -> Self + { + foreignKeyConstraints.append(ForeignKeyConstraint( + destinationTable: table, + destinationColumn: column, + deleteAction: deleteAction, + updateAction: updateAction, + isDeferred: isDeferred)) + return self + } + + func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? { + switch indexing { + case .none: return nil + case .unique: return nil + case .index: + return IndexDefinition( + name: "\(table)_on_\(name)", + table: table, + columns: [name], + options: options, + condition: nil) + } + } +} diff --git a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift new file mode 100644 index 000000000..b8f14ccf0 --- /dev/null +++ b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift @@ -0,0 +1,651 @@ +extension Database { + + // MARK: - Database Schema + + /// Creates a database table. + /// + /// For example: + /// + /// ```swift + /// 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() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// - + /// - + /// + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: 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. + /// + /// ### Reference documentation + /// + /// SQLite has many reference documents about table creation. They are a + /// great learning material: + /// + /// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) + /// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html) + /// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) + /// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html) + /// - [Rowid Tables](https://www.sqlite.org/rowidtable.html) + /// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) + /// - [STRICT Tables](https://www.sqlite.org/stricttables.html) + /// + /// ### Usage + /// + /// ```swift + /// // CREATE TABLE place ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // title TEXT, + /// // isFavorite BOOLEAN NOT NULL DEFAULT 0, + /// // latitude DOUBLE NOT NULL, + /// // longitude DOUBLE NOT NULL + /// // ) + /// try db.create(table: "place") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("title", .text) + /// t.column("isFavorite", .boolean).notNull().default(false) + /// t.column("longitude", .double).notNull() + /// t.column("latitude", .double).notNull() + /// } + /// ``` + /// + /// ### Configure table creation + /// + /// Use the `options` parameter to configure table creation + /// (see ``TableOptions``): + /// + /// ```swift + /// // CREATE TABLE player ( ... ) + /// try db.create(table: "player") { t in ... } + /// + /// // CREATE TEMPORARY TABLE player IF NOT EXISTS ( + /// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... } + /// ``` + /// + /// ### Add columns + /// + /// Add columns with their name and eventual type (`text`, `integer`, + /// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` + /// and `any`) - see ``Database/ColumnType``: + /// + /// ```swift + /// // CREATE TABLE example ( + /// // a, + /// // name TEXT, + /// // creationDate DATETIME, + /// try db.create(table: "example") { t in + /// t.column("a") + /// t.column("name", .text) + /// t.column("creationDate", .datetime) + /// ``` + /// + /// The `column()` method returns a ``ColumnDefinition`` that you can + /// further configure: + /// + /// ### Not null constraints, default values + /// + /// ```swift + /// // email TEXT NOT NULL, + /// t.column("email", .text).notNull() + /// + /// // name TEXT DEFAULT 'O''Reilly', + /// t.column("name", .text).defaults(to: "O'Reilly") + /// + /// // flag BOOLEAN NOT NULL DEFAULT 0, + /// t.column("flag", .boolean).notNull().defaults(to: false) + /// + /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP, + /// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP") + /// ``` + /// + /// ### Primary, unique, and foreign keys + /// + /// Use an individual column as **primary**, **unique**, or **foreign key**. + /// When defining a foreign key, the referenced column is the primary key of + /// the referenced table (unless you specify otherwise): + /// + /// ```swift + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// t.autoIncrementedPrimaryKey("id") + /// + /// // uuid TEXT NOT NULL PRIMARY KEY, + /// t.primaryKey("uuid", .text) + /// + /// // email TEXT UNIQUE, + /// t.column("email", .text) + /// .unique() + /// + /// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, + /// t.column("countryCode", .text) + /// .references("country", onDelete: .cascade) + /// ``` + /// + /// Primary, unique and foreign keys can also be added on several columns: + /// + /// ```swift + /// // a INTEGER NOT NULL, + /// // b TEXT NOT NULL, + /// // PRIMARY KEY (a, b) + /// t.primaryKey { + /// t.column("a", .integer) + /// t.column("b", .text) + /// } + /// + /// // a INTEGER NOT NULL, + /// // b TEXT NOT NULL, + /// // PRIMARY KEY (a, b) + /// t.column("a", .integer).notNull() + /// t.column("b", .text).notNull() + /// t.primaryKey(["a", "b"]) + /// + /// // a INTEGER, + /// // b TEXT, + /// // UNIQUE (a, b) ON CONFLICT REPLACE + /// t.column("a", .integer) + /// t.column("b", .text) + /// t.uniqueKey(["a", "b"], onConflict: .replace) + /// + /// // a INTEGER, + /// // b TEXT, + /// // FOREIGN KEY (a, b) REFERENCES parents(c, d) + /// t.column("a", .integer) + /// t.column("b", .text) + /// t.foreignKey(["a", "b"], references: "parents") + /// ``` + /// + /// > Tip: when you need an integer primary key that automatically generates + /// unique values, it is recommended that you use the + /// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method: + /// > + /// > ```swift + /// > try db.create(table: "example") { t in + /// > t.autoIncrementedPrimaryKey("id") + /// > ... + /// > } + /// > ``` + /// > + /// > The reason for this recommendation is that auto-incremented primary + /// > keys forbid the reuse of ids. This prevents your app or + /// > to think that a row was updated, when it was + /// > actually deleted and replaced. Depending on your application needs, + /// > this may be acceptable. But usually it is not. + /// + /// ### Indexed columns + /// + /// ```swift + /// t.column("score", .integer).indexed() + /// ``` + /// + /// For extra index options, see ``create(indexOn:columns:options:condition:)``. + /// + /// ### Generated columns + /// + /// See [Generated columns](https://sqlite.org/gencol.html) for + /// more information: + /// + /// ```swift + /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) + /// ``` + /// + /// ### Integrity checks + /// + /// SQLite will only let conforming rows in: + /// + /// ```swift + /// // name TEXT CHECK (LENGTH(name) > 0) + /// t.column("name", .text).check { length($0) > 0 } + /// + /// // score INTEGER CHECK (score > 0) + /// t.column("score", .integer).check(sql: "score > 0") + /// + /// // CHECK (a + b < 10), + /// t.check(Column("a") + Column("b") < 10) + /// + /// // CHECK (a + b < 10) + /// t.check(sql: "a + b < 10") + /// ``` + /// + /// ### Raw SQL columns and constraints + /// + /// Columns and constraints can be defined with raw sql: + /// + /// ```swift + /// t.column(sql: "name TEXT") + /// t.constraint(sql: "CHECK (a + b < 10)") + /// ``` + /// + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: + /// + /// ```swift + /// let defaultName = "O'Reilly" + /// t.column(literal: "name TEXT DEFAULT \(defaultName)") + /// + /// let forbiddenName = "admin" + /// t.constraint(literal: "CHECK (name <> \(forbiddenName))") + /// ``` + /// + /// - parameters: + /// - name: The table name. + /// - 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, + options: TableOptions = [], + body: (TableDefinition) throws -> Void) + throws + { + let table = TableDefinition( + name: name, + options: options) + try body(table) + let generator = try SQLTableGenerator(self, table: table) + let sql = try generator.sql(self) + try execute(sql: sql) + } + + /// Renames a database table. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func rename(table name: String, to newName: String) throws { + try execute(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") + } + + /// Modifies a database table. + /// + /// For example: + /// + /// ```swift + /// try db.alter(table: "player") { t in + /// t.add(column: "url", .text) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - name: The table name. + /// - body: A closure that defines table alterations. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func alter(table name: String, body: (TableAlteration) -> Void) throws { + let alteration = TableAlteration(name: name) + body(alteration) + let generator = SQLTableAlterationGenerator(alteration) + let sql = try generator.sql(self) + try execute(sql: sql) + } + + /// Deletes a database table. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(table name: String) throws { + try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") + } + + /// Creates a database view. + /// + /// You can create a view with an ``SQLRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", as: SQLRequest(literal: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// You can also create a view with a ``QueryInterfaceRequest``: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create( + /// view: "hero", + /// as: Player.filter(Column("isHero") == true)) + /// ``` + /// + /// When creating views in , it is not recommended to + /// use record types defined in the application. Instead of the `Player` + /// record type, prefer `Table("player")`: + /// + /// ```swift + /// // RECOMMENDED IN MIGRATIONS + /// try db.create( + /// view: "hero", + /// as: Table("player").filter(Column("isHero") == true)) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - request: The request that feeds the view. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + as request: SQLSubqueryable) + throws { + var literal: SQL = "CREATE " + + if options.contains(.temporary) { + literal += "TEMPORARY " + } + + literal += "VIEW " + + if options.contains(.ifNotExists) { + literal += "IF NOT EXISTS " + } + + literal += "\(identifier: name) " + + if let columns { + literal += "(" + literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ") + literal += ") " + } + + literal += "AS \(request)" + + // CREATE VIEW does not support arguments, so make sure we use + // literal values. + let context = SQLGenerationContext(self, argumentsSink: .literalValues) + let sql = try literal.sql(context) + try execute(sql: sql) + } + + /// Creates a database view. + /// + /// For example: + /// + /// ```swift + /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 + /// try db.create(view: "hero", asLiteral: """ + /// SELECT * FROM player WHERE isHero == 1 + /// """) + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - view: The view name. + /// - options: View creation options. + /// - columns: The columns of the view. If nil, the columns are the + /// columns of the request. + /// - sqlLiteral: An `SQL` literal. + public func create( + view name: String, + options: ViewOptions = [], + columns: [String]? = nil, + asLiteral sqlLiteral: SQL) + throws { + try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral)) + } + + /// Deletes a database view. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(view name: String) throws { + try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)") + } + + /// Creates an index. + /// + /// For example: + /// + /// ```swift + /// // CREATE INDEX index_player_on_email ON player(email) + /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"]) + /// ``` + /// + /// SQLite can also index expressions () + /// and use specific collations. To create such an index, use a raw SQL + /// query: + /// + /// ```swift + /// try db.execute(sql: "CREATE INDEX ...") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - warning: This is a legacy interface that is preserved for backwards + /// compatibility. Use of this interface is not recommended: prefer + /// ``create(indexOn: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 ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @_disfavoredOverload + public func create( + index name: String, + on table: String, + columns: [String], + unique: Bool = false, + ifNotExists: Bool = false, + condition: (any 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. + /// + /// For example: + /// + /// ```swift + /// // CREATE INDEX index_player_on_email ON player(email) + /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"]) + /// ``` + /// + /// To create a unique index, specify the `.unique` option: + /// + /// ```swift + /// // CREATE UNIQUE INDEX index_player_on_email ON player(email) + /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique) + /// ``` + /// + /// SQLite can also index expressions () + /// and use specific collations. To create such an index, use a raw SQL + /// query: + /// + /// ```swift + /// try db.execute(sql: "CREATE INDEX ...") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - name: The index name. + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - options: Index creation options. + /// - condition: If not nil, creates a partial index + /// (see ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func create( + index name: String, + on table: String, + columns: [String], + options: IndexOptions = [], + condition: (any SQLExpressible)? = nil) + throws + { + let index = IndexDefinition( + name: name, + table: table, + columns: columns, + options: options, + condition: condition?.sqlExpression) + let generator = SQLIndexGenerator(index: index) + let sql = try generator.sql(self) + try execute(sql: sql) + } + + /// Creates an index on the specified table and columns. + /// + /// The created index is named after the table and the column name(s): + /// + /// ```swift + /// // CREATE INDEX index_player_on_email ON player(email) + /// try db.create(indexOn: "player", columns: ["email"]) + /// ``` + /// + /// To create a unique index, specify the `.unique` option: + /// + /// ```swift + /// // CREATE UNIQUE INDEX index_player_on_email ON player(email) + /// try db.create(indexOn: "player", columns: ["email"], options: .unique) + /// ``` + /// + /// In order to specify the index name, use + /// ``create(index:on:columns:options:condition:)`` instead. + /// + /// SQLite can also index expressions () + /// and use specific collations. To create such an index, use a raw SQL + /// query: + /// + /// ```swift + /// try db.execute(sql: "CREATE INDEX ...") + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameters: + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - options: Index creation options. + /// - condition: If not nil, creates a partial index + /// (see ). + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func create( + indexOn table: String, + columns: [String], + options: IndexOptions = [], + condition: (any SQLExpressible)? = nil) + throws + { + try create( + index: Database.defaultIndexName(on: table, columns: columns), + on: table, + columns: columns, + options: options, + condition: condition) + } + + /// Deletes a database index. + /// + /// Related SQLite documentation: + /// + /// - parameter name: The index name. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(index name: String) throws { + try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)") + } + + /// Deletes the database index on the specified table and columns + /// if exactly one such index exists. + /// + /// - parameters: + /// - table: The name of the indexed table. + /// - columns: The indexed columns. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func drop(indexOn table: String, columns: [String]) throws { + let lowercasedColumns = columns.map { $0.lowercased() } + let indexes = try indexes(on: table).filter { index in + index.columns.map({ $0.lowercased() }) == lowercasedColumns + } + if let index = indexes.first, indexes.count == 1 { + try drop(index: index.name) + } + } + + /// Deletes and recreates from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func reindex(collation: Database.CollationName) throws { + try execute(sql: "REINDEX \(collation.rawValue)") + } + + /// Deletes and recreates from scratch all indices that use this collation. + /// + /// This method is useful when the definition of a collation sequence + /// has changed. + /// + /// Related SQLite documentation: + /// + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + public func reindex(collation: DatabaseCollation) throws { + try reindex(collation: Database.CollationName(rawValue: collation.name)) + } +} + +/// View creation options +public struct ViewOptions: OptionSet { + public let rawValue: Int + + public init(rawValue: Int) { self.rawValue = rawValue } + + /// Only creates the view if it does not already exist. + public static let ifNotExists = ViewOptions(rawValue: 1 << 0) + + /// Creates a temporary view. + public static let temporary = ViewOptions(rawValue: 1 << 1) +} diff --git a/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift b/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift new file mode 100644 index 000000000..7da337ec6 --- /dev/null +++ b/GRDB/QueryInterface/Schema/ForeignKeyDefinition.swift @@ -0,0 +1,106 @@ +/// Describes an association in the database schema. +/// +/// You get instances of `ForeignKeyDefinition` when you create a database +/// tables. For example: +/// +/// ```swift +/// try db.create(table: "player") { t in +/// t.belongsTo("team") // ForeignKeyDefinition +/// } +/// ``` +/// +/// See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)``. +public final class ForeignKeyDefinition { + enum Indexing { + case index + case unique + } + + var name: String + var table: String? + var deleteAction: Database.ForeignKeyAction? + var updateAction: Database.ForeignKeyAction? + var indexing: Indexing? + var isDeferred: Bool + var notNullConflictResolution: Database.ConflictResolution? + + init( + name: String, + table: String?, + deleteAction: Database.ForeignKeyAction?, + updateAction: Database.ForeignKeyAction?, + isIndexed: Bool, + isDeferred: Bool) + { + self.name = name + self.table = table + self.deleteAction = deleteAction + self.updateAction = updateAction + self.indexing = isIndexed ? .index : nil + self.isDeferred = isDeferred + } + + /// Adds a not null constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // teamId INTEGER NOT NULL REFERENCES team(id) + /// // ) + /// try db.create(table: "player") { t in + /// t.belongsTo("team").notNull() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. + /// - returns: `self` so that you can further refine the definition of + /// the association. + @discardableResult + public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { + notNullConflictResolution = conflictResolution ?? .abort + return self + } + + /// Adds a unique constraint. + /// + /// For example: + /// + /// ```swift + /// // CREATE TABLE player( + /// // teamId INTEGER UNIQUE REFERENCES team(id) + /// // ) + /// try db.create(table: "player") { t in + /// t.belongsTo("team").unique() + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - returns: `self` so that you can further refine the definition of + /// the association. + @discardableResult + public func unique() -> Self { + indexing = .unique + return self + } + + func primaryKey(_ db: Database) throws -> SQLPrimaryKeyDescriptor { + if let table { + return try SQLPrimaryKeyDescriptor.find(db, table: table) + } + + if try db.tableExists(name) { + return try SQLPrimaryKeyDescriptor.find(db, table: name) + } + + let pluralizedName = name.pluralized + if try db.tableExists(pluralizedName) { + return try SQLPrimaryKeyDescriptor.find(db, table: pluralizedName) + } + + throw DatabaseError.noSuchTable(name) + } +} diff --git a/GRDB/QueryInterface/Schema/IndexDefinition.swift b/GRDB/QueryInterface/Schema/IndexDefinition.swift new file mode 100644 index 000000000..5ac47c766 --- /dev/null +++ b/GRDB/QueryInterface/Schema/IndexDefinition.swift @@ -0,0 +1,26 @@ +struct IndexDefinition { + let name: String + let table: String + let columns: [String] + let options: IndexOptions + let condition: SQLExpression? +} + +/// Index creation options +public struct IndexOptions: OptionSet { + public let rawValue: Int + + 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) +} + +extension Database { + static func defaultIndexName(on table: String, columns: [String]) -> String { + "index_\(table)_on_\(columns.joined(separator: "_"))" + } +} diff --git a/GRDB/QueryInterface/Schema/TableAlteration.swift b/GRDB/QueryInterface/Schema/TableAlteration.swift new file mode 100644 index 000000000..a22b41991 --- /dev/null +++ b/GRDB/QueryInterface/Schema/TableAlteration.swift @@ -0,0 +1,163 @@ +/// A `TableDefinition` lets you modify the components of a database table. +/// +/// You don't create instances of this class. Instead, you use the `Database` +/// ``Database/alter(table:body:)`` method: +/// +/// ```swift +/// try db.alter(table: "player") { t in // t is TableAlteration +/// t.add(column: "bonus", .integer) +/// } +/// ``` +/// +/// Related SQLite documentation: +public final class TableAlteration { + let name: String + + enum TableAlterationKind { + case add(ColumnDefinition) + case addColumnLiteral(SQL) + case rename(old: String, new: String) + case drop(String) + } + + var alterations: [TableAlterationKind] = [] + + init(name: String) { + self.name = name + } + + /// Appends a column. + /// + /// For example: + /// + /// ```swift + /// // ALTER TABLE player ADD COLUMN bonus integer + /// try db.alter(table: "player") { t in + /// t.add(column: "bonus", .integer) + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter name: the column name. + /// - parameter type: the column type. + /// - returns: An ColumnDefinition that allows you to refine the + /// column definition. + @discardableResult + public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { + let column = ColumnDefinition(name: name, type: type) + alterations.append(.add(column)) + return column + } + + /// Appends a column. + /// + /// For example: + /// + /// ```swift + /// // ALTER TABLE player ADD COLUMN bonus integer + /// try db.alter(table: "player") { t in + /// t.addColumn(sql: "bonus integer") + /// } + /// ``` + public func addColumn(sql: String) { + alterations.append(.addColumnLiteral(SQL(sql: sql))) + } + + /// Appends a column. + /// + /// ``SQL`` literals allow you to safely embed raw values in your SQL, + /// without any risk of syntax errors or SQL injection: + /// + /// ```swift + /// // ALTER TABLE player ADD COLUMN name TEXT DEFAULT 'Anonymous' + /// try db.alter(table: "player") { t in + /// t.addColumn(literal: "name TEXT DEFAULT \(defaultName)") + /// } + /// ``` + public func addColumn(literal: SQL) { + alterations.append(.addColumnLiteral(literal)) + } + +#if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Renames a column. + /// + /// For example: + /// + /// ```swift + /// try db.alter(table: "player") { t in + /// t.rename(column: "url", to: "homeURL") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter name: the old name of the column. + /// - parameter newName: the new name of the column. + public func rename(column name: String, to newName: String) { + _rename(column: name, to: newName) + } + + /// Drops a column. + /// + /// For example: + /// + /// ```swift + /// try db.alter(table: "player") { t in + /// t.drop(column: "age") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameter name: the name of the column to drop. + public func drop(column name: String) { + _drop(column: name) + } +#else + /// Renames a column. + /// + /// For example: + /// + /// ```swift + /// try db.alter(table: "player") { t in + /// t.rename(column: "url", to: "homeURL") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - parameter name: the old name of the column. + /// - parameter newName: the new name of the column. + @available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+ + public func rename(column name: String, to newName: String) { + _rename(column: name, to: newName) + } + + /// Drops a column. + /// + /// For example: + /// + /// ```swift + /// try db.alter(table: "player") { t in + /// t.drop(column: "age") + /// } + /// ``` + /// + /// Related SQLite documentation: + /// + /// - Parameter name: the name of the column to drop. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func drop(column name: String) { + _drop(column: name) + } +#endif + + private func _rename(column name: String, to newName: String) { + alterations.append(.rename(old: name, new: newName)) + } + + private func _drop(column name: String) { + alterations.append(.drop(name)) + } +} diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 66a18645c..40958d1c4 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -1,643 +1,3 @@ -extension Database { - - // MARK: - Database Schema - - /// Creates a database table. - /// - /// For example: - /// - /// ```swift - /// 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() - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - - /// - - /// - /// - warning: This is a legacy interface that is preserved for backwards - /// compatibility. Use of this interface is not recommended: 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. - /// - /// ### Reference documentation - /// - /// SQLite has many reference documents about table creation. They are a - /// great learning material: - /// - /// - [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) - /// - [Datatypes In SQLite](https://www.sqlite.org/datatype3.html) - /// - [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) - /// - [The ON CONFLICT Clause](https://www.sqlite.org/lang_conflict.html) - /// - [Rowid Tables](https://www.sqlite.org/rowidtable.html) - /// - [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) - /// - [STRICT Tables](https://www.sqlite.org/stricttables.html) - /// - /// ### Usage - /// - /// ```swift - /// // CREATE TABLE place ( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // title TEXT, - /// // isFavorite BOOLEAN NOT NULL DEFAULT 0, - /// // latitude DOUBLE NOT NULL, - /// // longitude DOUBLE NOT NULL - /// // ) - /// try db.create(table: "place") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("title", .text) - /// t.column("isFavorite", .boolean).notNull().default(false) - /// t.column("longitude", .double).notNull() - /// t.column("latitude", .double).notNull() - /// } - /// ``` - /// - /// ### Configure table creation - /// - /// Use the `options` parameter to configure table creation - /// (see ``TableOptions``): - /// - /// ```swift - /// // CREATE TABLE player ( ... ) - /// try db.create(table: "player") { t in ... } - /// - /// // CREATE TEMPORARY TABLE player IF NOT EXISTS ( - /// try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... } - /// ``` - /// - /// ### Add columns - /// - /// Add columns with their name and eventual type (`text`, `integer`, - /// `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime` - /// and `any`) - see ``Database/ColumnType``: - /// - /// ```swift - /// // CREATE TABLE example ( - /// // a, - /// // name TEXT, - /// // creationDate DATETIME, - /// try db.create(table: "example") { t in - /// t.column("a") - /// t.column("name", .text) - /// t.column("creationDate", .datetime) - /// ``` - /// - /// The `column()` method returns a ``ColumnDefinition`` that you can - /// further configure: - /// - /// ### Not null constraints, default values - /// - /// ```swift - /// // email TEXT NOT NULL, - /// t.column("email", .text).notNull() - /// - /// // name TEXT DEFAULT 'O''Reilly', - /// t.column("name", .text).defaults(to: "O'Reilly") - /// - /// // flag BOOLEAN NOT NULL DEFAULT 0, - /// t.column("flag", .boolean).notNull().defaults(to: false) - /// - /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP, - /// t.column("creationDate", .datetime).defaults(sql: "CURRENT_TIMESTAMP") - /// ``` - /// - /// ### Primary, unique, and foreign keys - /// - /// Use an individual column as **primary**, **unique**, or **foreign key**. - /// When defining a foreign key, the referenced column is the primary key of - /// the referenced table (unless you specify otherwise): - /// - /// ```swift - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// t.autoIncrementedPrimaryKey("id") - /// - /// // uuid TEXT NOT NULL PRIMARY KEY, - /// t.primaryKey("uuid", .text) - /// - /// // email TEXT UNIQUE, - /// t.column("email", .text) - /// .unique() - /// - /// // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, - /// t.column("countryCode", .text) - /// .references("country", onDelete: .cascade) - /// ``` - /// - /// Primary, unique and foreign keys can also be added on several columns: - /// - /// ```swift - /// // a INTEGER NOT NULL, - /// // b TEXT NOT NULL, - /// // PRIMARY KEY (a, b) - /// t.primaryKey { - /// t.column("a", .integer) - /// t.column("b", .text) - /// } - /// - /// // a INTEGER NOT NULL, - /// // b TEXT NOT NULL, - /// // PRIMARY KEY (a, b) - /// t.column("a", .integer).notNull() - /// t.column("b", .text).notNull() - /// t.primaryKey(["a", "b"]) - /// - /// // a INTEGER, - /// // b TEXT, - /// // UNIQUE (a, b) ON CONFLICT REPLACE - /// t.column("a", .integer) - /// t.column("b", .text) - /// t.uniqueKey(["a", "b"], onConflict: .replace) - /// - /// // a INTEGER, - /// // b TEXT, - /// // FOREIGN KEY (a, b) REFERENCES parents(c, d) - /// t.column("a", .integer) - /// t.column("b", .text) - /// t.foreignKey(["a", "b"], references: "parents") - /// ``` - /// - /// > Tip: when you need an integer primary key that automatically generates - /// unique values, it is recommended that you use the - /// ``TableDefinition/autoIncrementedPrimaryKey(_:onConflict:)`` method: - /// > - /// > ```swift - /// > try db.create(table: "example") { t in - /// > t.autoIncrementedPrimaryKey("id") - /// > ... - /// > } - /// > ``` - /// > - /// > The reason for this recommendation is that auto-incremented primary - /// > keys forbid the reuse of ids. This prevents your app or - /// > to think that a row was updated, when it was - /// > actually deleted and replaced. Depending on your application needs, - /// > this may be acceptable. But usually it is not. - /// - /// ### Indexed columns - /// - /// ```swift - /// t.column("score", .integer).indexed() - /// ``` - /// - /// For extra index options, see ``create(indexOn:columns:options:condition:)``. - /// - /// ### Generated columns - /// - /// See [Generated columns](https://sqlite.org/gencol.html) for - /// more information: - /// - /// ```swift - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) - /// ``` - /// - /// ### Integrity checks - /// - /// SQLite will only let conforming rows in: - /// - /// ```swift - /// // name TEXT CHECK (LENGTH(name) > 0) - /// t.column("name", .text).check { length($0) > 0 } - /// - /// // score INTEGER CHECK (score > 0) - /// t.column("score", .integer).check(sql: "score > 0") - /// - /// // CHECK (a + b < 10), - /// t.check(Column("a") + Column("b") < 10) - /// - /// // CHECK (a + b < 10) - /// t.check(sql: "a + b < 10") - /// ``` - /// - /// ### Raw SQL columns and constraints - /// - /// Columns and constraints can be defined with raw sql: - /// - /// ```swift - /// t.column(sql: "name TEXT") - /// t.constraint(sql: "CHECK (a + b < 10)") - /// ``` - /// - /// ``SQL`` literals allow you to safely embed raw values in your SQL, - /// without any risk of syntax errors or SQL injection: - /// - /// ```swift - /// let defaultName = "O'Reilly" - /// t.column(literal: "name TEXT DEFAULT \(defaultName)") - /// - /// let forbiddenName = "admin" - /// t.constraint(literal: "CHECK (name <> \(forbiddenName))") - /// ``` - /// - /// - parameters: - /// - name: The table name. - /// - 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, - options: TableOptions = [], - body: (TableDefinition) throws -> Void) - throws - { - let definition = TableDefinition( - name: name, - options: options) - try body(definition) - let sql = try definition.sql(self) - try execute(sql: sql) - } - - /// Renames a database table. - /// - /// Related SQLite documentation: - /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func rename(table name: String, to newName: String) throws { - try execute(sql: "ALTER TABLE \(name.quotedDatabaseIdentifier) RENAME TO \(newName.quotedDatabaseIdentifier)") - } - - /// Modifies a database table. - /// - /// For example: - /// - /// ```swift - /// try db.alter(table: "player") { t in - /// t.add(column: "url", .text) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - name: The table name. - /// - body: A closure that defines table alterations. - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func alter(table name: String, body: (TableAlteration) -> Void) throws { - let alteration = TableAlteration(name: name) - body(alteration) - let sql = try alteration.sql(self) - try execute(sql: sql) - } - - /// Deletes a database table. - /// - /// Related SQLite documentation: - /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func drop(table name: String) throws { - try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)") - } - - /// Creates a database view. - /// - /// You can create a view with an ``SQLRequest``: - /// - /// ```swift - /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 - /// try db.create(view: "hero", as: SQLRequest(literal: """ - /// SELECT * FROM player WHERE isHero == 1 - /// """) - /// ``` - /// - /// You can also create a view with a ``QueryInterfaceRequest``: - /// - /// ```swift - /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 - /// try db.create( - /// view: "hero", - /// as: Player.filter(Column("isHero") == true)) - /// ``` - /// - /// When creating views in , it is not recommended to - /// use record types defined in the application. Instead of the `Player` - /// record type, prefer `Table("player")`: - /// - /// ```swift - /// // RECOMMENDED IN MIGRATIONS - /// try db.create( - /// view: "hero", - /// as: Table("player").filter(Column("isHero") == true)) - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - view: The view name. - /// - options: View creation options. - /// - columns: The columns of the view. If nil, the columns are the - /// columns of the request. - /// - request: The request that feeds the view. - public func create( - view name: String, - options: ViewOptions = [], - columns: [String]? = nil, - as request: SQLSubqueryable) - throws { - var literal: SQL = "CREATE " - - if options.contains(.temporary) { - literal += "TEMPORARY " - } - - literal += "VIEW " - - if options.contains(.ifNotExists) { - literal += "IF NOT EXISTS " - } - - literal += "\(identifier: name) " - - if let columns { - literal += "(" - literal += columns.map { "\(identifier: $0)" }.joined(separator: ", ") - literal += ") " - } - - literal += "AS \(request)" - - // CREATE VIEW does not support arguments, so make sure we use - // literal values. - let context = SQLGenerationContext(self, argumentsSink: .literalValues) - let sql = try literal.sql(context) - try execute(sql: sql) - } - - /// Creates a database view. - /// - /// For example: - /// - /// ```swift - /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 - /// try db.create(view: "hero", asLiteral: """ - /// SELECT * FROM player WHERE isHero == 1 - /// """) - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - view: The view name. - /// - options: View creation options. - /// - columns: The columns of the view. If nil, the columns are the - /// columns of the request. - /// - sqlLiteral: An `SQL` literal. - public func create( - view name: String, - options: ViewOptions = [], - columns: [String]? = nil, - asLiteral sqlLiteral: SQL) - throws { - try create(view: name, options: options, columns: columns, as: SQLRequest(literal: sqlLiteral)) - } - - /// Deletes a database view. - /// - /// Related SQLite documentation: - /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func drop(view name: String) throws { - try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)") - } - - /// Creates an index. - /// - /// For example: - /// - /// ```swift - /// // CREATE INDEX index_player_on_email ON player(email) - /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"]) - /// ``` - /// - /// SQLite can also index expressions () - /// and use specific collations. To create such an index, use a raw SQL - /// query: - /// - /// ```swift - /// try db.execute(sql: "CREATE INDEX ...") - /// ``` - /// - /// Related SQLite documentation: - /// - /// - warning: This is a legacy interface that is preserved for backwards - /// compatibility. Use of this interface is not recommended: prefer - /// ``create(indexOn: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 ). - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - @_disfavoredOverload - public func create( - index name: String, - on table: String, - columns: [String], - unique: Bool = false, - ifNotExists: Bool = false, - condition: (any 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. - /// - /// For example: - /// - /// ```swift - /// // CREATE INDEX index_player_on_email ON player(email) - /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"]) - /// ``` - /// - /// To create a unique index, specify the `.unique` option: - /// - /// ```swift - /// // CREATE UNIQUE INDEX index_player_on_email ON player(email) - /// try db.create(index: "index_player_on_email", on: "player", columns: ["email"], options: .unique) - /// ``` - /// - /// SQLite can also index expressions () - /// and use specific collations. To create such an index, use a raw SQL - /// query: - /// - /// ```swift - /// try db.execute(sql: "CREATE INDEX ...") - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - name: The index name. - /// - table: The name of the indexed table. - /// - columns: The indexed columns. - /// - options: Index creation options. - /// - condition: If not nil, creates a partial index - /// (see ). - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func create( - index name: String, - on table: String, - columns: [String], - options: IndexOptions = [], - condition: (any SQLExpressible)? = nil) - throws - { - let definition = IndexDefinition( - name: name, - table: table, - columns: columns, - options: options, - condition: condition?.sqlExpression) - let sql = try definition.sql(self) - try execute(sql: sql) - } - - /// Creates an index on the specified table and columns. - /// - /// The created index is named after the table and the column name(s): - /// - /// ```swift - /// // CREATE INDEX index_player_on_email ON player(email) - /// try db.create(indexOn: "player", columns: ["email"]) - /// ``` - /// - /// To create a unique index, specify the `.unique` option: - /// - /// ```swift - /// // CREATE UNIQUE INDEX index_player_on_email ON player(email) - /// try db.create(indexOn: "player", columns: ["email"], options: .unique) - /// ``` - /// - /// In order to specify the index name, use - /// ``create(index:on:columns:options:condition:)`` instead. - /// - /// SQLite can also index expressions () - /// and use specific collations. To create such an index, use a raw SQL - /// query: - /// - /// ```swift - /// try db.execute(sql: "CREATE INDEX ...") - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - table: The name of the indexed table. - /// - columns: The indexed columns. - /// - options: Index creation options. - /// - condition: If not nil, creates a partial index - /// (see ). - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func create( - indexOn table: String, - columns: [String], - options: IndexOptions = [], - condition: (any SQLExpressible)? = nil) - throws - { - try create( - index: defaultIndexName(on: table, columns: columns), - on: table, - columns: columns, - options: options, - condition: condition) - } - - private func defaultIndexName(on table: String, columns: [String]) -> String { - "index_\(table)_on_\(columns.joined(separator: "_"))" - } - - /// Deletes a database index. - /// - /// Related SQLite documentation: - /// - /// - parameter name: The index name. - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func drop(index name: String) throws { - try execute(sql: "DROP INDEX \(name.quotedDatabaseIdentifier)") - } - - /// Deletes the database index on the specified table and columns - /// if exactly one such index exists. - /// - /// - parameters: - /// - table: The name of the indexed table. - /// - columns: The indexed columns. - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func drop(indexOn table: String, columns: [String]) throws { - let lowercasedColumns = columns.map { $0.lowercased() } - let indexes = try indexes(on: table).filter { index in - index.columns.map({ $0.lowercased() }) == lowercasedColumns - } - if let index = indexes.first, indexes.count == 1 { - try drop(index: index.name) - } - } - - /// Deletes and recreates from scratch all indices that use this collation. - /// - /// This method is useful when the definition of a collation sequence - /// has changed. - /// - /// Related SQLite documentation: - /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func reindex(collation: Database.CollationName) throws { - try execute(sql: "REINDEX \(collation.rawValue)") - } - - /// Deletes and recreates from scratch all indices that use this collation. - /// - /// This method is useful when the definition of a collation sequence - /// has changed. - /// - /// Related SQLite documentation: - /// - /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public func reindex(collation: DatabaseCollation) throws { - try reindex(collation: Database.CollationName(rawValue: collation.name)) - } -} - /// Table creation options. public struct TableOptions: OptionSet { public let rawValue: Int @@ -665,19 +25,6 @@ public struct TableOptions: OptionSet { #endif } -/// View creation options -public struct ViewOptions: OptionSet { - public let rawValue: Int - - public init(rawValue: Int) { self.rawValue = rawValue } - - /// Only creates the view if it does not already exist. - public static let ifNotExists = ViewOptions(rawValue: 1 << 0) - - /// Creates a temporary view. - public static let temporary = ViewOptions(rawValue: 1 << 1) -} - /// A `TableDefinition` lets you define the components of a database table. /// /// See the documentation of the `Database` @@ -708,7 +55,9 @@ public struct ViewOptions: OptionSet { /// /// ### Define a Foreign Key /// +/// - ``belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` /// - ``foreignKey(_:references:columns:onDelete:onUpdate:deferred:)`` +/// - ``ForeignKeyDefinition`` /// /// ### Define a Unique Key /// @@ -723,50 +72,42 @@ public struct ViewOptions: OptionSet { /// - ``constraint(sql:)`` public final class TableDefinition { struct KeyConstraint { - var columns: [String] + enum Component { + case columnName(String) + case columnDefinition(ColumnDefinition) + case foreignKeyDefinition(ForeignKeyDefinition) + } + var components: [Component] var conflictResolution: Database.ConflictResolution? - } - - private struct ForeignKeyConstraint { - var columns: [String] - var table: String - var destinationColumns: [String]? - var deleteAction: Database.ForeignKeyAction? - var updateAction: Database.ForeignKeyAction? - var deferred: Bool - } - - private enum ColumnItem { - case definition(ColumnDefinition) - case literal(SQL) - var columnDefinition: ColumnDefinition? { - switch self { - case let .definition(def): return def - case .literal: return nil - } + init(components: [Component], conflictResolution: Database.ConflictResolution?) { + self.components = components + self.conflictResolution = conflictResolution } - func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String { - switch self { - case let .definition(def): - return try def.sql(db, tableName: tableName, primaryKeyColumns: primaryKeyColumns) - case let .literal(sqlLiteral): - let context = SQLGenerationContext(db, argumentsSink: .literalValues) - return try sqlLiteral.sql(context) + init(columns: [String], conflictResolution: Database.ConflictResolution?) { + let components = columns.map { name in + Component.columnName(name) } + self.init(components: components, conflictResolution: conflictResolution) } } - private let name: String - private let options: TableOptions - private var columns: [ColumnItem] = [] - private var inPrimaryKeyBody = false - private var primaryKeyConstraint: KeyConstraint? - private var uniqueKeyConstraints: [KeyConstraint] = [] - private var foreignKeyConstraints: [ForeignKeyConstraint] = [] - private var checkConstraints: [SQLExpression] = [] - private var literalConstraints: [SQL] = [] + enum ColumnComponent { + case columnDefinition(ColumnDefinition) + case columnLiteral(SQL) + case foreignKeyDefinition(ForeignKeyDefinition) + case foreignKeyConstraint(SQLForeignKeyConstraint) + } + + let name: String + let options: TableOptions + var columnComponents: [ColumnComponent] = [] + var inPrimaryKeyBody = false + var primaryKeyConstraint: KeyConstraint? + var uniqueKeyConstraints: [KeyConstraint] = [] + var checkConstraints: [SQLExpression] = [] + var literalConstraints: [SQL] = [] init(name: String, options: TableOptions) { self.name = name @@ -872,7 +213,7 @@ public final class TableDefinition { // Programmer error fatalError("can't define several primary keys") } - primaryKeyConstraint = KeyConstraint(columns: [], conflictResolution: conflictResolution) + primaryKeyConstraint = KeyConstraint(components: [], conflictResolution: conflictResolution) let oldValue = inPrimaryKeyBody inPrimaryKeyBody = true @@ -902,13 +243,13 @@ public final class TableDefinition { @discardableResult public func column(_ name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { let column = ColumnDefinition(name: name, type: type) - columns.append(.definition(column)) + columnComponents.append(.columnDefinition(column)) if inPrimaryKeyBody { // Add a not null constraint in order to fix an SQLite bug: // column.notNull() - primaryKeyConstraint!.columns.append(name) + primaryKeyConstraint!.components.append(.columnDefinition(column)) } return column @@ -927,8 +268,7 @@ public final class TableDefinition { /// } /// ``` public func column(sql: String) { - GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL") - columns.append(.literal(SQL(sql: sql))) + column(literal: SQL(sql: sql)) } /// Appends a table column. @@ -947,7 +287,7 @@ public final class TableDefinition { /// ``` public func column(literal: SQL) { GRDBPrecondition(!inPrimaryKeyBody, "Primary key columns can not be defined with raw SQL") - columns.append(.literal(literal)) + columnComponents.append(.columnLiteral(literal)) } /// Adds a primary key constraint. @@ -1062,7 +402,8 @@ public final class TableDefinition { /// are used. /// - deleteAction: Optional action when the referenced row is deleted. /// - updateAction: Optional action when the referenced row is updated. - /// - deferred: If true, defines a deferred foreign key constraint. + /// - isDeferred: A boolean value indicating whether the foreign key + /// constraint is deferred. /// See . public func foreignKey( _ columns: [String], @@ -1070,15 +411,195 @@ public final class TableDefinition { columns destinationColumns: [String]? = nil, onDelete deleteAction: Database.ForeignKeyAction? = nil, onUpdate updateAction: Database.ForeignKeyAction? = nil, - deferred: Bool = false) + deferred isDeferred: Bool = false) { - foreignKeyConstraints.append(ForeignKeyConstraint( - columns: columns, - table: table, - destinationColumns: destinationColumns, - deleteAction: deleteAction, - updateAction: updateAction, - deferred: deferred)) + let foreignKeyConstraint = SQLForeignKeyConstraint( + columns: columns, + destinationTable: table, + destinationColumns: destinationColumns, + deleteAction: deleteAction, + updateAction: updateAction, + isDeferred: isDeferred) + columnComponents.append(.foreignKeyConstraint(foreignKeyConstraint)) + } + + /// Declares an association to another table. + /// + /// `belongsTo` appends as many columns as there are columns in the + /// primary key of the referenced table, and declares a foreign key that + /// guarantees schema integrity. All primary keys are supported, + /// including composite primary keys that span several columns, and the + /// hidden `rowid` column. + /// + /// Added columns are prefixed with `name`, and end with the name of the + /// matching column in the primary key of the referenced table. In the + /// following example, `belongsTo("team")` adds a `teamId` column, and + /// `belongsTo("country")` adds a `countryCode` column: + /// + /// ```swift + /// try db.create(table: "team") { t in + /// t.autoIncrementedPrimaryKey("id") + /// } + /// try db.create(table: "country") { t in + /// t.primaryKey("code", .text) + /// } + /// + /// // CREATE TABLE player ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // teamId INTEGER REFERENCES team(id), + /// // countryCode TEXT NOT NULL REFERENCES country(code), + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.belongsTo("team") + /// t.belongsTo("country").notNull() + /// } + /// ``` + /// + /// When in doubt, you can check the names of the created columns: + /// + /// ```swift + /// // Prints ["id", "teamId", "countryCode"] + /// try print(db.columns(in: "player").map(\.name)) + /// ``` + /// + /// Singular names can refer to database tables whose name is plural: + /// + /// ```swift + /// try db.create(table: "teams") { t in + /// t.autoIncrementedPrimaryKey("id") + /// } + /// try db.create(table: "countries") { t in + /// t.primaryKey("code", .text) + /// } + /// + /// // CREATE TABLE players ( + /// // teamId INTEGER REFERENCES teams(id), + /// // countryCode TEXT REFERENCES countries(code), + /// // ) + /// try db.create(table: "players") { t in + /// t.belongsTo("team") + /// t.belongsTo("country") + /// } + /// ``` + /// + /// When the added columns should have a custom prefix, specify an + /// explicit table name: + /// + /// ```swift + /// // CREATE TABLE player ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // captainId INTEGER REFERENCES player(id), + /// // ) + /// try db.create(table: "player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.belongsTo("captain", inTable: "player") + /// } + /// + /// // CREATE TABLE book ( + /// // id INTEGER PRIMARY KEY AUTOINCREMENT, + /// // authorId INTEGER REFERENCES person(id), + /// // translatorId INTEGER REFERENCES person(id), + /// // title TEXT + /// // ) + /// try db.create(table: "book") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.belongsTo("author", inTable: "person") + /// t.belongsTo("translator", inTable: "person") + /// t.column("title", .text) + /// } + /// ``` + /// + /// Specify foreign key actions: + /// + /// ```swift + /// try db.create(table: "player") { t in + /// t.belongsTo("team", onDelete: .cascade) + /// t.belongsTo("captain", inTable: "player", onDelete: .setNull) + /// } + /// ``` + /// + /// The added columns are indexed by default. You can disable this + /// automatic index with the `indexed: false` option. You can also make + /// this index unique with ``ForeignKeyDefinition/unique()``: + /// + /// ```swift + /// try db.create(table: "player") { t in + /// // teamId is not indexed + /// t.belongsTo("team", indexed: false) + /// + /// // One single player per country + /// t.belongsTo("country").unique() + /// } + /// ``` + /// + /// For more precision in the definition of foreign keys, use instead + /// ``ColumnDefinition/references(_:column:onDelete:onUpdate:deferred:)`` + /// or ``TableDefinition/foreignKey(_:references:columns:onDelete:onUpdate:deferred:)``. + /// For example: + /// + /// ```swift + /// try db.create(table: "player") { t in + /// // This convenience method... + /// t.belongsTo("team") + /// + /// // ... is equivalent to: + /// t.column("teamId", .integer) + /// .references("team") + /// .indexed() + /// + /// // ... and is equivalent to: + /// t.column("teamId", .integer).indexed() + /// t.foreignKey(["teamId"], references: "team") + /// } + /// ``` + /// + /// See [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) + /// for more information about foreign keys and associations. + /// + /// - parameters: + /// - name: The name of the foreign key, used as a prefix for the + /// added columns. + /// - table: The referenced table. If nil, the referenced table is + /// designated by the `name` parameter. + /// - deleteAction: Optional action when the referenced row + /// is deleted. + /// - updateAction: Optional action when the referenced row + /// is updated. + /// - isDeferred: A boolean value indicating whether the foreign key + /// constraint is deferred. + /// See . + /// - indexed: A boolean value indicating whether the foreign key is + /// indexed. It is true by default. + /// - returns: A ``ForeignKeyDefinition`` that allows you to refine the + /// foreign key. + @discardableResult + public func belongsTo( + _ name: String, + inTable table: String? = nil, + onDelete deleteAction: Database.ForeignKeyAction? = nil, + onUpdate updateAction: Database.ForeignKeyAction? = nil, + deferred isDeferred: Bool = false, + indexed: Bool = true) + -> ForeignKeyDefinition + { + let foreignKey = ForeignKeyDefinition( + name: name, + table: table, + deleteAction: deleteAction, + updateAction: updateAction, + isIndexed: indexed && !inPrimaryKeyBody, + isDeferred: isDeferred) + columnComponents.append(.foreignKeyDefinition(foreignKey)) + + if inPrimaryKeyBody { + // Add a not null constraint in order to fix an SQLite bug: + // + foreignKey.notNull() + primaryKeyConstraint!.components.append(.foreignKeyDefinition(foreignKey)) + } + + return foreignKey } /// Adds a check constraint. @@ -1157,7 +678,7 @@ public final class TableDefinition { public func check(_ condition: some SQLSpecificExpressible) { checkConstraints.append(condition.sqlExpression) } - + /// Adds a check constraint. /// /// For example: @@ -1231,1083 +752,4 @@ public final class TableDefinition { public func constraint(literal: SQL) { literalConstraints.append(literal) } - - fileprivate func sql(_ db: Database) throws -> String { - var statements: [String] = [] - - do { - var chunks: [String] = [] - chunks.append("CREATE") - if options.contains(.temporary) { - chunks.append("TEMPORARY") - } - chunks.append("TABLE") - if options.contains(.ifNotExists) { - chunks.append("IF NOT EXISTS") - } - chunks.append(name.quotedDatabaseIdentifier) - - let primaryKeyColumns: [String] - if let primaryKeyConstraint { - primaryKeyColumns = primaryKeyConstraint.columns - } else if let column = columns.lazy.compactMap(\.columnDefinition).first(where: { $0.primaryKey != nil }) { - primaryKeyColumns = [column.name] - } else { - // WITHOUT ROWID optimization requires a primary key. If the - // user sets withoutRowID, but does not define a primary key, - // this is undefined behavior. - // - // We thus can use the rowId column even when the withoutRowID - // flag is set ;-) - primaryKeyColumns = [Column.rowID.name] - } - - do { - var items: [String] = [] - try items.append(contentsOf: columns.map { - try $0.sql(db, tableName: name, primaryKeyColumns: primaryKeyColumns) - }) - - if let constraint = primaryKeyConstraint { - var chunks: [String] = [] - chunks.append("PRIMARY KEY") - chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") - if let conflictResolution = constraint.conflictResolution { - chunks.append("ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - items.append(chunks.joined(separator: " ")) - } - - for constraint in uniqueKeyConstraints { - var chunks: [String] = [] - chunks.append("UNIQUE") - chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") - if let conflictResolution = constraint.conflictResolution { - chunks.append("ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - items.append(chunks.joined(separator: " ")) - } - - for constraint in foreignKeyConstraints { - var chunks: [String] = [] - chunks.append("FOREIGN KEY") - chunks.append("(\(constraint.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")))") - chunks.append("REFERENCES") - if let destinationColumns = constraint.destinationColumns { - chunks.append(""" - \(constraint.table.quotedDatabaseIdentifier)(\ - \(destinationColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - } else if constraint.table == name { - chunks.append(""" - \(constraint.table.quotedDatabaseIdentifier)(\ - \(primaryKeyColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - } else { - let primaryKey = try db.primaryKey(constraint.table) - chunks.append(""" - \(constraint.table.quotedDatabaseIdentifier)(\ - \(primaryKey.columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - } - if let deleteAction = constraint.deleteAction { - chunks.append("ON DELETE") - chunks.append(deleteAction.rawValue) - } - if let updateAction = constraint.updateAction { - chunks.append("ON UPDATE") - chunks.append(updateAction.rawValue) - } - if constraint.deferred { - chunks.append("DEFERRABLE INITIALLY DEFERRED") - } - items.append(chunks.joined(separator: " ")) - } - - for checkExpression in checkConstraints { - var chunks: [String] = [] - try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))") - items.append(chunks.joined(separator: " ")) - } - - for literal in literalConstraints { - let context = SQLGenerationContext(db, argumentsSink: .literalValues) - try items.append(literal.sql(context)) - } - - chunks.append("(\(items.joined(separator: ", ")))") - } - - var tableOptions: [String] = [] - -#if GRDBCUSTOMSQLITE || GRDBCIPHER - if options.contains(.strict) { - tableOptions.append("STRICT") - } -#else - if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+ - 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, options: indexOptions) } - .map { try $0.sql(db) } - statements.append(contentsOf: indexStatements) - return statements.joined(separator: "; ") - } -} - -/// A `TableDefinition` lets you modify the components of a database table. -/// -/// You don't create instances of this class. Instead, you use the `Database` -/// ``Database/alter(table:body:)`` method: -/// -/// ```swift -/// try db.alter(table: "player") { t in // t is TableAlteration -/// t.add(column: "bonus", .integer) -/// } -/// ``` -/// -/// Related SQLite documentation: -public final class TableAlteration { - private let name: String - - private enum TableAlterationKind { - case add(ColumnDefinition) - case addColumnLiteral(SQL) - case rename(old: String, new: String) - case drop(String) - } - - private var alterations: [TableAlterationKind] = [] - - init(name: String) { - self.name = name - } - - /// Appends a column. - /// - /// For example: - /// - /// ```swift - /// // ALTER TABLE player ADD COLUMN bonus integer - /// try db.alter(table: "player") { t in - /// t.add(column: "bonus", .integer) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter name: the column name. - /// - parameter type: the column type. - /// - returns: An ColumnDefinition that allows you to refine the - /// column definition. - @discardableResult - public func add(column name: String, _ type: Database.ColumnType? = nil) -> ColumnDefinition { - let column = ColumnDefinition(name: name, type: type) - alterations.append(.add(column)) - return column - } - - /// Appends a column. - /// - /// For example: - /// - /// ```swift - /// // ALTER TABLE player ADD COLUMN bonus integer - /// try db.alter(table: "player") { t in - /// t.addColumn(sql: "bonus integer") - /// } - /// ``` - public func addColumn(sql: String) { - alterations.append(.addColumnLiteral(SQL(sql: sql))) - } - - /// Appends a column. - /// - /// ``SQL`` literals allow you to safely embed raw values in your SQL, - /// without any risk of syntax errors or SQL injection: - /// - /// ```swift - /// // ALTER TABLE player ADD COLUMN name TEXT DEFAULT 'Anonymous' - /// try db.alter(table: "player") { t in - /// t.addColumn(literal: "name TEXT DEFAULT \(defaultName)") - /// } - /// ``` - public func addColumn(literal: SQL) { - alterations.append(.addColumnLiteral(literal)) - } - - #if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Renames a column. - /// - /// For example: - /// - /// ```swift - /// try db.alter(table: "player") { t in - /// t.rename(column: "url", to: "homeURL") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter name: the old name of the column. - /// - parameter newName: the new name of the column. - public func rename(column name: String, to newName: String) { - _rename(column: name, to: newName) - } - - /// Drops a column. - /// - /// For example: - /// - /// ```swift - /// try db.alter(table: "player") { t in - /// t.drop(column: "age") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - Parameter name: the name of the column to drop. - public func drop(column name: String) { - _drop(column: name) - } - #else - /// Renames a column. - /// - /// For example: - /// - /// ```swift - /// try db.alter(table: "player") { t in - /// t.rename(column: "url", to: "homeURL") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter name: the old name of the column. - /// - parameter newName: the new name of the column. - @available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+ - public func rename(column name: String, to newName: String) { - _rename(column: name, to: newName) - } - - /// Drops a column. - /// - /// For example: - /// - /// ```swift - /// try db.alter(table: "player") { t in - /// t.drop(column: "age") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - Parameter name: the name of the column to drop. - @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func drop(column name: String) { - _drop(column: name) - } - #endif - - private func _rename(column name: String, to newName: String) { - alterations.append(.rename(old: name, new: newName)) - } - - private func _drop(column name: String) { - alterations.append(.drop(name)) - } - - fileprivate func sql(_ db: Database) throws -> String { - var statements: [String] = [] - - for alteration in alterations { - switch alteration { - case let .add(column): - var chunks: [String] = [] - chunks.append("ALTER TABLE") - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("ADD COLUMN") - try chunks.append(column.sql(db, tableName: name, primaryKeyColumns: nil)) - let statement = chunks.joined(separator: " ") - statements.append(statement) - - if let indexDefinition = column.indexDefinition(in: name) { - try statements.append(indexDefinition.sql(db)) - } - - case let .addColumnLiteral(sqlLiteral): - var chunks: [String] = [] - chunks.append("ALTER TABLE") - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("ADD COLUMN") - let context = SQLGenerationContext(db, argumentsSink: .literalValues) - try chunks.append(sqlLiteral.sql(context)) - let statement = chunks.joined(separator: " ") - statements.append(statement) - - case let .rename(oldName, newName): - var chunks: [String] = [] - chunks.append("ALTER TABLE") - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("RENAME COLUMN") - chunks.append(oldName.quotedDatabaseIdentifier) - chunks.append("TO") - chunks.append(newName.quotedDatabaseIdentifier) - let statement = chunks.joined(separator: " ") - statements.append(statement) - - case let .drop(column): - var chunks: [String] = [] - chunks.append("ALTER TABLE") - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("DROP COLUMN") - chunks.append(column.quotedDatabaseIdentifier) - let statement = chunks.joined(separator: " ") - statements.append(statement) - } - } - - return statements.joined(separator: "; ") - } -} - -/// Describes a database column. -/// -/// You get instances of `ColumnDefinition` when you create or alter a database -/// tables. For example: -/// -/// ```swift -/// try db.create(table: "player") { t in -/// t.column("name", .text) // ColumnDefinition -/// } -/// -/// try db.alter(table: "player") { t in -/// t.add(column: "score", .integer) // ColumnDefinition -/// } -/// ``` -/// -/// See ``TableDefinition/column(_:_:)`` and ``TableAlteration/add(column:_:)``. -/// -/// Related SQLite documentation: -/// -/// - -/// - -/// -/// ## Topics -/// -/// ### Foreign Keys -/// -/// - ``references(_:column:onDelete:onUpdate:deferred:)`` -/// -/// ### Indexes -/// -/// - ``indexed()`` -/// - ``unique(onConflict:)`` -/// -/// ### Default value -/// -/// - ``defaults(to:)`` -/// - ``defaults(sql:)`` -/// -/// ### Collations -/// -/// - ``collate(_:)-4dljx`` -/// - ``collate(_:)-9ywza`` -/// -/// ### Generated Columns -/// -/// - ``generatedAs(_:_:)`` -/// - ``generatedAs(sql:_:)`` -/// - ``GeneratedColumnQualification`` -/// -/// ### Other Constraints -/// -/// - ``check(_:)`` -/// - ``check(sql:)`` -/// - ``notNull(onConflict:)`` -/// -/// ### Sunsetted Methods -/// -/// Those are legacy interfaces that are preserved for backwards compatibility. -/// Their use is not recommended. -/// -/// - ``primaryKey(onConflict:autoincrement:)`` -public final class ColumnDefinition { - enum Index { - case none - case index - case unique(Database.ConflictResolution) - } - - private struct ForeignKeyConstraint { - var table: String - var column: String? - var deleteAction: Database.ForeignKeyAction? - var updateAction: Database.ForeignKeyAction? - var deferred: Bool - } - - /// The kind of a generated column. - /// - /// Related SQLite documentation: - public enum GeneratedColumnQualification { - /// A `VIRTUAL` generated column. - case virtual - /// A `STORED` generated column. - case stored - } - - private struct GeneratedColumnConstraint { - var expression: SQLExpression - var qualification: GeneratedColumnQualification - } - - fileprivate let name: String - private let type: Database.ColumnType? - fileprivate var primaryKey: (conflictResolution: Database.ConflictResolution?, autoincrement: Bool)? - private var index: Index = .none - private var notNullConflictResolution: Database.ConflictResolution? - private var checkConstraints: [SQLExpression] = [] - private var foreignKeyConstraints: [ForeignKeyConstraint] = [] - private var defaultExpression: SQLExpression? - private var collationName: String? - private var generatedColumnConstraint: GeneratedColumnConstraint? - - init(name: String, type: Database.ColumnType?) { - self.name = name - self.type = type - } - - /// Adds a primary key constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id TEXT NOT NULL PRIMARY KEY - /// // ) - /// try db.create(table: "player") { t in - /// t.primaryKey("id", .text) - /// } - /// ``` - /// - /// - important: Make sure you add a not null constraint on your primary key - /// column, as in the above example, or SQLite will allow null values. - /// See - /// for more information. - /// - /// - warning: This is a legacy interface that is preserved for backwards - /// compatibility. Use of this interface is not recommended: prefer - /// ``TableDefinition/primaryKey(_:_:onConflict:)`` - /// instead. - /// - /// - parameters: - /// - conflictResolution: An optional ``Database/ConflictResolution``. - /// - autoincrement: If true, the primary key is autoincremented. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func primaryKey( - onConflict conflictResolution: Database.ConflictResolution? = nil, - autoincrement: Bool = false) - -> Self - { - primaryKey = (conflictResolution: conflictResolution, autoincrement: autoincrement) - return self - } - - /// Adds a not null constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // name TEXT NOT NULL - /// // ) - /// try db.create(table: "player") { t in - /// t.column("name", .text).notNull() - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { - notNullConflictResolution = conflictResolution ?? .abort - return self - } - - /// Adds a unique constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // email TEXT UNIQUE - /// // ) - /// try db.create(table: "player") { t in - /// t.column("email", .text).unique() - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter conflictResolution: An optional ``Database/ConflictResolution``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self { - index = .unique(conflictResolution ?? .abort) - return self - } - - /// Adds an index. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player(email TEXT); - /// // CREATE INDEX player_on_email ON player(email); - /// try db.create(table: "player") { t in - /// t.column("email", .text).indexed() - /// } - /// ``` - /// - /// The name of the created index is `
_on_`, where `table` - /// and `column` are the names of the table and the column. See the - /// example above. - /// - /// See also ``unique(onConflict:)``. - /// - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func indexed() -> Self { - if case .none = index { - self.index = .index - } - return self - } - - /// Adds a check constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // name TEXT CHECK (LENGTH(name) > 0) - /// // ) - /// try db.create(table: "player") { t in - /// t.column("name", .text).check { length($0) > 0 } - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter condition: A closure whose argument is a ``Column`` that - /// represents the defined column, and returns the expression to check. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func check(_ condition: (Column) -> any SQLExpressible) -> Self { - checkConstraints.append(condition(Column(name)).sqlExpression) - return self - } - - /// Adds a check constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // name TEXT CHECK (LENGTH(name) > 0) - /// // ) - /// try db.create(table: "player") { t in - /// t.column("name", .text).check(sql: "LENGTH(name) > 0") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter sql: An SQL snippet. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func check(sql: String) -> Self { - checkConstraints.append(SQL(sql: sql).sqlExpression) - return self - } - - /// Defines the default value. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // email TEXT DEFAULT 'Anonymous' - /// // ) - /// try db.create(table: "player") { t in - /// t.column("name", .text).defaults(to: "Anonymous") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter value: A ``DatabaseValueConvertible`` value. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func defaults(to value: some DatabaseValueConvertible) -> Self { - defaultExpression = value.sqlExpression - return self - } - - /// Defines the default value. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // creationDate DATETIME DEFAULT CURRENT_TIMESTAMP - /// // ) - /// try db.create(table: "player") { t in - /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter sql: An SQL snippet. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func defaults(sql: String) -> Self { - defaultExpression = SQL(sql: sql).sqlExpression - return self - } - - /// Defines the default collation. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // email TEXT COLLATE NOCASE - /// // ) - /// try db.create(table: "player") { t in - /// t.column("email", .text).collate(.nocase) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter collation: A ``Database/CollationName``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func collate(_ collation: Database.CollationName) -> Self { - collationName = collation.rawValue - return self - } - - /// Defines the default collation. - /// - /// For example: - /// - /// ```swift - /// try db.create(table: "player") { t in - /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameter collation: A ``DatabaseCollation``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func collate(_ collation: DatabaseCollation) -> Self { - collationName = collation.name - return self - } - -#if GRDBCUSTOMSQLITE || GRDBCIPHER - /// Defines the column as a generated column. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // score INTEGER NOT NULL, - /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL - /// // ) - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - sql: An SQL expression. - /// - qualification: The generated column's qualification, which - /// defaults to ``GeneratedColumnQualification/virtual``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func generatedAs( - sql: String, - _ qualification: GeneratedColumnQualification = .virtual) - -> Self - { - let expression = SQL(sql: sql).sqlExpression - generatedColumnConstraint = GeneratedColumnConstraint( - expression: expression, - qualification: qualification) - return self - } - - /// Defines the column as a generated column. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // score INTEGER NOT NULL, - /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL - /// // ) - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - expression: The generated expression. - /// - qualification: The generated column's qualification, which - /// defaults to ``GeneratedColumnQualification/virtual``. - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func generatedAs( - _ expression: some SQLExpressible, - _ qualification: GeneratedColumnQualification = .virtual) - -> Self - { - generatedColumnConstraint = GeneratedColumnConstraint( - expression: expression.sqlExpression, - qualification: qualification) - return self - } - #else - /// Defines the column as a generated column. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // score INTEGER NOT NULL, - /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL - /// // ) - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(sql: "score + bonus") - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - sql: An SQL expression. - /// - qualification: The generated column's qualification, which - /// defaults to ``GeneratedColumnQualification/virtual``. - /// - returns: `self` so that you can further refine the column definition. - @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) - @discardableResult - public func generatedAs( - sql: String, - _ qualification: GeneratedColumnQualification = .virtual) - -> Self - { - let expression = SQL(sql: sql).sqlExpression - generatedColumnConstraint = GeneratedColumnConstraint( - expression: expression, - qualification: qualification) - return self - } - - /// Defines the column as a generated column. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE player( - /// // id INTEGER PRIMARY KEY AUTOINCREMENT, - /// // score INTEGER NOT NULL, - /// // bonus INTEGER NOT NULL, - /// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL - /// // ) - /// try db.create(table: "player") { t in - /// t.autoIncrementedPrimaryKey("id") - /// t.column("score", .integer).notNull() - /// t.column("bonus", .integer).notNull() - /// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - expression: The generated expression. - /// - qualification: The generated column's qualification, which - /// defaults to ``GeneratedColumnQualification/virtual``. - /// - returns: `self` so that you can further refine the column definition. - @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually) - @discardableResult - public func generatedAs( - _ expression: some SQLExpressible, - _ qualification: GeneratedColumnQualification = .virtual) - -> Self - { - generatedColumnConstraint = GeneratedColumnConstraint( - expression: expression.sqlExpression, - qualification: qualification) - return self - } - #endif - - /// Adds a foreign key constraint. - /// - /// For example: - /// - /// ```swift - /// // CREATE TABLE book( - /// // authorId INTEGER REFERENCES author(id) ON DELETE CASCADE - /// // ) - /// try db.create(table: "book") { t in - /// t.column("authorId", .integer).references("author", onDelete: .cascade) - /// } - /// ``` - /// - /// Related SQLite documentation: - /// - /// - parameters: - /// - table: The referenced table. - /// - column: The referenced column in the referenced table. If not - /// specified, the column of the primary key of the referenced table - /// is used. - /// - deleteAction: Optional action when the referenced row is deleted. - /// - updateAction: Optional action when the referenced row is updated. - /// - deferred: If true, defines a deferred foreign key constraint. - /// See . - /// - returns: `self` so that you can further refine the column definition. - @discardableResult - public func references( - _ table: String, - column: String? = nil, - onDelete deleteAction: Database.ForeignKeyAction? = nil, - onUpdate updateAction: Database.ForeignKeyAction? = nil, - deferred: Bool = false) -> Self - { - foreignKeyConstraints.append(ForeignKeyConstraint( - table: table, - column: column, - deleteAction: deleteAction, - updateAction: updateAction, - deferred: deferred)) - return self - } - - fileprivate func sql(_ db: Database, tableName: String, primaryKeyColumns: [String]?) throws -> String { - var chunks: [String] = [] - chunks.append(name.quotedDatabaseIdentifier) - if let type { - chunks.append(type.rawValue) - } - - if let (conflictResolution, autoincrement) = primaryKey { - chunks.append("PRIMARY KEY") - if let conflictResolution { - chunks.append("ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - if autoincrement { - chunks.append("AUTOINCREMENT") - } - } - - switch notNullConflictResolution { - case .none: - break - case .abort: - chunks.append("NOT NULL") - case let conflictResolution?: - chunks.append("NOT NULL ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - - switch index { - case .none: - break - case .unique(let conflictResolution): - switch conflictResolution { - case .abort: - chunks.append("UNIQUE") - default: - chunks.append("UNIQUE ON CONFLICT") - chunks.append(conflictResolution.rawValue) - } - case .index: - break - } - - for checkConstraint in checkConstraints { - try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))") - } - - if let defaultExpression { - try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))") - } - - if let collationName { - chunks.append("COLLATE") - chunks.append(collationName) - } - - for constraint in foreignKeyConstraints { - chunks.append("REFERENCES") - if let column = constraint.column { - // explicit reference - chunks.append("\(constraint.table.quotedDatabaseIdentifier)(\(column.quotedDatabaseIdentifier))") - } else if constraint.table.lowercased() == tableName.lowercased() { - // implicit autoreference - let primaryKeyColumns = try primaryKeyColumns ?? db.primaryKey(constraint.table).columns - chunks.append(""" - \(constraint.table.quotedDatabaseIdentifier)(\ - \(primaryKeyColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - } else { - // implicit external reference - let primaryKeyColumns = try db.primaryKey(constraint.table).columns - chunks.append(""" - \(constraint.table.quotedDatabaseIdentifier)(\ - \(primaryKeyColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - } - if let deleteAction = constraint.deleteAction { - chunks.append("ON DELETE") - chunks.append(deleteAction.rawValue) - } - if let updateAction = constraint.updateAction { - chunks.append("ON UPDATE") - chunks.append(updateAction.rawValue) - } - if constraint.deferred { - chunks.append("DEFERRABLE INITIALLY DEFERRED") - } - } - - if let constraint = generatedColumnConstraint { - try chunks.append("GENERATED ALWAYS AS (\(constraint.expression.quotedSQL(db)))") - let qualificationLiteral: String - switch constraint.qualification { - case .stored: - qualificationLiteral = "STORED" - case .virtual: - qualificationLiteral = "VIRTUAL" - } - chunks.append(qualificationLiteral) - } - - return chunks.joined(separator: " ") - } - - fileprivate func indexDefinition(in table: String, options: IndexOptions = []) -> IndexDefinition? { - switch index { - case .none: return nil - case .unique: return nil - case .index: - return IndexDefinition( - name: "\(table)_on_\(name)", - table: table, - columns: [name], - options: options, - condition: nil) - } - } -} - -/// Index creation options -public struct IndexOptions: OptionSet { - public let rawValue: Int - - 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 options: IndexOptions - let condition: SQLExpression? - - func sql(_ db: Database) throws -> String { - var chunks: [String] = [] - chunks.append("CREATE") - if options.contains(.unique) { - chunks.append("UNIQUE") - } - chunks.append("INDEX") - if options.contains(.ifNotExists) { - chunks.append("IF NOT EXISTS") - } - chunks.append(name.quotedDatabaseIdentifier) - chunks.append("ON") - chunks.append(""" - \(table.quotedDatabaseIdentifier)(\ - \(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\ - ) - """) - if let condition { - try chunks.append("WHERE \(condition.quotedSQL(db))") - } - return chunks.joined(separator: " ") - } } diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index c46f3455f..b7a5602da 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -69,6 +69,7 @@ 563B8FBB24A1D036007A48C9 /* ReceiveValuesOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */; }; 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */; }; 563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; + 563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */; }; 563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; }; 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; }; 563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */; }; @@ -295,6 +296,14 @@ 56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F61DEA283D469F00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DE8283D469F00AF9884 /* getThreadsCount.c */; }; + 56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */; }; + 56F89E072A57EBA7002FE2AA /* TableAlteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E032A57EBA7002FE2AA /* TableAlteration.swift */; }; + 56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */; }; + 56F89E092A57EBA7002FE2AA /* ForeignKeyDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */; }; + 56F89E0A2A57EBA7002FE2AA /* IndexDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */; }; + 56F89E1A2A585E0D002FE2AA /* SQLColumnGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */; }; + 56F89E1B2A585E0D002FE2AA /* SQLTableAlterationGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */; }; + 56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */; }; 56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; }; 56FA0C4128B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */; }; 56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; }; @@ -504,6 +513,7 @@ 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReceiveValuesOn.swift; sourceTree = ""; }; 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnDemandFuture.swift; sourceTree = ""; }; 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; + 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = ""; }; 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -792,6 +802,14 @@ 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56F61DE8283D469F00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DE9283D469F00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; + 56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnDefinition.swift; sourceTree = ""; }; + 56F89E032A57EBA7002FE2AA /* TableAlteration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableAlteration.swift; sourceTree = ""; }; + 56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+SchemaDefinition.swift"; sourceTree = ""; }; + 56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinition.swift; sourceTree = ""; }; + 56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexDefinition.swift; sourceTree = ""; }; + 56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnGenerator.swift; sourceTree = ""; }; + 56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableAlterationGenerator.swift; sourceTree = ""; }; + 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLTableGenerator.swift; sourceTree = ""; }; 56FA0C3428B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FA0C4028B20ADB00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = ""; }; 56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = ""; }; @@ -1178,8 +1196,12 @@ 5656A8292295BD56001FF3FF /* SQLGeneration */ = { isa = PBXGroup; children = ( + 56F89E162A585E0D002FE2AA /* SQLColumnGenerator.swift */, 5656A82B2295BD56001FF3FF /* SQLGenerationContext.swift */, + 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */, 5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */, + 56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */, + 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -1187,6 +1209,11 @@ 5656A82C2295BD56001FF3FF /* Schema */ = { isa = PBXGroup; children = ( + 56F89DF82A57EAB9002FE2AA /* ColumnDefinition.swift */, + 56F89E042A57EBA7002FE2AA /* Database+SchemaDefinition.swift */, + 56F89E052A57EBA7002FE2AA /* ForeignKeyDefinition.swift */, + 56F89E062A57EBA7002FE2AA /* IndexDefinition.swift */, + 56F89E032A57EBA7002FE2AA /* TableAlteration.swift */, 5656A82D2295BD56001FF3FF /* TableDefinition.swift */, 5656A82E2295BD56001FF3FF /* VirtualTableModule.swift */, ); @@ -1860,6 +1887,7 @@ 563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */, 5656A85D2295BD56001FF3FF /* VirtualTableModule.swift in Sources */, 5656A8872295BD56001FF3FF /* SQLOperators.swift in Sources */, + 56F89E092A57EBA7002FE2AA /* ForeignKeyDefinition.swift in Sources */, 566DDE12288D76400000DCFB /* Fixits.swift in Sources */, 563EF44D2161F196007DAACD /* Inflections.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -1874,6 +1902,7 @@ 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, + 56F89E1A2A585E0D002FE2AA /* SQLColumnGenerator.swift in Sources */, 56894F332604FC1E00268F4D /* Table.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -1925,6 +1954,7 @@ 563B8FB224A1CE9E007A48C9 /* DatabasePublishers.swift in Sources */, 56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, + 56F89E1B2A585E0D002FE2AA /* SQLTableAlterationGenerator.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 5656A8812295BD56001FF3FF /* SQLCollection.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, @@ -1952,6 +1982,8 @@ 5656A8832295BD56001FF3FF /* SQLExpression.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, + 56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */, + 56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */, 560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */, 5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */, 5690C3421D23E82A00E59934 /* Data.swift in Sources */, @@ -1965,6 +1997,7 @@ 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, + 56F89E072A57EBA7002FE2AA /* TableAlteration.swift in Sources */, 56FBFED62210731100945324 /* SQLRequest.swift in Sources */, 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, @@ -1983,10 +2016,13 @@ 564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */, 5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, + 563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */, 5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, + 56F89E0A2A57EBA7002FE2AA /* IndexDefinition.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, 56D110F328AFC90800E64463 /* MutablePersistableRecord.swift in Sources */, + 56F89E082A57EBA7002FE2AA /* Database+SchemaDefinition.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 56D3332329C38D7B00430680 /* WALSnapshotTransaction.swift in Sources */, From 466ecd5ba5026055946cebd44902a0fa36f40c79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 11:38:11 +0200 Subject: [PATCH 24/28] Documentation --- Documentation/AssociationsBasics.md | 44 ++++++++++--------- GRDB/Documentation.docc/DatabaseSchema.md | 12 ++--- GRDB/Documentation.docc/Migrations.md | 5 +-- .../RecordRecommendedPractices.md | 8 +--- .../Association/BelongsToAssociation.swift | 19 ++++---- .../Association/HasManyAssociation.swift | 20 ++++----- .../Association/HasOneAssociation.swift | 16 +++---- 7 files changed, 58 insertions(+), 66 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 1ba5a8c4d..b517dea44 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -429,15 +429,13 @@ The matching [migration] would look like: migrator.registerMigration("Employees") { db in try db.create(table: "employee") { t in t.autoIncrementedPrimaryKey("id") - t.column("managerId", .integer) - .indexed() - .references("employee", onDelete: .restrict) + t.belongsTo("manager", inTable: "employee", onDelete: .setNull) t.column("name", .text) } } ``` -Note that both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example: +Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example: ```swift struct EmployeeInfo: FetchableRecord, Decodable { @@ -536,20 +534,16 @@ migrator.registerMigration("Books and Authors") { db in } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer) // (2) + t.belongsTo("author", onDelete: .cascade) // (2) .notNull() // (3) - .indexed() // (4) - .references("author", onDelete: .cascade) // (5) t.column("title", .text) } } ``` 1. The `author` table has a primary key. -2. The `book.authorId` column is used to link a book to the author it belongs to. +2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. 3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. -4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. -5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns. @@ -595,20 +589,16 @@ migrator.registerMigration("Books and Authors") { db in } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer) // (2) + t.belongsTo("author", onDelete: .cascade) // (2) .notNull() // (3) - .indexed() // (4) - .references("author", onDelete: .cascade) // (5) t.column("title", .text) } } ``` 1. The `author` table has a primary key. -2. The `book.authorId` column is used to link a book to the author it belongs to. +2. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. 3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. -4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. -5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported, including composite primary keys that span several columns. @@ -654,10 +644,9 @@ migrator.registerMigration("Countries") { db in } try db.create(table: "demographics") { t in t.autoIncrementedPrimaryKey("id") - t.column("countryCode", .text) // (2) + t.belongsTo("country", onDelete: .cascade) // (2) .notNull() // (3) .unique() // (4) - .references("country", onDelete: .cascade) // (5) t.column("population", .integer) t.column("density", .double) } @@ -665,10 +654,9 @@ migrator.registerMigration("Countries") { db in ``` 1. The `country` table has a primary key. -2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. +2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information. 3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country. 4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile. -5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information. The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns. @@ -720,6 +708,22 @@ Sometimes the database schema does not define any foreign key. And sometimes, th ![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) +```swift +// The migration that has created the above schema +migrator.registerMigration("Library") { db in + try db.create(table: "person") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.belongsTo("author", inTable: "person") + t.belongsTo("translator", inTable: "person") + t.column("title", .text) + } +} +``` + When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person". Your help is needed. You have to instruct GRDB which foreign key to use: diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index 2469c6539..ce908d8ce 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -135,8 +135,8 @@ try db.create(table: "team") { t in try db.create(table: "membership") { t in // Composite primary key t.primaryKey { - t.column("playerId", .integer).references("player") - t.column("teamId", .text).references("team") + t.belongsTo("player") + t.belongsTo("team") } t.column("role", .text).notNull() } @@ -241,10 +241,10 @@ Unique indexes makes sure SQLite prevents the insertion of conflicting rows: // RECOMMENDED try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") + t.belongsTo("team").notNull() + t.column("position", .integer).notNull() // Players must have distinct names t.column("name", .text).unique() - t.column("teamId", .integer).notNull().references("team") - t.column("position", .integer).notNull() } // One single player at any given position in a team @@ -307,7 +307,7 @@ try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() // A player must refer to an existing team - t.column("teamId", .integer).notNull().references("team") + t.belongsTo("team").notNull() } // REQUIRES EXTRA CONFIGURATION @@ -319,6 +319,8 @@ try db.create(table: "player") { t in } ``` +See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys. + GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema: ```swift diff --git a/GRDB/Documentation.docc/Migrations.md b/GRDB/Documentation.docc/Migrations.md index 4ee44da1f..0af07bddc 100644 --- a/GRDB/Documentation.docc/Migrations.md +++ b/GRDB/Documentation.docc/Migrations.md @@ -26,10 +26,7 @@ migrator.registerMigration("Create authors") { db in migrator.registerMigration("Add books and author.birthYear") { db in try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer) - .notNull() - .indexed() - .references("author", onDelete: .cascade) + t.belongsTo("author").notNull() t.column("title", .text).notNull() } diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md index 8cfbdf1d4..a7a0acf31 100644 --- a/GRDB/Documentation.docc/RecordRecommendedPractices.md +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -31,10 +31,8 @@ migrator.registerMigration("createLibrary") { db in try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() // (5) - t.column("authorId", .integer) // (6) + t.belongsTo("author", onDelete: .cascade) // (6) .notNull() // (7) - .indexed() // (8) - .references("author", onDelete: .cascade) // (9) } } @@ -46,10 +44,8 @@ try migrator.migrate(dbQueue) 3. An author must have a name. 4. The country of an author is not always known. 5. A book must have a title. -6. The `book.authorId` column is used to link a book to the author it belongs to. +6. The `book.authorId` column is used to link a book to the author it belongs to. This column is indexed in order to ease the selection of an author's books. A foreign key is defined from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information. 7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. -8. The `book.authorId` column is indexed in order to ease the selection of an author's books. -9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information. Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc. diff --git a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift index 205414e8c..0bf573452 100644 --- a/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/BelongsToAssociation.swift @@ -28,26 +28,23 @@ /// } /// try db.create(table: "book") { t in /// t.autoIncrementedPrimaryKey("id") -/// t.column("authorId", .integer) // (2) +/// t.belongsTo("author", onDelete: .cascade) // (2) /// .notNull() // (3) -/// .indexed() // (4) -/// .references("author", onDelete: .cascade) // (5) /// t.column("title", .text) /// } /// ``` /// /// 1. The author table has a primary key. /// 2. The `book.authorId` column is used to link a book to the author it -/// belongs to. +/// belongs to. This column is indexed in order to ease the selection of +/// an author's books. A foreign key is defined from `book.authorId` +/// column to `authors.id`, so that SQLite guarantees that no book refers +/// to a missing author. The `onDelete: .cascade` option has SQLite +/// automatically delete all of an author's books when that author is +/// deleted. See for +/// more information. /// 3. Make the `book.authorId` column not null if you want SQLite to guarantee /// that all books have an author. -/// 4. Create an index on the `book.authorId` column in order to ease the -/// selection of an author's books. -/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that -/// SQLite guarantees that no book refers to a missing author. The -/// `onDelete: .cascade` option has SQLite automatically delete all of an -/// author's books when that author is deleted. -/// See for more information. /// /// The example above uses auto-incremented primary keys. But generally /// speaking, all primary keys are supported. diff --git a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift index cce49cdc2..dd8886050 100644 --- a/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasManyAssociation.swift @@ -28,26 +28,22 @@ /// } /// try db.create(table: "book") { t in /// t.autoIncrementedPrimaryKey("id") -/// t.column("authorId", .integer) // (2) +/// t.belongsTo("author", onDelete: .cascade) // (2) /// .notNull() // (3) -/// .indexed() // (4) -/// .references("author", onDelete: .cascade) // (5) /// t.column("title", .text) /// } /// ``` /// /// 1. The author table has a primary key. -/// 2. The `book.authorId` column is used to link a book to the author it -/// belongs to. +/// belongs to. This column is indexed in order to ease the selection of +/// an author's books. A foreign key is defined from `book.authorId` +/// column to `authors.id`, so that SQLite guarantees that no book refers +/// to a missing author. The `onDelete: .cascade` option has SQLite +/// automatically delete all of an author's books when that author is +/// deleted. See for +/// more information. /// 3. Make the `book.authorId` column not null if you want SQLite to guarantee /// that all books have an author. -/// 4. Create an index on the `book.authorId` column in order to ease the -/// selection of an author's books. -/// 5. Create a foreign key from `book.authorId` column to `author.id`, so that -/// SQLite guarantees that no book refers to a missing author. The -/// `onDelete: .cascade` option has SQLite automatically delete all of an -/// author's books when that author is deleted. -/// See for more information. /// /// The example above uses auto-incremented primary keys. But generally /// speaking, all primary keys are supported. diff --git a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift index e0ba88751..16636e138 100644 --- a/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Request/Association/HasOneAssociation.swift @@ -29,10 +29,9 @@ /// } /// try db.create(table: "demographics") { t in /// t.autoIncrementedPrimaryKey("id") -/// t.column("countryCode", .text) // (2) +/// t.belongsTo("country", onDelete: .cascade) // (2) /// .notNull() // (3) /// .unique() // (4) -/// .references("country", onDelete: .cascade) // (5) /// t.column("population", .integer) /// t.column("density", .double) /// } @@ -40,16 +39,17 @@ /// /// 1. The country table has a primary key. /// 2. The `demographics.countryCode` column is used to link a demographic -/// profile to the country it belongs to. +/// profile to the country it belongs to. This column is indexed in order +/// to ease the selection of the demographics of a country. A foreign key +/// is defined from `demographics.countryCode` column to `country.code`, +/// so that SQLite guarantees that no profile refers to a missing +/// country. The `onDelete: .cascade` option has SQLite automatically +/// delete a profile when its country is deleted. See +/// for more information. /// 3. Make the `demographics.countryCode` column not null if you want SQLite to /// guarantee that all profiles are linked to a country. /// 4. Create a unique index on the `demographics.countryCode` column in order /// to guarantee the unicity of any country's demographics. -/// 5. Create a foreign key from `demographics.countryCode` column to -/// `country.code`, so that SQLite guarantees that no profile refers to a -/// missing country. The `onDelete: .cascade` option has SQLite automatically -/// delete a profile when its country is deleted. -/// See for more information. /// /// The example above uses a string primary for the country table. But generally /// speaking, all primary keys are supported. From f8c99f96bc68954c7851ceef4222f426ae5e394c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 12:19:40 +0200 Subject: [PATCH 25/28] Upgrade playgrounds with belongsTo --- .../Playgrounds/Associations.playground/Contents.swift | 5 +---- .../TransactionObserver.playground/Contents.swift | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/Documentation/Playgrounds/Associations.playground/Contents.swift b/Documentation/Playgrounds/Associations.playground/Contents.swift index 1fd67547b..eb8c84ab0 100644 --- a/Documentation/Playgrounds/Associations.playground/Contents.swift +++ b/Documentation/Playgrounds/Associations.playground/Contents.swift @@ -29,10 +29,7 @@ migrator.registerMigration("createLibrary") { db in try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() - t.column("authorId", .integer) - .notNull() - .indexed() - .references("author", onDelete: .cascade) + t.belongsTo("author", onDelete: .cascade).notNull() } } diff --git a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift index fcfc80234..0db433c81 100644 --- a/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Documentation/Playgrounds/TransactionObserver.playground/Contents.swift @@ -23,7 +23,7 @@ migrator.registerMigration("createPet") { db in try db.create(table: "pet") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() - t.column("ownerId", .integer).references("person", onDelete: .cascade) + t.belongsTo("owner", inTable: "person", onDelete: .cascade) } } try! migrator.migrate(dbQueue) From 913168df2d6445e70baaffd42136911cc1f8a359 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 12:43:01 +0200 Subject: [PATCH 26/28] Upgrade tests with belongsTo --- .../GRDBTests/AssociationAggregateTests.swift | 4 +- ...ciationBelongsToDecodableRecordTests.swift | 2 +- ...ciationBelongsToFetchableRecordTests.swift | 2 +- .../AssociationBelongsToRowScopeTests.swift | 2 +- .../AssociationBelongsToSQLTests.swift | 10 +-- .../AssociationHasManyOrderingTests.swift | 2 +- .../AssociationHasManyRowScopeTests.swift | 6 +- .../AssociationHasManySQLTests.swift | 10 +-- ...sociationHasManyThroughOrderingTests.swift | 4 +- ...sociationHasManyThroughRowScopeTests.swift | 24 +++---- .../AssociationHasManyThroughSQLTests.swift | 40 +++++------ .../GRDBTests/AssociationHasOneSQLTests.swift | 6 +- ...ionHasOneThroughDecodableRecordTests.swift | 4 +- ...ionHasOneThroughFetchableRecordTests.swift | 4 +- ...ssociationHasOneThroughRowScopeTests.swift | 4 +- ...ationHasOneThroughSQLDerivationTests.swift | 4 +- .../AssociationHasOneThroughSQLTests.swift | 72 +++++++++---------- ...ciationPrefetchingCodableRecordTests.swift | 4 +- .../CommonTableExpressionTests.swift | 4 +- Tests/GRDBTests/DatabaseErrorTests.swift | 4 +- Tests/GRDBTests/DerivableRequestTests.swift | 2 +- .../QueryInterfaceExpressionsTests.swift | 2 +- .../QueryInterfacePromiseTests.swift | 2 +- .../QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/SQLLiteralTests.swift | 2 +- Tests/GRDBTests/TableRecordDeleteTests.swift | 4 +- Tests/GRDBTests/TableRecordUpdateTests.swift | 2 +- ...bservationQueryInterfaceRequestTests.swift | 2 +- 28 files changed, 114 insertions(+), 116 deletions(-) diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index 8d4333a26..a29ece144 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -51,13 +51,13 @@ class AssociationAggregateTests: GRDBTestCase { } try db.create(table: "player") { t in t.primaryKey("id", .integer) - t.column("teamId", .integer).references("team") + t.belongsTo("team") t.column("name", .text) t.column("score", .integer) } try db.create(table: "award") { t in t.primaryKey("customPrimaryKey", .integer) - t.column("teamId", .integer).references("team") + t.belongsTo("team") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index 161e8e148..bdfac0827 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -55,7 +55,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { } try db.create(table: "players") { t in t.primaryKey("id", .integer) - t.column("teamId", .integer).references("teams") + t.belongsTo("team") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift index 06e63f47a..e288e6c0c 100644 --- a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -57,7 +57,7 @@ class AssociationBelongsToFetchableRecordTests: GRDBTestCase { } try db.create(table: "players") { t in t.primaryKey("id", .integer) - t.column("teamId", .integer).references("teams") + t.belongsTo("team") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index b7f826ab0..813a993e2 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -27,7 +27,7 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase { } try db.create(table: "players") { t in t.primaryKey("id", .integer) - t.column("teamId", .integer).references("teams") + t.belongsTo("team") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index c56904732..75f26a493 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -330,7 +330,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { t.column("name", .text) } try db.create(table: "children") { t in - t.column("parentId", .integer).references("parents") + t.belongsTo("parent") } } @@ -546,8 +546,8 @@ class AssociationBelongsToSQLTests: GRDBTestCase { t.column("name", .text) } try db.create(table: "children") { t in - t.column("parent1Id", .integer).references("parents") - t.column("parent2Id", .integer).references("parents") + t.belongsTo("parent1", inTable: "parents") + t.belongsTo("parent2", inTable: "parents") } } @@ -1742,7 +1742,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId", .integer).references("a") + t.belongsTo("a") } struct A: TableRecord { } struct B: TableRecord { } @@ -1771,7 +1771,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase { t.column("name", .text) } try db.create(table: "children") { t in - t.column("parentId", .integer).references("parents") + t.belongsTo("parent") } } diff --git a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift index 5feb757c9..dff328b69 100644 --- a/Tests/GRDBTests/AssociationHasManyOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyOrderingTests.swift @@ -36,7 +36,7 @@ class AssociationHasManyOrderingTests: GRDBTestCase { } try db.create(table: "player") { t in t.primaryKey("id", .integer) - t.column("teamId", .integer).notNull().references("team") + t.belongsTo("team").notNull() t.column("name", .text).notNull() t.column("position", .integer).notNull() } diff --git a/Tests/GRDBTests/AssociationHasManyRowScopeTests.swift b/Tests/GRDBTests/AssociationHasManyRowScopeTests.swift index a3d244ea9..69f450aa7 100644 --- a/Tests/GRDBTests/AssociationHasManyRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasManyRowScopeTests.swift @@ -18,7 +18,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent") + t.belongsTo("parent") } try db.execute(sql: """ INSERT INTO parent (id) VALUES (1); @@ -49,7 +49,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase { } try db.create(table: "children") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parents") + t.belongsTo("parent") } try db.execute(sql: """ INSERT INTO parents (id) VALUES (1); @@ -79,7 +79,7 @@ class AssociationHasManyRowScopeTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent") + t.belongsTo("parent") } try db.execute(sql: """ INSERT INTO parent (id) VALUES (1); diff --git a/Tests/GRDBTests/AssociationHasManySQLTests.swift b/Tests/GRDBTests/AssociationHasManySQLTests.swift index ffc3fcaab..f56133ab0 100644 --- a/Tests/GRDBTests/AssociationHasManySQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManySQLTests.swift @@ -217,7 +217,7 @@ class AssociationHasManySQLTests: GRDBTestCase { t.primaryKey("id", .integer) } try db.create(table: "children") { t in - t.column("parentId", .integer).references("parents") + t.belongsTo("parent") } } @@ -346,8 +346,8 @@ class AssociationHasManySQLTests: GRDBTestCase { t.primaryKey("id", .integer) } try db.create(table: "children") { t in - t.column("parent1Id", .integer).references("parents") - t.column("parent2Id", .integer).references("parents") + t.belongsTo("parent1", inTable: "parents") + t.belongsTo("parent2", inTable: "parents") } } @@ -1074,10 +1074,10 @@ class AssociationHasManySQLTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent") + t.belongsTo("parent") } try db.create(table: "toy") { t in - t.column("childId", .integer).references("child") + t.belongsTo("child") } } diff --git a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift index 79be3fa5e..0b9946192 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift @@ -40,8 +40,8 @@ class AssociationHasManyThroughOrderingTests: GRDBTestCase { t.column("name", .text).notNull() } try db.create(table: "playerRole") { t in - t.column("teamId", .integer).notNull().references("team") - t.column("playerId", .integer).notNull().references("player") + t.belongsTo("team").notNull() + t.belongsTo("player").notNull() t.column("position", .integer).notNull() t.primaryKey(["teamId", "playerId"]) } diff --git a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift index 215720a6b..fbe43d7b5 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughRowScopeTests.swift @@ -23,11 +23,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "parent") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("child") + t.belongsTo("child") } try db.create(table: "grandChild") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("child") + t.belongsTo("child") } try db.execute(sql: """ INSERT INTO child (id) VALUES (1); @@ -64,11 +64,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "parents") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("children") + t.belongsTo("child") } try db.create(table: "grandChildren") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("children") + t.belongsTo("child") } try db.execute(sql: """ INSERT INTO children (id) VALUES (1); @@ -106,11 +106,11 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "parents") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("children") + t.belongsTo("child") } try db.create(table: "grandChildren") { t in t.autoIncrementedPrimaryKey("id") - t.column("childId").references("children") + t.belongsTo("child") } try db.execute(sql: """ INSERT INTO children (id) VALUES (1); @@ -157,8 +157,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId").references("parent") - t.column("grandChildId").references("grandChild") + t.belongsTo("parent") + t.belongsTo("grandChild") } try db.execute(sql: """ INSERT INTO parent (id) VALUES (1); @@ -198,8 +198,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "children") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId").references("parents") - t.column("grandChildId").references("grandChildren") + t.belongsTo("parent") + t.belongsTo("grandChild") } try db.execute(sql: """ INSERT INTO parents (id) VALUES (1); @@ -237,8 +237,8 @@ class AssociationHasManyThroughRowScopeTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId").references("parent") - t.column("grandChildId").references("grandChild") + t.belongsTo("parent") + t.belongsTo("grandChild") } try db.execute(sql: """ INSERT INTO parent (id) VALUES (1); diff --git a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift index d054a57c2..816e8beac 100644 --- a/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasManyThroughSQLTests.swift @@ -26,11 +26,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasManyWithTwoSteps( @@ -66,11 +66,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasManyWithTwoSteps( @@ -109,8 +109,8 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") - t.column("aId").references("a") + t.belongsTo("c") + t.belongsTo("a") } try testHasManyWithTwoSteps( @@ -146,11 +146,11 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasManyWithTwoSteps( @@ -334,13 +334,13 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent") + t.belongsTo("parent") } try db.create(table: "toy") { t in - t.column("childId", .integer).references("child") + t.belongsTo("child") } try db.create(table: "pet") { t in - t.column("childId", .integer).references("child") + t.belongsTo("child") } } @@ -462,15 +462,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try testHasManyWithThreeSteps( @@ -521,15 +521,15 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasManyWithThreeSteps( @@ -581,12 +581,12 @@ class AssociationHasManyThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") - t.column("dId").references("d") + t.belongsTo("b") + t.belongsTo("d") } try testHasManyWithThreeSteps( diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift index f61c05772..6d7420787 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -189,7 +189,7 @@ class AssociationHasOneSQLTests: GRDBTestCase { t.primaryKey("id", .integer) } try db.create(table: "children") { t in - t.column("parentId", .integer).references("parents") + t.belongsTo("parent") } } @@ -299,8 +299,8 @@ class AssociationHasOneSQLTests: GRDBTestCase { t.primaryKey("id", .integer) } try db.create(table: "children") { t in - t.column("parent1Id", .integer).references("parents") - t.column("parent2Id", .integer).references("parents") + t.belongsTo("parent1", inTable: "parents") + t.belongsTo("parent2", inTable: "parents") } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift index dccbce7b4..2a976c262 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughDecodableRecordTests.swift @@ -49,12 +49,12 @@ class AssociationHasOneThroughDecodableRecordTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") t.column("name", .text) } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift index ee45837bd..d0a49bfff 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughFetchableRecordTests.swift @@ -86,12 +86,12 @@ class AssociationHasOneThroughFetchableRecordTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") t.column("name", .text) } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift index 05981b01f..f5138711f 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughRowScopeTests.swift @@ -35,12 +35,12 @@ class AssociationHasOneThroughRowscopeTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") t.column("name", .text) } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") t.column("name", .text) } diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index 630c7aa88..ce9a335e0 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -38,11 +38,11 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift index 368aadd96..a9521cc5c 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLTests.swift @@ -28,11 +28,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithTwoSteps( @@ -68,11 +68,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithTwoSteps( @@ -111,8 +111,8 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") - t.column("aId").references("a") + t.belongsTo("c") + t.belongsTo("a") } try testHasOneWithTwoSteps( @@ -148,11 +148,11 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithTwoSteps( @@ -437,15 +437,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("dId").references("d") + t.belongsTo("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithThreeSteps( @@ -494,15 +494,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithThreeSteps( @@ -554,12 +554,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") - t.column("dId").references("d") + t.belongsTo("b") + t.belongsTo("d") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithThreeSteps( @@ -608,15 +608,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try testHasOneWithThreeSteps( @@ -668,12 +668,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("dId").references("d") + t.belongsTo("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") - t.column("cId").references("c") + t.belongsTo("a") + t.belongsTo("c") } try testHasOneWithThreeSteps( @@ -725,12 +725,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") - t.column("cId").references("c") + t.belongsTo("a") + t.belongsTo("c") } try testHasOneWithThreeSteps( @@ -782,12 +782,12 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") - t.column("dId").references("d") + t.belongsTo("b") + t.belongsTo("d") } try testHasOneWithThreeSteps( @@ -836,15 +836,15 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("aId").references("a") + t.belongsTo("a") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try testHasOneWithThreeSteps( @@ -1724,19 +1724,19 @@ class AssociationHasOneThroughSQLTests: GRDBTestCase { } try db.create(table: "d") { t in t.autoIncrementedPrimaryKey("id") - t.column("eId").references("e") + t.belongsTo("e") } try db.create(table: "c") { t in t.autoIncrementedPrimaryKey("id") - t.column("dId").references("d") + t.belongsTo("d") } try db.create(table: "b") { t in t.autoIncrementedPrimaryKey("id") - t.column("cId").references("c") + t.belongsTo("c") } try db.create(table: "a") { t in t.autoIncrementedPrimaryKey("id") - t.column("bId").references("b") + t.belongsTo("b") } let associations = [ diff --git a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift index f981209ba..7877a5e2d 100644 --- a/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingCodableRecordTests.swift @@ -1350,9 +1350,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase { try dbQueue.write { db in try db.create(table: "employee") { t in t.autoIncrementedPrimaryKey("id") - t.column("managerId", .integer) - .indexed() - .references("employee", onDelete: .restrict) + t.belongsTo("manager", inTable: "employee", onDelete: .restrict) t.column("name", .text) } try db.execute(sql: """ diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index c12a52ebe..448b06add 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -631,11 +631,11 @@ class CommonTableExpressionTests: GRDBTestCase { } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") - t.column("teamId", .integer).references("team") + t.belongsTo("team") } try db.create(table: "award") { t in t.autoIncrementedPrimaryKey("id") - t.column("playerId", .integer).references("player") + t.belongsTo("player") } struct Team: TableRecord { } struct Player: TableRecord { diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index fe7b42448..8bba886ff 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -205,7 +205,7 @@ class DatabaseErrorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { $0.column("id", .integer).primaryKey() } - try db.create(table: "children") { $0.column("parentId", .integer).references("parents") } + try db.create(table: "children") { $0.belongsTo("parent") } do { try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)") } catch let error as DatabaseError { @@ -219,7 +219,7 @@ class DatabaseErrorTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "parents") { $0.column("id", .integer).primaryKey() } - try db.create(table: "children") { $0.column("parentId", .integer).references("parents") } + try db.create(table: "children") { $0.belongsTo("parent") } do { try db.execute(sql: "INSERT INTO children (parentId) VALUES (1)") } catch let error as NSError { diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 3d418da97..d5555ee9e 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -50,7 +50,7 @@ private var libraryMigrator: DatabaseMigrator = { } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer).notNull().references("author") + t.belongsTo("author").notNull() t.column("title", .text).notNull() } try db.create(virtualTable: "bookFts4", using: FTS4()) { t in diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 57a2863cf..c4b0c0046 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -660,7 +660,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { try dbQueue.write { db in try db.create(table: "parent") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent") + t.belongsTo("parent") } try db.create(table: "child") { t in t.column("childParentId", .integer).references("parent") diff --git a/Tests/GRDBTests/QueryInterfacePromiseTests.swift b/Tests/GRDBTests/QueryInterfacePromiseTests.swift index 1cd1c14de..fc4fb50cf 100644 --- a/Tests/GRDBTests/QueryInterfacePromiseTests.swift +++ b/Tests/GRDBTests/QueryInterfacePromiseTests.swift @@ -14,7 +14,7 @@ class QueryInterfacePromiseTests: GRDBTestCase { try dbWriter.write { db in try db.create(table: "node") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("node") + t.belongsTo("parent", inTable: "node") } } } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index d3450c6a2..91f032354 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -300,7 +300,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { } try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer).references("author") + t.belongsTo("author") } try db.execute(sql: """ INSERT INTO author(id, name) VALUES (1, 'Arthur'); diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index d1c04b7d4..e5ef6272b 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -614,7 +614,7 @@ extension SQLLiteralTests { } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") - t.column("teamId", .integer).references("team") + t.belongsTo("team") t.column("score", .integer) } struct Player: TableRecord { } diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index 23df2f131..88e9c8174 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -382,7 +382,7 @@ class TableRecordDeleteTests: GRDBTestCase { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") - t.column("teamId", .integer).references("team") + t.belongsTo("team") } do { @@ -457,7 +457,7 @@ class TableRecordDeleteTests: GRDBTestCase { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") - t.column("teamId", .integer).references("team") + t.belongsTo("team") } do { diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index 31a523708..b5de3fab7 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -674,7 +674,7 @@ class TableRecordUpdateTests: GRDBTestCase { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") - t.column("teamId", .integer).references("team") + t.belongsTo("team") t.column("score", .integer) } diff --git a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift index 30317ed65..c11704e34 100644 --- a/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/ValueObservationQueryInterfaceRequestTests.swift @@ -26,7 +26,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase { } try db.create(table: "child") { t in t.autoIncrementedPrimaryKey("id") - t.column("parentId", .integer).references("parent", onDelete: .cascade) + t.belongsTo("parent", onDelete: .cascade) t.column("name", .text) } } From 4ac434c83ca723c704b4df9d80406ad66d62d6e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 11:51:06 +0200 Subject: [PATCH 27/28] CHANGELOG --- CHANGELOG.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 350e1e0cf..1b45cd179 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -119,6 +119,16 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: - **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes - **New**: [#1402](https://github.com/groue/GRDB.swift/pull/1402) by [@groue](https://github.com/groue): Upgrade custom SQLite builds to 3.42.0 - **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13 +- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema +- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405): + - [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:)) + - [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) + - [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations) + - [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) + - [Associations](Documentation/AssociationsBasics.md) + - [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation) + - [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation) + - [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation) ## 6.15.1 From e16d4accb324ca2c04f202814b348d48a9ad1dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 9 Jul 2023 18:08:27 +0200 Subject: [PATCH 28/28] v6.16.0 --- CHANGELOG.md | 5 ++++- GRDB.swift.podspec | 2 +- README.md | 2 +- Support/Info.plist | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b45cd179..cd6621e25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: #### 6.x Releases +- `6.16.x` Releases - [6.16.0](#6160) - `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151) - `6.14.x` Releases - [6.14.0](#6140) - `6.13.x` Releases - [6.13.0](#6130) @@ -113,7 +114,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- -## Next Release +## 6.16.0 + +Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.15.1...v6.16.0) - **New**: [#1397](https://github.com/groue/GRDB.swift/pull/1397) by [@groue](https://github.com/groue): Swift API for creating database views - **New**: [#1401](https://github.com/groue/GRDB.swift/pull/1401) by [@kustra](https://github.com/kustra): Linux compilation fixes diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 594701479..24952f89f 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.15.1' + s.version = '6.16.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' diff --git a/README.md b/README.md index 636350339..85cbd4ad0 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ CI Status

-**Latest release**: June 17, 2023 • [version 6.15.1](https://github.com/groue/GRDB.swift/tree/v6.15.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: July 9, 2023 • [version 6.16.0](https://github.com/groue/GRDB.swift/tree/v6.16.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) **Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ diff --git a/Support/Info.plist b/Support/Info.plist index f5b1cc90d..3538d97b0 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.15.1 + 6.16.0 CFBundleSignature ???? CFBundleVersion