Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2025-09-23 20:14:27 +02:00
commit c5d02eac32
69 files changed
+3090 -403

No files matched your search

+10
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.7.x` Releases - [7.7.0](#770)
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
- `7.5.x` Releases - [7.5.0](#750)
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
@@ -138,6 +139,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.7.0
Released September 23, 2025
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
## 7.6.1
Released July 23, 2025
@@ -158,7 +158,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 1600;
LastUpgradeCheck = 2600;
TargetAttributes = {
56CFC6432C9F1DC9000B5023 = {
CreatedOnToolsVersion = 16.0;
@@ -293,6 +293,7 @@
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
@@ -350,6 +351,7 @@
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_EMIT_LOC_STRINGS = YES;
VALIDATE_PRODUCT = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1600"
LastUpgradeVersion = "2600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -56,7 +56,7 @@ import GRDB
// Start observing the database.
// Previous observation, if any, is cancelled.
cancellable = observation.start(in: appDatabase.reader) { error in
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
// Handle error
} onChange: { [unowned self] players in
self.players = players
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.6.1'
s.version = '7.7.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+18 -1
View File
@@ -81,6 +81,7 @@
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
@@ -223,6 +224,7 @@
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
@@ -288,6 +290,7 @@
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
@@ -503,6 +506,7 @@
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
@@ -674,6 +678,7 @@
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
@@ -792,6 +797,7 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
@@ -997,6 +1003,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1486,6 +1493,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
@@ -1592,6 +1600,7 @@
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
@@ -1842,8 +1851,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -2009,6 +2019,7 @@
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
@@ -2113,6 +2124,7 @@
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
@@ -2207,6 +2219,7 @@
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
@@ -2539,6 +2552,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2546,6 +2560,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -2570,6 +2585,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2577,6 +2593,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+20 -4
View File
@@ -87,7 +87,7 @@ public struct Configuration: Sendable {
/// with the number of snapshots.
///
/// The default configuration label is nil.
public var label: String? = nil
public var label: String?
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they does not match any
@@ -329,7 +329,7 @@ public struct Configuration: Sendable {
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
/// If nil, GRDB picks a default one.
var readonlyBusyMode: Database.BusyMode? = nil
var readonlyBusyMode: Database.BusyMode?
/// The maximum number of concurrent reader connections.
///
@@ -387,7 +387,7 @@ public struct Configuration: Sendable {
/// ``qos`` property.
///
/// The default is nil.
public var targetQueue: DispatchQueue? = nil
public var targetQueue: DispatchQueue?
/// The target dispatch queue for write database accesses.
///
@@ -395,7 +395,7 @@ public struct Configuration: Sendable {
/// by ``targetQueue``.
///
/// The default is nil.
public var writeTargetQueue: DispatchQueue? = nil
public var writeTargetQueue: DispatchQueue?
#if os(iOS)
/// A boolean value indicating whether the database connection releases
@@ -421,6 +421,22 @@ public struct Configuration: Sendable {
/// reveals that a lot of time is spent opening new SQLite connections.
public var persistentReadOnlyConnections = false
// MARK: - Database Schema
/// A custom schema source.
///
/// The use case for a custom schema source is enabling GRDB features that
/// would not work with the built-in schema introspection that is provided
/// by SQLite. For example, a custom schema source can help record types
/// that read or write in a database view.
///
/// The schema source is automatically disabled during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public var schemaSource: (any DatabaseSchemaSource)?
// MARK: - Factory Configuration
/// Creates a factory configuration.
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -387,7 +387,7 @@ extension SQLStatementCursor: Cursor {
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
// Compile next statement
var statementEnd: UnsafePointer<CChar>? = nil
var statementEnd: UnsafePointer<CChar>?
let statement = try Statement(
database: database,
statementStart: baseAddress + offset,
+26 -7
View File
@@ -113,6 +113,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``resumeNotification``
/// - ``suspendNotification``
///
/// ### The Schema Source
///
/// - ``schemaSource``
/// - ``withSchemaSource(_:execute:)``
///
/// ### Other Database Operations
///
/// - ``add(tokenizer:)``
@@ -169,7 +174,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// connection has been opened is an SQLite misuse, and has no effect.
///
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
nonisolated(unsafe) public static var logError: LogErrorFunction? {
didSet {
if logError != nil {
_registerErrorLogCallback { (_, code, message) in
@@ -187,6 +192,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The database configuration.
public let configuration: Configuration
/// The current schema source.
///
/// By default, it is the ``Configuration/schemaSource``
/// of ``configuration``. To modify the schema source,
/// use ``withSchemaSource(_:execute:)``.
///
/// The schema source is automatically disabled (nil) during database
/// migrations performed by ``DatabaseMigrator``: those access the raw
/// SQLite schema, unaltered. If a migration needs a schema source,
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
/// the body of a migration.
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
/// A description of this database connection.
///
/// The returned string is based on the ``Configuration/label``
@@ -442,6 +460,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaSource = configuration.schemaSource
self.path = path
// We do not report read-only transactions to transaction observers, so
@@ -459,7 +478,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
var sqliteConnection: SQLiteConnection? = nil
var sqliteConnection: SQLiteConnection?
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
// https://www.sqlite.org/c3ref/open.html
@@ -806,7 +825,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
collationPointer,
{ (collationPointer, length1, buffer1, length2, buffer2) in
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
@@ -1286,7 +1305,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
var statement: SQLiteStatement? = nil
var statement: SQLiteStatement?
let sql = "PRAGMA journal_mode"
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
defer { sqlite3_finalize(statement) }
@@ -1483,7 +1502,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that transaction has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1626,7 +1645,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
// what happened.
var firstError: Error? = nil
var firstError: Error?
let needsRollback: Bool
do {
let completion = try operations()
@@ -1744,7 +1763,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
/// Commits a database transaction.
+20 -16
View File
@@ -53,12 +53,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
}
}
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
/// <https://www.sqlite.org/c3ref/create_collation.html>
typealias XCompare = @Sendable (
_ length1: CInt,
_ buffer1: UnsafeRawPointer,
_ length2: CInt,
_ buffer2: UnsafeRawPointer
) -> CInt
/// The identifier of the collation.
public var id: ID { ID(name: name) }
/// The name of the collation.
public let name: String
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
let xCompare: XCompare
/// Creates a collation.
///
@@ -75,21 +84,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
/// - parameters:
/// - name: The collation name.
/// - function: A function that compares two strings.
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
return CInt(function(string1, string2).rawValue)
})
}
init(_ name: String, xCompare: @escaping XCompare) {
self.name = name
self.function = { (length1, buffer1, length2, buffer2) in
// Buffers are not C strings: they do not end with \0.
let string1 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
length: Int(length1),
encoding: .utf8,
freeWhenDone: false)!
let string2 = String(
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
length: Int(length2),
encoding: .utf8,
freeWhenDone: false)!
return function(string1, string2)
}
self.xCompare = xCompare
}
}
+46 -18
View File
@@ -82,20 +82,43 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
/// have exactly `argumentCount` elements, provided `argumentCount` is
/// not nil.
public init(
public convenience init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv[index]!)
}
let result = try function(arguments)
switch result?.databaseValue.storage ?? .null {
case .null:
sqlite3_result_null(context)
case .int64(let int64):
sqlite3_result_int64(context, int64)
case .double(let double):
sqlite3_result_double(context, double)
case .string(let string):
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes {
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
}
}
}
}
init(
_ name: String,
argumentCount: Int? = nil,
pure: Bool = false,
xFunc: @escaping XFunc)
{
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.isPure = pure
self.kind = .function { (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
}
return try function(arguments)
}
self.kind = .function(xFunc)
}
/// Creates an SQL aggregate function.
@@ -256,11 +279,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private class FunctionDefinition {
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
throws -> (any DatabaseValueConvertible)?)
let xFunc: XFunc
init(xFunc: @escaping XFunc)
{
self.compute = compute
self.xFunc = xFunc
}
}
@@ -283,11 +305,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
}
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
typealias XFunc = @Sendable (
_ argc: CInt,
_ argv: UnsafeMutablePointer<OpaquePointer?>,
_ context: OpaquePointer?
) throws -> Void
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
private enum Kind: Sendable {
/// A regular function: SELECT f(1)
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
case function(XFunc)
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
case aggregate(@Sendable () -> any DatabaseAggregate)
@@ -296,8 +326,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
var definition: AnyObject {
switch self {
case .function(let compute):
return FunctionDefinition(compute: compute)
case .function(let xFunc):
return FunctionDefinition(xFunc: xFunc)
case .aggregate(let makeAggregate):
return AggregateDefinition(makeAggregate: makeAggregate)
}
@@ -312,9 +342,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
.fromOpaque(sqlite3_user_data(sqliteContext))
.takeUnretainedValue()
do {
try DatabaseFunction.report(
result: definition.compute(argc, argv),
in: sqliteContext)
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
} catch {
DatabaseFunction.report(error: error, in: sqliteContext)
}
@@ -464,7 +492,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate {
public protocol DatabaseAggregate: GRDBSendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+21 -6
View File
@@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader {
return try await readerPool.get { reader in
try await reader.execute { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
// The block isolation comes from the DEFERRED transaction.
@@ -387,8 +392,13 @@ extension DatabasePool: DatabaseReader {
// Second async jump because that's how `Pool.async` has to be used.
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
@@ -551,8 +561,13 @@ extension DatabasePool: DatabaseReader {
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
// Ignore commit error, but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
releaseReader(.reuse)
}
+14 -4
View File
@@ -248,8 +248,13 @@ extension DatabaseQueue: DatabaseReader {
) {
writer.async { db in
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
@@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
defer {
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
try? db.endReadOnly()
}
+2 -2
View File
@@ -256,8 +256,8 @@ extension DatabaseRegion {
}
} else {
// full database
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
let schema = try db.schema(schemaIdentifier)
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
let schema = try db.schema(schemaID)
return try schema.objects
.filter { $0.type == .table }
.flatMap { table in
+6 -2
View File
@@ -201,7 +201,11 @@ extension DatabasePublishers {
self.observation = observation
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = DatabaseRegionSubscription(
writer: writer,
observation: observation,
@@ -212,7 +216,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+218
View File
@@ -0,0 +1,218 @@
/// A type that provides information about the database schema.
///
/// ## Overview
///
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
///
/// The use case for a custom schema source is to enable GRDB features that
/// would not work with the built-in schema introspection provided
/// by SQLite.
///
/// For example, if your database schema contains a view and you wish to use
/// GRDB features that need a primary key, such as the
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
/// methods of the ``PersistableRecord`` protocol, then use a schema source
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
/// <doc:ViewRecords> for a detailed guide about such views.
///
/// ## Enabling a Schema Source
///
/// To enable a schema source in a database connection, configure its
/// ``Configuration/schemaSource``:
///
/// ```swift
/// struct MySchemaSource: DatabaseSchemaSource { ... }
///
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
/// ```
///
/// ## Schema Sources and Migrations
///
/// By default, schema sources are disabled during <doc:Migrations>. In
/// migrations that need a schema source, you can use
/// ``Database/withSchemaSource(_:execute:)``:
///
/// ```swift
/// migrator.registerMigration("My migration") { db in
/// // No schema source is enabled at this point.
/// try db.withSchemaSource(MySchemaSource()) {
/// // Here the provided schema source is in effect.
/// }
/// }
/// ```
///
/// Take care that **a good migration is a migration that is never
/// modified once it has shipped**: check
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
///
/// ## Topics
///
/// ### Customizing the Database Schema
///
/// - ``columnsForPrimaryKey(_:inView:)``
///
/// ### Chaining Schema Sources
///
/// - ``then(_:)``
public protocol DatabaseSchemaSource: Sendable {
/// Returns the names of the columns for the primary key in the
/// provided database view.
///
/// Return `nil` if no customization should happen. Return an empty
/// array to specify that the view has no primary key. The default
/// implementation returns `nil`.
///
/// In your implementation, make sure that the returned columns define
/// a genuine **primary key**:
///
/// - All columns exist in the provided view.
/// - The set of columns reliably identifies and distinguishes between
/// each individual row in the view.
/// - No column contains NULL values.
///
/// It is a programmer error with undefined consequences to miss
/// those requirements.
///
/// For example:
///
/// ```swift
/// // A schema source that specifies that all views are identified by
/// // their "id" column:
/// struct MySchemaSource: DatabaseSchemaSource {
/// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
/// ["id"]
/// }
/// }
///
/// // A database connection configured with the schema source.
/// var config = Configuration()
/// config.schemaSource = MySchemaSource()
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
///
/// // A record type that feeds from a view.
/// struct Player: Decodable, Identifiable, FetchableRecord {
/// static let databaseTableName = "playerView"
/// var id: String
/// var name: String
/// }
///
/// // Thanks to the schema source, we can fetch players by id:
/// let player = try dbQueue.read { db in
/// try Player.find(db, id: "alice")
/// }
/// ```
///
/// ### Schema Sources in Libraries
///
/// When you are developing a schema source for a library, some extra
/// care is necessary whenever the database file is owned by the users
/// of your library. Your users may define views for their own purposes,
/// and your library knows nothing about the eventual primary key of
/// those views.
///
/// In this case, make your schema source `public`, and have this method
/// return `nil` for those unknown views. If needed, use the `db`
/// argument and query the database schema with
/// <doc:DatabaseSchemaIntrospection> methods.
///
/// For example:
///
/// ```swift
/// // A well-behaved schema source defined by a library is public
/// // and returns nil for unknown views.
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
/// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
/// if view.name == "playerView" {
/// // This is a view managed by my library:
/// return ["id"]
/// } else if try db.tableExists(view.name + "MyLibrary") {
/// // This is a view managed by my library:
/// return ["uuid"]
/// } else {
/// // Not a view managed by my library:
/// // don't mess with user's schema
/// return nil
/// }
/// }
/// }
/// ```
///
/// With such a setup, your user will be able to deal with their
/// own views, by chaining your schema source with other ones
/// (see ``DatabaseSchemaSource/then(_:)``):
///
/// ```swift
/// // Application code
/// import MyLibrary
/// import GRDB
///
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
/// let customSchemaSource = TheirCustomSchemaSource()
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
///
/// - Parameters:
/// - db: A database connection.
/// - view: The identifier of a database view.
func columnsForPrimaryKey(
_ db: Database,
inView view: DatabaseObjectID
) throws -> [String]?
}
extension DatabaseSchemaSource {
public func columnsForPrimaryKey(
_ db: Database,
inView view: DatabaseObjectID
) throws -> [String]? {
nil
}
}
// MARK: - Combined2SchemaSource
extension DatabaseSchemaSource {
/// Returns a schema source that queries `other` when this source does
/// not perform a customization.
///
/// For example:
///
/// ```swift
/// let schemaSource1 = SomeSchemaSource()
/// let schemaSource2 = AnotherSchemaSource()
/// let schemaSource = schemaSource1.then(schemaSource2)
///
/// var config = Configuration()
/// config.schemaSource = schemaSource
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
/// ```
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
Chained2SchemaSource(first: self, second: other)
}
}
// TODO: move to parameter packs eventually. Parameter packs in generic types
// are only available in macOS 14.0.0 or newer.
// This schema source is designed to tame bad citizens that customize tables
// and views they do not own (such as insufficienly robust schema sources
// exposed by external libraries). We should NEVER MERGE the results of the
// schema sources.
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
where Source1: DatabaseSchemaSource,
Source2: DatabaseSchemaSource
{
var first: Source1
var second: Source2
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
return nil
}
}
+7 -2
View File
@@ -113,8 +113,13 @@ public final class DatabaseSnapshot {
deinit {
// Leave snapshot isolation
reader.reentrantSync { db in
// Ignore commit error (we can not notify it), but make sure we leave the transaction
try? db.commit()
// Commit or rollback, but make sure we leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
assert(!db.isInsideTransaction)
}
}
+4
View File
@@ -43,3 +43,7 @@ private final class DispatchQueueExecutor: SerialExecutor {
dispatchPrecondition(condition: .onQueue(queue))
}
}
#if os(Linux)
extension DispatchQueueExecutor: @unchecked Sendable {}
#endif
+1 -1
View File
@@ -141,7 +141,7 @@ public final class Statement {
let authorizer = database.authorizer
authorizer.reset()
var sqliteStatement: SQLiteStatement? = nil
var sqliteStatement: SQLiteStatement?
let code = sqlite3_prepare_v3(
database.sqliteConnection, statementStart, -1, prepFlags,
&sqliteStatement, statementEnd)
+1 -1
View File
@@ -1494,7 +1494,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
-> DatabaseValue?
{
var value: SQLiteValue? = nil
var value: SQLiteValue?
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
if let value {
return DatabaseValue(sqliteValue: value)
+7 -1
View File
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
// WALSnapshotTransaction may be deinitialized in the dispatch
// queue of its reader: allow reentrancy.
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
try? db.commit()
// Commit or rollback, but try hard to leave the read-only transaction
// (commit may fail with a CancellationError).
do {
try db.commit()
} catch {
try? db.rollback()
}
return db.isInsideTransaction
}
release(isInsideTransaction)
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
### Supporting Types
- ``DatabaseSchemaID``
- ``DatabaseObjectID``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
@@ -96,6 +96,7 @@ do {
- ``persistentReadOnlyConnections``
- ``prepareDatabase(_:)``
- ``publicStatementArguments``
- ``schemaSource``
- ``transactionClock``
- ``TransactionClock``
@@ -106,3 +107,7 @@ do {
- ``writeQoS``
- ``targetQueue``
- ``writeTargetQueue``
### Supporting Types
- ``DatabaseSchemaSource``
+1
View File
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
- <doc:ViewRecords>
### Application Tools
@@ -229,5 +229,11 @@ Task {
}
```
## Topics
### Supporting Types
- ``GRDBSendableMetatype``
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
+383
View File
@@ -0,0 +1,383 @@
# View Records
Define record types that target database views.
## Overview
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
```swift
// OK: Works out of the box
let captains = try Captain.fetchAll(db)
let captainCount = try Captain.fetchCount(db)
// KO: Requires extra configuration
// SQLite error 1: database view captain has no primary key
var bob = try Captain.find(db, id: "bob")
bob.name = "Bobby"
// SQLite error 1: cannot modify captain because it is a view
try bob.update(db)
```
This article explains how to solve those errors:
- How to provide a primary key to a view.
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
>
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
## Preliminary Setup
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("Teams and players") { db in
try db.create(table: "team") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.belongsTo("team", onDelete: .setNull)
t.column("isCaptain", .boolean).notNull()
}
// One unique captain per team
try db.create(
indexOn: "player", columns: ["teamId"],
options: .unique,
condition: Column("isCaptain"))
}
```
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
```swift
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
}
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
var id: String
var name: String
var teamId: String?
var isCaptain: Bool
}
```
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
```swift
migrator.registerMigration("Read-only captains") { db in
try db.execute(sql: """
CREATE VIEW captain AS
SELECT id, name, teamId
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
}
struct Captain: Decodable, Identifiable, FetchableRecord {
var id: String
var name: String
var teamId: String
}
```
✅ From now on, we can use the `Captain` record:
```swift
let dbQueue = try DatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.fetchAll(db)
// Prints:
// Captain(id: "alice", name: "Alice", teamId: "red")
// Captain(id: "bob", name: "Bob", teamId: "blue")
print(captains)
}
```
## Specifying the primary key of a view
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
```swift
struct GameSchemaSource: DatabaseSchemaSource {
/// Returns the names of the columns for the primary key in the
/// provided database view.
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
```
We configure the database connection with this schema source:
```swift
var config = Configuration()
config.schemaSource = GameSchemaSource()
let dbQueue = try DatabaseQueue(configuration: config)
try migrator.migrate(dbQueue)
```
✅ We can now use the primary key of captains:
```swift
try dbQueue.read { db in
// [Insert some teams and players...]
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
let alice = try Captain.find(db, id: "alice")
}
```
## Associations between views
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
```swift
extension Captain {
// Time to define some columns
enum Columns {
static let teamId = Column(CodingKeys.teamId)
}
// The captain view has a foreign key to teams,
// from the teamId column to the team primary key.
// SQLite does not know about it, so we declare it explicitly:
static let teamForeignKey = ForeignKey([Columns.teamId])
// A captain belongs to a team.
static let team = belongsTo(Team.self, using: teamForeignKey)
}
extension Team {
// A team has a captain.
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
}
```
✅ We can now use those associations:
```swift
try dbQueue.read { db in
// All teams with a captain
let teamsWithCaptain: [Team] = try Team
.joining(required: Team.captain)
.fetchAll(db)
// All (captain, team) pairs
struct CaptainWithTeam: Decodable, FetchableRecord {
var captain: Captain
var team: Team
}
let captainsWithTeam: [CaptainWithTeam] = try Captain
.including(required: Captain.team)
.asRequest(of: CaptainWithTeam.self)
.fetchAll(db)
}
```
## Inserting rows into a view
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
```swift
migrator.registerMigration("Captain insert") { db in
try db.execute(sql: """
-- Insert trigger
CREATE TRIGGER captain_insert
INSTEAD OF INSERT ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain;
-- Insert new captain
INSERT INTO player(id, name, teamId, isCaptain)
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
```swift
extension Captain: Encodable, PersistableRecord { }
```
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
✅ We can directly insert captains:
```swift
try dbQueue.write {
try Team(id: "green", name: "Green").insert(db)
// Diane is the captain
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
// Well, no: Eugene is the captain
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
// Prints:
// team player captain
// green|Green diane|Diane|green|0 eugene|Eugene|green
// eugene|Eugene|green|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Updating rows in a view
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
```swift
migrator.registerMigration("Captain update") { db in
try db.execute(sql: """
-- Update trigger
CREATE TRIGGER captain_update
INSTEAD OF UPDATE ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
-- Update captain
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
WHERE id = NEW.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's update captains:
```swift
try dbQueue.write {
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
// Bob is the Blue captain.
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
try bob.insert(db)
// Bob is now Bobby, the Red captain.
// Alice is no longer the Red captain.
try bob.updateChanges(db) {
$0.name = "Bobby"
$0.teamId = "red"
}
// Prints:
// team player captain
// blue|Blue alice|Alice|red|0 bob|Bobby|red
// red|Red bob|Bobby|red|1
try db.dumpTables(["team", "player", "captain"])
}
```
## Deleting rows from a view
The last missing INSTEAD OF trigger deals with deletes:
```swift
migrator.registerMigration("Captain delete") { db in
try db.execute(sql: """
-- Delete trigger
CREATE TRIGGER captain_delete
INSTEAD OF DELETE ON captain
BEGIN
DELETE FROM player WHERE id = OLD.id;
END;
""")
}
// Apply the new migration
try migrator.migrate(dbQueue)
```
✅ Let's delete some captains:
```swift
try dbQueue.write {
// Delete Alice
try Captain.deleteOne(db, id: "alice")
// Delete Bob
let bob = try Captain.find(db, id: "bob")
try bob.delete(db)
// Delete all captains
try Captain.deleteAll()
}
```
## Going further
To exercise the techniques described here, try to define record types for these other views:
- The `enrolledPlayer` view that only contains players that belong to a team:
```swift
try db.execute(sql: """
CREATE VIEW enrolledPlayer AS
SELECT id, name, teamId, isCaptain
FROM player
WHERE teamId IS NOT NULL;
""")
```
- The `teamWithCaptainId` view that contains a `captainId` column:
```swift
try db.execute(sql: """
CREATE VIEW teamWithCaptainId AS
SELECT team.id, team.name, player.id AS captainId
FROM team
JOIN player ON player.teamId = team.id AND player.isCaptain;
""")
```
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
```swift
try db.execute(sql: """
CREATE VIEW captain AS
SELECT teamId, name
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
```
[database view]: https://www.sqlite.org/lang_createview.html
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
+2 -2
View File
@@ -117,8 +117,8 @@ public struct FTS5 {
///
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
var statement: SQLiteStatement?
var api: UnsafePointer<fts5_api>?
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
+1 -1
View File
@@ -208,7 +208,7 @@ extension Database {
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
var tokenizerPointer: OpaquePointer?
let code: CInt
if arguments.isEmpty {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
+26 -10
View File
@@ -8,20 +8,36 @@ struct Migration: Sendable {
let identifier: String
var foreignKeyChecks: ForeignKeyChecks
let migrate: @Sendable (Database) throws -> Void
// Private so that the guarantees of `run(_:)` are enforced.
private let migrate: @Sendable (Database) throws -> Void
init(
identifier: String,
foreignKeyChecks: ForeignKeyChecks,
migrate: @escaping @Sendable (Database) throws -> Void
) {
self.identifier = identifier
self.foreignKeyChecks = foreignKeyChecks
self.migrate = migrate
}
func run(_ db: Database) throws {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db)
case .immediate:
// Migrations access the raw SQLite schema, without alteration due
// to the schemaSource. The goal is to ensure that migrations are
// immutable, immune from spooky actions at a distance.
try db.withSchemaSource(nil) {
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
switch foreignKeyChecks {
case .deferred:
try runWithDeferredForeignKeysChecks(db)
case .immediate:
try runWithImmediateForeignKeysChecks(db)
case .disabled:
try runWithDisabledForeignKeysChecks(db)
}
} else {
try runWithImmediateForeignKeysChecks(db)
case .disabled:
try runWithDisabledForeignKeysChecks(db)
}
} else {
try runWithImmediateForeignKeysChecks(db)
}
}
@@ -636,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
var key: String?
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
@@ -362,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest {
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
let databaseTableName = self.databaseTableName
return selectWhenConnected { db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
"selectID requires a single-column primary key in the table \(databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
@@ -633,8 +635,9 @@ extension QueryInterfaceRequest {
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
let prevCount = db.totalChangesCount
try statement.execute()
return db.changesCount
return db.totalChangesCount - prevCount
}
}
@@ -1133,8 +1136,9 @@ extension QueryInterfaceRequest {
// database not hit
return 0
}
let prevCount = db.totalChangesCount
try updateStatement.execute()
return db.changesCount
return db.totalChangesCount - prevCount
}
/// Updates matching rows, and returns the number of updated rows.
@@ -826,10 +826,17 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// ("foo", "bar") do not contain a unique key (primary key
// or unique index).
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
if (try? db.viewExists(databaseTableName)) == true {
fatalError("""
database view \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
} else {
fatalError("""
table \(databaseTableName) has no unique key on column(s) \
\(key.keys.sorted().joined(separator: ", "))
""")
}
}
let lowercaseColumns = columns.map { $0.lowercased() }
+3 -3
View File
@@ -1592,7 +1592,7 @@ extension SQLExpression {
case let .associativeBinary(op, expressions):
assert(expressions.count > 1)
if op == .and {
var result: Set<Int64>? = nil
var result: Set<Int64>?
for expression in expressions {
if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) {
if var rowIDs = result {
@@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation {
var name: String
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -123,7 +123,7 @@ struct SQLForeignKeyRequest {
}
private func tableType(_ db: Database, for name: String) throws -> TableType? {
for schemaID in try db.schemaIdentifiers() {
for schemaID in try db.fetchSchemaIdentifiers() {
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
return TableType(isView: false)
}
+5 -3
View File
@@ -285,12 +285,14 @@ extension SQLRelation: Refinable {
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
if try db.tableExists(source.tableName) {
do {
// Order by primary key. Don't order by rowid because those are
// not stable: rowids can change after a vacuum.
return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
} else {
// Support for views: create a stable order from all columns:
} catch {
// Could not find the primary key. Assume we're ordering
// a view that is not customized with the schemaSource.
// Create a stable order from all columns:
// ORDER BY 1, 2, 3, ...
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord {
public protocol EncodableRecord: GRDBSendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
@@ -53,7 +53,8 @@ extension MutablePersistableRecord {
// Nil primary key
return false
}
let prevCount = db.totalChangesCount
try statement.execute()
return db.changesCount > 0
return (db.totalChangesCount - prevCount) > 0
}
}
@@ -956,8 +956,10 @@ extension MutablePersistableRecord {
// Nil primary key
try dao.recordNotFound()
}
let prevCount = db.totalChangesCount
let returned = try fetch(statement)
if db.changesCount == 0 {
let changesCount = db.totalChangesCount - prevCount
if changesCount == 0 {
// No row was updated
try dao.recordNotFound()
}
@@ -184,6 +184,11 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
/// }
/// ```
///
/// - important: Due to an SQLite limitation, this callback is
/// unreliable when the record type writes into a database view
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
/// not the rowid of the inserted row.
///
/// - parameter inserted: Information about the inserted row.
mutating func didInsert(_ inserted: InsertionSuccess)
+5
View File
@@ -73,6 +73,11 @@ public protocol PersistableRecord: MutablePersistableRecord {
/// - note: If you need a mutating variant of this method, adopt the
/// ``MutablePersistableRecord`` protocol instead.
///
/// - important: Due to an SQLite limitation, this callback is
/// unreliable when the record type writes into a database view
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
/// not the rowid of the inserted row.
///
/// - parameter inserted: Information about the inserted row.
func didInsert(_ inserted: InsertionSuccess)
}
+5 -1
View File
@@ -134,7 +134,7 @@ import Foundation
/// - ``select(_:as:)-tjh0``
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
public protocol TableRecord {
public protocol TableRecord: GRDBSendableMetatype {
/// A type that defines columns.
///
/// For example:
@@ -209,6 +209,10 @@ public protocol TableRecord {
/// // SELECT * FROM player
/// try Player.fetchAll(db)
/// ```
///
/// You can specify the name of a database table, or the name of a
/// database view. When you target a database view, some extra
/// configuration might be needed. Please check <doc:ViewRecords>.
static var databaseTableName: String { get }
/// The columns selected by the record.
+4 -2
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -35,7 +35,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
}
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
where Downstream: Subscriber & GRDBSendableMetatype
{
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
+10
View File
@@ -23,6 +23,16 @@ public func databaseQuestionMarks(count: Int) -> String {
repeatElement("?", count: count).joined(separator: ",")
}
#if compiler(>=6.2)
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = SendableMetatype
#else
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = Any
#endif
// MARK: - Internal
/// Reserved for GRDB: do not use.
@@ -11,7 +11,7 @@
// which is its `Fetcher`.
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer {
public protocol _ValueReducer: GRDBSendableMetatype {
/// The Sendable type that fetches database values
associatedtype Fetcher: _ValueReducerFetcher
+6 -2
View File
@@ -511,7 +511,11 @@ extension DatabasePublishers {
self.start = start
}
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
public func receive<S>(subscriber: S)
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
let subscription = ValueSubscription(
start: start,
downstream: subscriber)
@@ -521,7 +525,7 @@ extension DatabasePublishers {
private class ValueSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error
{
// @unchecked Sendable because `cancellable` and `state` are
+18 -1
View File
@@ -60,6 +60,7 @@
5623B61A2AED39C300436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6182AED39C200436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */; };
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; };
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
@@ -219,6 +220,7 @@
567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */; };
56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
@@ -279,6 +281,7 @@
56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */; };
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; };
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BF22882417821F003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF22862417821F003D86EB /* UtilsTests.swift */; };
56C0539322ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; };
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; };
@@ -516,6 +519,7 @@
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
@@ -698,6 +702,7 @@
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
@@ -801,6 +806,7 @@
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56BF22862417821F003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C0538A22ACEECD0029D27D /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56C0538C22ACEECD0029D27D /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
@@ -1011,6 +1017,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1491,6 +1498,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */,
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
@@ -1597,6 +1605,7 @@
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */,
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
@@ -1880,8 +1889,9 @@
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 1400;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
F3BA80591CFB2BB2003DC1BA = {
@@ -2028,6 +2038,7 @@
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */,
5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */,
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */,
@@ -2252,6 +2263,7 @@
563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */,
@@ -2368,6 +2380,7 @@
566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */,
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
@@ -2555,6 +2568,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2562,6 +2576,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator";
SUPPORTS_MACCATALYST = YES;
@@ -2588,6 +2603,7 @@
DYLIB_COMPATIBILITY_VERSION = 1;
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -2595,6 +2611,7 @@
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
SKIP_INSTALL = YES;
SUPPORTED_PLATFORMS = "appletvos appletvsimulator driverkit iphoneos iphonesimulator macosx watchos watchsimulator";
SUPPORTS_MACCATALYST = YES;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+4 -4
View File
@@ -25,7 +25,7 @@
---
**Latest release**: July 23, 2025 • [version 7.6.1](https://github.com/groue/GRDB.swift/tree/v7.6.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: September 23, 2025 • [version 7.7.0](https://github.com/groue/GRDB.swift/tree/v7.7.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
@@ -335,7 +335,7 @@ Documentation
- [Unicode](#unicode)
- [Memory Management](#memory-management)
- [Data Protection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/Documentation/GRDB7MigrationGuide.md)
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
- :bulb: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
@@ -2194,7 +2194,7 @@ For more information about batch updates, see [Update Requests](#update-requests
> **Note**: Upsert apis are available from SQLite 3.35.0+: iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build] or [SQLCipher](#encryption).
>
> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUdate`, `didUdate` are not called.
> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks reports the rowid of the inserted or updated row; `willUpdate`, `aroundUpdate`, `didUpdate` are not called.
[PersistableRecord] provides three upsert methods:
@@ -3008,7 +3008,7 @@ try player.insert(db)
> // INSERT OR IGNORE INTO player ... RETURNING *
> do {
> let insertedPlayer = try player.insertAndFetch(db) {
> // Succesful insertion
> // Successful insertion
> catch RecordError.recordNotFound {
> // Failed insertion due to IGNORE policy
> }
+2 -2
View File
@@ -1,4 +1,4 @@
@import Foundation;
#import <Foundation/Foundation.h>
//! Project version number for GRDB.
FOUNDATION_EXPORT double GRDB_VersionNumber;
@@ -8,4 +8,4 @@ FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#import <GRDB/GRDBCustomSQLite-USER.h>
#import <GRDB/sqlite3.h>
#import "GRDB-Bridging.h"
#import <GRDB/GRDB-Bridging.h>
-1
View File
@@ -18,7 +18,6 @@ disabled_rules:
- non_optional_string_data_conversion
- opening_brace
- optional_data_string_conversion
- redundant_optional_initialization
- syntactic_sugar
- todo
- trailing_comma
+1 -2
View File
@@ -1,4 +1,4 @@
@import Foundation;
#import <Foundation/Foundation.h>
//! Project version number for GRDB.
FOUNDATION_EXPORT double GRDB_VersionNumber;
@@ -7,4 +7,3 @@ FOUNDATION_EXPORT double GRDB_VersionNumber;
FOUNDATION_EXPORT const unsigned char GRDB_VersionString[];
#import <GRDB/GRDB-Bridging.h>
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.6.1</string>
<string>7.7.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -491,15 +491,19 @@
567B5C4C2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */; };
567B5C4D2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; };
567B5C4E2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; };
568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
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 */; };
56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; };
56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; };
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; };
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
/* End PBXBuildFile section */
@@ -752,8 +756,10 @@
567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -769,7 +775,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5B33E6E34F941B4C839A714F /* (null) in Frameworks */,
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */,
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -935,6 +941,7 @@
56419CF724A5405A004967E1 /* DatabaseRegionObservationTests.swift */,
56419D2624A5405D004967E1 /* DatabaseRegionTests.swift */,
56419CB324A54055004967E1 /* DatabaseSavepointTests.swift */,
56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */,
567B5C222AD32A2D00629622 /* DatabaseSnapshotPoolTests.swift */,
56419CE624A54058004967E1 /* DatabaseSnapshotTests.swift */,
56419CD624A54057004967E1 /* DatabaseSuspensionTests.swift */,
@@ -1019,6 +1026,7 @@
56419C9F24A54054004967E1 /* Record+QueryInterfaceRequestTests.swift */,
56419D0C24A5405B004967E1 /* RecordEditedTests.swift */,
56419CAE24A54054004967E1 /* RecordInitializersTests.swift */,
568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */,
567B5C262AD32A2D00629622 /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
56419D4224A5405F004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
56419D0824A5405B004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
@@ -1380,6 +1388,7 @@
56419E4F24A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
567B5C412AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */,
56419E9F24A54063004967E1 /* FetchableRecordTests.swift in Sources */,
568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419E3324A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
56419DFF24A54062004967E1 /* DatabaseCollationTests.swift in Sources */,
56419E9B24A54063004967E1 /* FTS3RecordTests.swift in Sources */,
@@ -1484,6 +1493,7 @@
56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */,
56419E1124A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */,
56419DC724A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56419EF524A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
56419D6F24A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7324A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
@@ -1630,6 +1640,7 @@
56419E5024A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
567B5C422AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */,
56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */,
568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419E3424A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
56419E0024A54062004967E1 /* DatabaseCollationTests.swift in Sources */,
56419E9C24A54063004967E1 /* FTS3RecordTests.swift in Sources */,
@@ -1734,6 +1745,7 @@
56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */,
56419E1224A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */,
56419DC824A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56419EF624A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
56419D7024A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7424A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
@@ -479,6 +479,8 @@
567B5C462AD32F5900629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */; };
567B5C472AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; };
567B5C482AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; };
568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
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 */; };
@@ -497,11 +499,13 @@
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 */; };
56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; };
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; };
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
/* End PBXBuildFile section */
@@ -748,6 +752,7 @@
567B5C0F2AD32A0000629622 /* TableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = "<group>"; };
567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
@@ -757,6 +762,7 @@
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -772,7 +778,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5B33E6E34F941B4C839A714F /* (null) in Frameworks */,
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */,
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -939,6 +945,7 @@
56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */,
56419F0424A54093004967E1 /* DatabaseRegionTests.swift */,
56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */,
56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */,
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */,
56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */,
56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */,
@@ -1023,6 +1030,7 @@
56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */,
56419F2124A54094004967E1 /* RecordEditedTests.swift */,
56419F4824A54097004967E1 /* RecordInitializersTests.swift */,
568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */,
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
@@ -1386,6 +1394,7 @@
5641A0C424A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06E24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
56419FE424A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */,
5641A0E224A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */,
5641A07E24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */,
@@ -1490,6 +1499,7 @@
5641A00024A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */,
5641A0BE24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */,
5641A07224A540A1004967E1 /* FoundationNSNullTests.swift in Sources */,
56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
5641A14E24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C024A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08024A540A1004967E1 /* ResultCodeTests.swift in Sources */,
@@ -1636,6 +1646,7 @@
5641A0C524A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06F24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
56419FE524A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419FDF24A540A1004967E1 /* NumericOverflowTests.swift in Sources */,
5641A0E324A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */,
5641A07F24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */,
@@ -1740,6 +1751,7 @@
5641A00124A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */,
5641A0BF24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */,
5641A07324A540A1004967E1 /* FoundationNSNullTests.swift in Sources */,
56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
5641A14F24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C124A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08124A540A1004967E1 /* ResultCodeTests.swift in Sources */,
@@ -2359,5 +2359,41 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
""")
}
}
do {
// View with custom primary key.
// Existence check is performed on the primary key.
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorID", .integer)
}
try db.execute(sql: """
CREATE VIEW authorView AS SELECT * FROM author
""")
let association = Book.belongsTo(Table("authorView"), using: ForeignKey(["authorId"], to: ["id"]))
let authorAlias = TableAlias()
let request = Book
.joining(optional: association.aliased(authorAlias))
.filter(!authorAlias.exists)
try assertEqualSQL(db, request, """
SELECT "book".* FROM "book" \
LEFT JOIN "authorView" ON "authorView"."id" = "book"."authorId" \
WHERE "authorView"."id" IS NULL
""")
}
}
}
}
+23 -23
View File
@@ -6,38 +6,38 @@ class DatabaseCollationTests: GRDBTestCase {
func testDefaultCollations() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT)")
try db.execute(sql: "INSERT INTO strings VALUES (1, '1')")
try db.execute(sql: "INSERT INTO strings VALUES (2, '2')")
try db.execute(sql: "INSERT INTO strings VALUES (3, '10')")
try db.execute(sql: "INSERT INTO strings VALUES (4, 'a')")
try db.execute(sql: "INSERT INTO strings VALUES (5, 'à')")
try db.execute(sql: "INSERT INTO strings VALUES (6, 'A')")
try db.execute(sql: "INSERT INTO strings VALUES (7, 'Z')")
try db.execute(sql: "INSERT INTO strings VALUES (8, 'z')")
try db.execute(sql: """
CREATE TABLE strings (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO strings VALUES (1, '1');
INSERT INTO strings VALUES (2, '2');
INSERT INTO strings VALUES (3, '10');
INSERT INTO strings VALUES (4, 'a');
INSERT INTO strings VALUES (5, 'à');
INSERT INTO strings VALUES (6, 'A');
INSERT INTO strings VALUES (7, 'Z');
INSERT INTO strings VALUES (8, 'z');
INSERT INTO strings VALUES (9, '');
INSERT INTO strings VALUES (10, NULL);
INSERT INTO strings VALUES (11, x'42FF'); -- Invalid UTF8 "B�"
""")
// Swift 4.2 and Swift 4.1 don't sort strings in the same way
if "z" < "à" {
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,8,5])
} else {
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[1,3,2,6,7,4,5,8])
}
// Note that "B�" is always last. We can observe that SQLite
// does not invoke the collation for invalid UTF8 strings.
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"),
[10,9,1,3,2,6,7,4,8,5,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
[10,9,1,3,2,4,6,5,7,8,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCaseInsensitiveCompare.name), id"),
[1,3,2,4,6,5,7,8])
[10,9,1,3,2,4,6,5,7,8,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedCompare.name), id"),
[1,3,2,4,6,5,8,7])
[10,9,1,3,2,4,6,5,8,7,11])
XCTAssertEqual(
try Int.fetchAll(db, sql: "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.localizedStandardCompare.name), id"),
[1,2,3,4,6,5,8,7])
[10,9,1,2,3,4,6,5,8,7,11])
}
}
+69
View File
@@ -22,6 +22,11 @@ private struct Player: Codable, MutablePersistableRecord {
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
enum Columns {
static let name = Column(CodingKeys.name)
static let teamId = Column(CodingKeys.teamId)
}
}
private struct Team: Codable, PersistableRecord {
@@ -1141,6 +1146,70 @@ final class DatabaseDumpTests: GRDBTestCase {
}
}
func test_dumpTables_single_view_with_schema_source() throws {
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["teamId", "name"]
}
}
dbConfiguration.schemaSource = SchemaSource()
try makeRugbyDatabase().write { db in
try db.create(view: "playerName", as: Player
.orderByPrimaryKey()
.filter { $0.teamId != nil }
.select { [$0.teamId, $0.name] })
do {
// Default order: use the view ordering
do {
// Default format
let stream = TestStream()
try db.dumpTables(["playerName"], to: stream)
XCTAssertEqual(stream.output, """
FRA|Antoine Dupond
ENG|Owen Farrell
""")
}
do {
// Custom format
let stream = TestStream()
try db.dumpTables(["playerName"], format: .json(), to: stream)
XCTAssertEqual(stream.output, """
[{"teamId":"FRA","name":"Antoine Dupond"},
{"teamId":"ENG","name":"Owen Farrell"}]
""")
}
}
do {
// Stable order (primary key)
do {
// Default format
let stream = TestStream()
try db.dumpTables(["playerName"], stableOrder: true, to: stream)
XCTAssertEqual(stream.output, """
ENG|Owen Farrell
FRA|Antoine Dupond
""")
}
do {
// Custom format
let stream = TestStream()
try db.dumpTables(["playerName"], format: .json(), stableOrder: true, to: stream)
XCTAssertEqual(stream.output, """
[{"teamId":"ENG","name":"Owen Farrell"},
{"teamId":"FRA","name":"Antoine Dupond"}]
""")
}
}
}
}
func test_dumpTables_multiple() throws {
try makeRugbyDatabase().read { db in
do {
@@ -1109,4 +1109,61 @@ class DatabaseMigratorTests : GRDBTestCase {
XCTFail("Expected error")
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY { }
}
func test_schemaSource_is_disabled_during_migrations() throws {
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
var migrator = DatabaseMigrator()
do {
migrator.registerMigration("A") { db in
try db.execute(sql: "CREATE VIEW myView as SELECT 1 AS id")
// Cache is empty, and schemaSource is disabled.
XCTAssertNil(db.schemaSource)
XCTAssertThrowsError(try db.primaryKey("myView"))
}
try migrator.migrate(dbQueue)
}
try dbQueue.inDatabase { db in
// Cache was cleared, and schemaSource is active.
XCTAssertNotNil(db.schemaSource)
XCTAssertNoThrow(try db.primaryKey("myView"))
}
do {
migrator.registerMigration("B") { db in
// Cache was cleared again, and schemaSource is disabled.
XCTAssertNil(db.schemaSource)
XCTAssertThrowsError(try db.primaryKey("myView"))
}
try migrator.migrate(dbQueue)
}
}
func test_schemaSource_can_be_restored_during_migrations() throws {
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
var migrator = DatabaseMigrator()
migrator.registerMigration("A") { db in
try db.execute(sql: "CREATE VIEW myView as SELECT 1 AS id")
try db.withSchemaSource(SchemaSource()) {
XCTAssertNoThrow(try db.primaryKey("myView"))
}
}
try migrator.migrate(dbQueue)
}
}
+48
View File
@@ -677,4 +677,52 @@ class DatabaseReaderTests : GRDBTestCase {
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
// Regression test for https://github.com/groue/GRDB.swift/pull/1797
func test_cancellation_does_not_impact_other_tasks() async throws {
func test(_ dbReader: some DatabaseReader) async throws {
// Numbers that have the test fail more or less reliably
// (on my machine) unless the #1797 patch is applied.
let repeatCount = 30
let taskCount = 400
for _ in 0..<repeatCount {
try await withThrowingTaskGroup(of: Void.self) { group in
for i in 0..<taskCount{
let task = Task {
try await dbReader.read { db in
try db.execute(sql: "SELECT 1")
}
}
group.addTask {
if i.isMultiple(of: 2) {
Task {
// For the test to fail, we need to be lucky, here:
// Cancellation must occur after the database access
// has completed, but before `read` has returned. This
// triggers the failure of unrelated tasks because
// the database enters the cancelled state
// (fixed by #1797).
task.cancel()
}
// Ignore expected CancellationError
try? await task.value
} else {
// Unexpected CancellationError fails the test
try await task.value
}
}
}
try await group.waitForAll()
}
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(makeDatabasePool().makeSnapshot())
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
try await test(makeDatabasePool().makeSnapshotPool())
#endif
try await test(AnyDatabaseReader(makeDatabaseQueue()))
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
}
@@ -0,0 +1,100 @@
import XCTest
import GRDB
class DatabaseSchemaSourceTests: GRDBTestCase {
func test_schemaSource_can_query_schema() throws {
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
let tableName = view.name + "_table"
if try db.tableExists(view.name + "_table"),
try db.primaryKey(tableName).columns == ["id"],
try db.columns(in: view.name, in: view.schemaID.name).contains(where: { $0.name == "name" })
{
return ["id"]
} else {
return nil
}
}
}
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.execute(sql: """
-- Matches SchemaSource
CREATE TABLE view1_table(id INTEGER PRIMARY KEY, name TEXT);
CREATE VIEW view1 AS SELECT * FROM view1_table;
-- Does not match SchemaSource
CREATE VIEW view2 AS SELECT 1;
-- Does not match SchemaSource
CREATE TABLE view3_table(uuid TEXT PRIMARY KEY);
CREATE VIEW view3 AS SELECT * FROM view3_table;
-- Does not match SchemaSource
CREATE TABLE view4_table(id INTEGER PRIMARY KEY, name TEXT);
CREATE VIEW view4 AS SELECT id FROM view4_table;
""")
try XCTAssertEqual(db.primaryKey("view1").columns, ["id"])
XCTAssertThrowsError(try db.primaryKey("view2"))
XCTAssertThrowsError(try db.primaryKey("view3"))
XCTAssertThrowsError(try db.primaryKey("view4"))
}
}
func test_then_with_columnsForPrimaryKey_inView() throws {
struct SchemaSource1: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
switch view.name {
case "view1": ["code"]
case "view2": ["id"]
default: nil
}
}
}
struct SchemaSource2: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
switch view.name {
case "view1": ["identifier"]
case "view3": ["uuid"]
default: nil
}
}
}
func setupSchema(_ db: Database) throws {
try db.execute(sql: """
CREATE VIEW view1 AS SELECT 'foo' AS code, 'whatever' AS identifier;
CREATE VIEW view2 AS SELECT 1 AS id;
CREATE VIEW view3 AS SELECT 'foo' AS uuid;
""")
}
do {
let schemaSource = SchemaSource1().then(SchemaSource2())
dbConfiguration.schemaSource = schemaSource
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try setupSchema(db)
try XCTAssertEqual(db.primaryKey("view1").columns, ["code"])
try XCTAssertEqual(db.primaryKey("view2").columns, ["id"])
try XCTAssertEqual(db.primaryKey("view3").columns, ["uuid"])
}
}
do {
let schemaSource = SchemaSource2().then(SchemaSource1())
dbConfiguration.schemaSource = schemaSource
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try setupSchema(db)
try XCTAssertEqual(db.primaryKey("view1").columns, ["identifier"])
try XCTAssertEqual(db.primaryKey("view2").columns, ["id"])
try XCTAssertEqual(db.primaryKey("view3").columns, ["uuid"])
}
}
}
}
+4 -1
View File
@@ -70,7 +70,10 @@ class GRDBTestCase: XCTestCase {
var sqlQueries: [String] { _sqlQueriesMutex.load() }
// Automatically updated by default dbConfiguration
var lastSQLQuery: String? { sqlQueries.last }
var lastSQLQuery: String? {
// Skip comments that may be inserted by triggers and virtual tables.
sqlQueries.last { !$0.hasPrefix("--") }
}
override func setUp() {
super.setUp()
+28
View File
@@ -71,9 +71,37 @@ class IndexInfoTests: GRDBTestCase {
try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["year"]))
try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["personId"]))
try XCTAssertFalse(db.table("citizenships", hasUniqueKey: ["countryIsoCode"]))
try db.execute(sql: "CREATE VIEW personView AS SELECT * FROM persons")
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["rowid"]))
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["id"]))
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["email"]))
try XCTAssertFalse(db.table("personView", hasUniqueKey: []))
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["name"]))
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["id", "email"]))
}
}
func testColumnsThatUniquelyIdentityRows_with_view_and_schema_source() throws {
struct MySchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
dbConfiguration.schemaSource = MySchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
try db.execute(sql: "CREATE VIEW personView AS SELECT * FROM persons")
try XCTAssertTrue(db.table("personView", hasUniqueKey: ["id"]))
try XCTAssertFalse(db.table("personView", hasUniqueKey: []))
try XCTAssertFalse(db.table("personView", hasUniqueKey: ["name"]))
try XCTAssertTrue(db.table("personView", hasUniqueKey: ["id", "email"]))
}
}
// Regression test for https://github.com/groue/GRDB.swift/issues/840
func testIndexOnExpressionIsExcluded() throws {
let dbQueue = try makeDatabaseQueue()
+119 -2
View File
@@ -26,8 +26,12 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTFail("Expected Error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "no such table: items")
XCTAssertEqual(error.description, "SQLite error 1: no such table: items")
XCTAssertEqual(error.message, """
database view items has no primary key
""")
XCTAssertEqual(error.description, """
SQLite error 1: database view items has no primary key
""")
}
}
}
@@ -242,4 +246,117 @@ class PrimaryKeyInfoTests: GRDBTestCase {
XCTAssertTrue(primaryKey.tableHasRowID)
}
}
// MARK: - Customization with DatabaseSchemaSource
func test_custom_schemaSource_nil_result() throws {
struct MySchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
nil
}
}
dbConfiguration.schemaSource = MySchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player")
do {
let primaryKey = try db.primaryKey("player")
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)
}
do {
_ = try db.primaryKey("playerView")
XCTFail("Expected Error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, """
database view playerView has no primary key
""")
XCTAssertEqual(error.description, """
SQLite error 1: database view playerView has no primary key
""")
}
}
}
func test_custom_schemaSource_empty_result() throws {
struct MySchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
[]
}
}
dbConfiguration.schemaSource = MySchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player")
do {
let primaryKey = try db.primaryKey("player")
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)
}
do {
_ = try db.primaryKey("playerView")
XCTFail("Expected Error")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, """
database view playerView has no primary key
""")
XCTAssertEqual(error.description, """
SQLite error 1: database view playerView has no primary key
""")
}
}
}
func test_custom_schemaSource_custom_primary_key() throws {
struct MySchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["playerId"]
}
}
dbConfiguration.schemaSource = MySchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)")
try db.execute(sql: "CREATE VIEW playerView as SELECT id AS playerId, name FROM player")
do {
let primaryKey = try db.primaryKey("player")
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)
}
do {
let primaryKey = try db.primaryKey("playerView")
XCTAssertEqual(primaryKey.columnInfos?.map(\.name), ["playerId"])
XCTAssertEqual(primaryKey.columnInfos?.map(\.type), ["INTEGER"])
XCTAssertEqual(primaryKey.columns, ["playerId"])
XCTAssertNil(primaryKey.rowIDColumn)
XCTAssertFalse(primaryKey.isRowID)
XCTAssertFalse(primaryKey.tableHasRowID)
}
}
}
}
@@ -0,0 +1,386 @@
import XCTest
import GRDB
#warning("TODO: document the caveat that didInsert(with:) is unreliable due to last insert rowid not set by triggers: https://sqlite.org/c3ref/last_insert_rowid.html. See also https://sqlite.org/forum/forumpost/fb1c3b4a13")
private struct Player: Codable,
Equatable,
Identifiable,
FetchableRecord,
PersistableRecord
{
var id: String
var name: String
var teamId: String?
var isCaptain: Bool
}
private struct Team: Codable,
Equatable,
Identifiable,
FetchableRecord,
PersistableRecord
{
var id: String
var name: String
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
}
private struct Captain: Codable,
Equatable,
Identifiable,
FetchableRecord,
PersistableRecord
{
var id: String
var name: String
var teamId: String
enum Columns {
static let teamId = Column(CodingKeys.teamId)
}
static let teamForeignKey = ForeignKey([Columns.teamId])
static let team = belongsTo(Team.self, using: teamForeignKey)
}
private struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
if view.name == "captain" {
return ["id"]
} else {
// Do not customize
return nil
}
}
}
class RecordMappedOnMutableViewTests : GRDBTestCase {
private lazy var migrator: DatabaseMigrator = {
var migrator = DatabaseMigrator()
migrator.registerMigration("Teams and players") { db in
try db.create(table: "team") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.belongsTo("team", onDelete: .setNull)
t.column("isCaptain", .boolean).notNull()
}
// One unique captain per team
try db.create(
indexOn: "player", columns: ["teamId"],
options: .unique,
condition: Column("isCaptain"))
}
migrator.registerMigration("Read-only captains") { db in
try db.execute(sql: """
CREATE VIEW captain AS
SELECT id, name, teamId
FROM player
WHERE isCaptain AND teamId IS NOT NULL;
""")
}
migrator.registerMigration("Captain CRUD") { db in
try db.execute(sql: """
-- Insert trigger
CREATE TRIGGER captain_insert
INSTEAD OF INSERT ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain;
-- Insert new captain
INSERT INTO player(id, name, teamId, isCaptain)
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
END;
-- Update trigger
CREATE TRIGGER captain_update
INSTEAD OF UPDATE ON captain
BEGIN
-- Remove previous captain
UPDATE player SET isCaptain = 0
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
-- Update captain
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
WHERE id = NEW.id;
END;
-- Delete trigger
CREATE TRIGGER captain_delete
INSTEAD OF DELETE ON captain
BEGIN
DELETE FROM player WHERE id = OLD.id;
END;
""")
}
return migrator
}()
func test_read_only() throws {
// No schema source, no CRUD
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue, upTo: "Read-only captains")
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.fetchAll(db)
XCTAssertEqual(captains.count, 2)
XCTAssert(captains.contains(Captain(id: "alice", name: "Alice", teamId: "red")))
XCTAssert(captains.contains(Captain(id: "bob", name: "Bob", teamId: "blue")))
}
}
func test_read_only_primary_key() throws {
// No CRUD
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue, upTo: "Read-only captains")
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
XCTAssertEqual(captains, [
Captain(id: "alice", name: "Alice", teamId: "red"),
Captain(id: "bob", name: "Bob", teamId: "blue"),
])
let alice = try Captain.find(db, id: "alice")
XCTAssertEqual(alice, Captain(id: "alice", name: "Alice", teamId: "red"))
try db.dumpTables(["team", "player", "captain"])
}
}
func test_CRUD() throws {
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
let red = Team(id: "red", name: "Red")
try red.insert(db)
let blue = Team(id: "blue", name: "Blue")
try blue.insert(db)
// Insert in view
let alice = Captain(id: "alice", name: "Alice", teamId: red.id)
try alice.insert(db)
var bob = Captain(id: "bob", name: "Bob", teamId: blue.id)
try bob.insert(db)
do {
try XCTAssertEqual(
Player.find(db, id: "bob"),
Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true))
}
// Update in view
let modified = try bob.updateChanges(db) {
$0.name = "Bobby"
$0.teamId = red.id
}
XCTAssertTrue(modified)
do {
// Bob is captain of reds.
try XCTAssertEqual(
Player.find(db, id: "bob"),
Player(id: "bob", name: "Bobby", teamId: "red", isCaptain: true))
// Alice is no longer captain.
try XCTAssertEqual(
Player.find(db, id: "alice"),
Player(id: "alice", name: "Alice", teamId: "red", isCaptain: false))
}
// Insert in view and replace caption
let craig = Captain(id: "craig", name: "Craig", teamId: "red")
try craig.insert(db)
do {
// Craig is captain of reds.
try XCTAssertEqual(
Player.find(db, id: "craig"),
Player(id: "craig", name: "Craig", teamId: "red", isCaptain: true))
// Bob is no longer captain.
try XCTAssertEqual(
Player.find(db, id: "bob"),
Player(id: "bob", name: "Bobby", teamId: "red", isCaptain: false))
}
// Delete in view
let deleted = try craig.delete(db)
XCTAssertTrue(deleted)
do {
try XCTAssertNil(Player.fetchOne(db, id: "craig"))
}
}
}
func test_fetch_by_primary_key() throws {
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
try XCTAssertEqual(
Captain.fetchOne(db, key: "alice"),
Captain(id: "alice", name: "Alice", teamId: "red"))
try XCTAssertEqual(
Captain.fetchOne(db, key: ["id": "alice"]),
Captain(id: "alice", name: "Alice", teamId: "red"))
try XCTAssertEqual(
Captain.fetchOne(db, id: "alice"),
Captain(id: "alice", name: "Alice", teamId: "red"))
try XCTAssertEqual(
Captain.find(db, id: "alice"),
Captain(id: "alice", name: "Alice", teamId: "red"))
}
}
func test_stable_order() throws {
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
let request = Captain.all().withStableOrder()
try assertEqualSQL(db, request, "SELECT * FROM \"captain\" ORDER BY \"id\"")
}
}
func test_team_has_one_captain_request() throws {
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
let red = Team(id: "red", name: "Red")
try red.insert(db)
let blue = Team(id: "blue", name: "Blue")
try blue.insert(db)
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
do {
let captain = try red.request(for: Team.captain).fetchOne(db)
// This LIMIT 1 can't be removed until we know that teamId
// is a unique key on the captain view.
//
// We considered using the teamId as the primary key for
// captains, but when a captain does not know its player id:
//
// - Conversion between Player and Captain is uneasy
// - We can't insert a captain because the player id is not
// auto-incremented (no sqlite3_last_insert_rowid
// from triggers)
XCTAssertEqual(lastSQLQuery, """
SELECT * FROM "captain" WHERE "teamId" = 'red' LIMIT 1
""")
XCTAssertEqual(captain, Captain(id: "alice", name: "Alice", teamId: "red"))
}
do {
struct TeamWithCaptain: Decodable, Equatable, FetchableRecord {
var team: Team
var captain: Captain?
}
let teamsWithCaptain = try Team
.including(optional: Team.captain)
.asRequest(of: TeamWithCaptain.self)
.orderByPrimaryKey()
.fetchAll(db)
XCTAssertEqual(lastSQLQuery, """
SELECT "team".*, "captain".* \
FROM "team" \
LEFT JOIN "captain" ON "captain"."teamId" = "team"."id" \
ORDER BY "team"."id"
""")
XCTAssertEqual(teamsWithCaptain, [
TeamWithCaptain(
team: Team(id: "blue", name: "Blue"),
captain: nil),
TeamWithCaptain(
team: Team(id: "red", name: "Red"),
captain: Captain(id: "alice", name: "Alice", teamId: "red")),
])
}
}
}
func test_captain_belongs_to_team_request() throws {
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try migrator.migrate(dbQueue)
try dbQueue.write { db in
try Team(id: "red", name: "Red").insert(db)
try Team(id: "blue", name: "Blue").insert(db)
let alice = Captain(id: "alice", name: "Alice", teamId: "red")
try alice.insert(db)
try Captain(id: "bob", name: "Bob", teamId: "blue").insert(db)
do {
let team = try alice.request(for: Captain.team).fetchOne(db)
XCTAssertEqual(lastSQLQuery, """
SELECT * FROM "team" WHERE "id" = 'red'
""")
XCTAssertEqual(team, Team(id: "red", name: "Red"))
}
do {
struct CaptainWithTeam: Decodable, Equatable, FetchableRecord {
var captain: Captain
var team: Team
}
let captainsWithTeam = try Captain
.including(required: Captain.team)
.asRequest(of: CaptainWithTeam.self)
.orderByPrimaryKey()
.fetchAll(db)
XCTAssertEqual(lastSQLQuery, """
SELECT "captain".*, "team".* \
FROM "captain" \
JOIN "team" ON "team"."id" = "captain"."teamId" \
ORDER BY "captain"."id"
""")
XCTAssertEqual(captainsWithTeam, [
CaptainWithTeam(
captain: Captain(id: "alice", name: "Alice", teamId: "red"),
team: Team(id: "red", name: "Red")),
CaptainWithTeam(
captain: Captain(id: "bob", name: "Bob", teamId: "blue"),
team: Team(id: "blue", name: "Blue")),
])
}
}
}
}
+395 -17
View File
@@ -1,6 +1,7 @@
import XCTest
import GRDB
// Table records
private struct Hacker : TableRecord {
static let databaseTableName = "hackers"
var id: Int64? // Optional
@@ -26,6 +27,40 @@ private struct Citizenship : TableRecord {
static let databaseTableName = "citizenships"
}
// View records
private struct PersonView : Codable, PersistableRecord, FetchableRecord, Hashable {
static let databaseTableName = "personsView"
var id: Int64 // Non-optional
var name: String
var email: String
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
}
}
extension PersonView: Identifiable { }
private struct CitizenshipView : TableRecord {
static let databaseTableName = "citizenshipsView"
}
// Schema source
private struct ViewSchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
switch view.name {
case "personsView":
return ["id"]
case "citizenshipsView":
return ["personId", "countryIsoCode"]
default:
return nil
}
}
}
class TableRecordDeleteTests: GRDBTestCase {
@@ -34,6 +69,40 @@ class TableRecordDeleteTests: GRDBTestCase {
try db.execute(sql: "CREATE TABLE hackers (name TEXT)")
try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)")
try db.execute(sql: "CREATE TABLE citizenships (personId INTEGER NOT NULL, countryIsoCode TEXT NOT NULL, PRIMARY KEY (personId, countryIsoCode))")
// mutable views
try db.execute(sql: """
CREATE VIEW personsView AS SELECT * FROM persons;
-- Insert trigger
CREATE TRIGGER personsView_insert
INSTEAD OF INSERT ON personsView
BEGIN
INSERT INTO persons (id, name, email)
VALUES (NEW.id, NEW.name, NEW.email);
END;
-- Delete trigger
CREATE TRIGGER personsView_delete
INSTEAD OF DELETE ON personsView
BEGIN
DELETE FROM persons WHERE id = OLD.id;
END;
""")
try db.execute(sql: """
CREATE VIEW citizenshipsView AS SELECT * FROM citizenships;
-- Insert trigger
CREATE TRIGGER citizenshipsView_insert
INSTEAD OF INSERT ON citizenshipsView
BEGIN
INSERT INTO citizenships (personId, countryIsoCode)
VALUES (NEW.personId, NEW.countryIsoCode);
END;
-- Delete trigger
CREATE TRIGGER citizenshipsView_delete
INSTEAD OF DELETE ON citizenshipsView
BEGIN
DELETE FROM citizenships WHERE personId = OLD.personId AND countryIsoCode = OLD.countryIsoCode;
END;
""")
}
}
@@ -76,7 +145,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testSingleColumnPrimaryKey() throws {
func testSingleColumnPrimaryKey_table() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: 1)
@@ -114,7 +183,48 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testMultipleColumnPrimaryKey() throws {
func testSingleColumnPrimaryKey_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try PersonView.deleteOne(db, key: 1)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1")
XCTAssertFalse(deleted)
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try PersonView.deleteOne(db, key: 1)
XCTAssertTrue(deleted)
XCTAssertEqual(try PersonView.fetchCount(db), 0)
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try PersonView.deleteOne(db, id: 1)
XCTAssertTrue(deleted)
XCTAssertEqual(try PersonView.fetchCount(db), 0)
do {
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try PersonView.deleteAll(db, keys: [2, 3, 4])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (2, 3, 4)")
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try PersonView.fetchCount(db), 1)
}
do {
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try PersonView.deleteAll(db, ids: [2, 3, 4])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (2, 3, 4)")
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try PersonView.fetchCount(db), 1)
}
}
}
func testMultipleColumnPrimaryKey_table() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Citizenship.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
@@ -135,6 +245,30 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testMultipleColumnPrimaryKey_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try CitizenshipView.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"citizenshipsView\" WHERE (\"personId\" = 1) AND (\"countryIsoCode\" = 'FR')")
XCTAssertFalse(deleted)
try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"])
deleted = try CitizenshipView.deleteOne(db, key: ["personId": 1, "countryIsoCode": "FR"])
XCTAssertTrue(deleted)
XCTAssertEqual(try CitizenshipView.fetchCount(db), 0)
try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "FR"])
try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [1, "US"])
try db.execute(sql: "INSERT INTO citizenshipsView (personId, countryIsoCode) VALUES (?, ?)", arguments: [2, "US"])
let deletedCount = try CitizenshipView.deleteAll(db, keys: [["personId": 1, "countryIsoCode": "FR"], ["personId": 1, "countryIsoCode": "US"], ["personId": 1, "countryIsoCode": "DE"]])
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try CitizenshipView.fetchCount(db), 1)
}
}
func testUniqueIndex() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -156,7 +290,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testImplicitUniqueIndexOnSingleColumnPrimaryKey() throws {
func testImplicitUniqueIndexOnSingleColumnPrimaryKey_table() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try Person.deleteOne(db, key: ["id": 1])
@@ -177,7 +311,31 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAll() throws {
func testImplicitUniqueIndexOnSingleColumnPrimaryKey_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
var deleted = try PersonView.deleteOne(db, key: ["id": 1])
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1")
XCTAssertFalse(deleted)
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
deleted = try PersonView.deleteOne(db, key: ["id": 1])
XCTAssertTrue(deleted)
XCTAssertEqual(try PersonView.fetchCount(db), 0)
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"])
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"])
try db.execute(sql: "INSERT INTO personsView (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"])
let deletedCount = try PersonView.deleteAll(db, keys: [["id": 2], ["id": 3], ["id": 4]])
XCTAssertEqual(deletedCount, 2)
XCTAssertEqual(try PersonView.fetchCount(db), 1)
}
}
func testRequestDeleteAll_table() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -230,7 +388,63 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchStatement() throws {
func testRequestDeleteAll_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try PersonView.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"")
try PersonView.filter { $0.name == "Arthur" }.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"name\" = 'Arthur'")
try PersonView.filter(key: 1).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1")
try PersonView.filter(keys: [1, 2]).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2)")
try PersonView.filter(id: 1).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1")
try PersonView.filter(ids: [1, 2]).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2)")
try PersonView.filter(sql: "id = 1").deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE id = 1")
try PersonView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE (id = 1) AND (\"name\" = 'Arthur')")
try PersonView.select { $0.name }.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"")
try PersonView.order { $0.name }.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"")
if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") {
try PersonView.limit(1).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" LIMIT 1")
try PersonView.order { $0.name }.deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\"")
try PersonView.order { $0.name }.limit(1).deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" ORDER BY \"name\" LIMIT 1")
try PersonView.order { $0.name }.limit(1, offset: 2).reversed().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2")
try PersonView.limit(1, offset: 2).reversed().deleteAll(db)
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" LIMIT 1 OFFSET 2")
}
}
}
func testRequestDeleteAndFetchStatement_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -264,7 +478,41 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchCursor() throws {
func testRequestDeleteAndFetchStatement_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let request = PersonView.all()
let statement = try request.deleteAndFetchStatement(db, select: { [$0.name] })
XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING \"name\"")
XCTAssertEqual(statement.columnNames, ["name"])
}
do {
let request = PersonView.all()
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING *")
XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
}
do {
let request = PersonView.all()
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns(excluding: ["name"])])
XCTAssertEqual(statement.sql, "DELETE FROM \"personsView\" RETURNING \"id\", \"email\"")
XCTAssertEqual(statement.columnNames, ["id", "email"])
}
}
}
func testRequestDeleteAndFetchCursor_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -293,19 +541,11 @@ class TableRecordDeleteTests: GRDBTestCase {
_ = try Person.filter(keys: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
#if GRDBCUSTOMSQLITE || GRDBCIPHER
_ = try Person.filter(id: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
_ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
#else
_ = try Person.filter(id: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *")
_ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *")
#endif
_ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *")
@@ -323,7 +563,60 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchArray() throws {
func testRequestDeleteAndFetchCursor_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
_ = try PersonView.all().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *")
_ = try PersonView.all().deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *")
_ = try PersonView.filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"name\" = 'Arthur' RETURNING *")
_ = try PersonView.filter(key: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1 RETURNING *")
_ = try PersonView.filter(keys: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2) RETURNING *")
_ = try PersonView.filter(id: 1).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" = 1 RETURNING *")
_ = try PersonView.filter(ids: [1, 2]).deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE \"id\" IN (1, 2) RETURNING *")
_ = try PersonView.filter(sql: "id = 1").deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE id = 1 RETURNING *")
_ = try PersonView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" WHERE (id = 1) AND (\"name\" = 'Arthur') RETURNING *")
_ = try PersonView.select { $0.name }.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *")
_ = try PersonView.order { $0.name }.deleteAndFetchCursor(db).next()
XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"personsView\" RETURNING *")
// No test for LIMIT ... RETURNING ... since this is not supported by SQLite
}
}
func testRequestDeleteAndFetchArray_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -351,7 +644,37 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchSet() throws {
func testRequestDeleteAndFetchArray_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db)
let request = PersonView.filter { $0.id != 2 }
let deletePersons = try request
.deleteAndFetchAll(db)
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(deletePersons, [
PersonView(id: 1, name: "Arthur", email: "arthur@example.com"),
PersonView(id: 3, name: "Craig", email: "craig@example.com"),
])
}
}
func testRequestDeleteAndFetchSet_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -377,7 +700,35 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchIds() throws {
func testRequestDeleteAndFetchSet_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db)
let request = PersonView.filter { $0.id != 2 }
let deletePersons = try request.deleteAndFetchSet(db)
XCTAssertEqual(deletePersons, [
PersonView(id: 1, name: "Arthur", email: "arthur@example.com"),
PersonView(id: 3, name: "Craig", email: "craig@example.com"),
])
}
}
func testRequestDeleteAndFetchIds_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -400,6 +751,32 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
func testRequestDeleteAndFetchIds_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try PersonView(id: 1, name: "Arthur", email: "arthur@example.com").insert(db)
try PersonView(id: 2, name: "Barbara", email: "barbara@example.com").insert(db)
try PersonView(id: 3, name: "Craig", email: "craig@example.com").insert(db)
let request = PersonView.filter { $0.id != 2 }
let deletedIds = try request.deleteAndFetchIds(db)
XCTAssertEqual(deletedIds, [1, 3])
}
}
// TODO: duplicate test with views?
func testJoinedRequestDeleteAll() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
@@ -460,6 +837,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
}
// TODO: duplicate test with views?
func testJoinedRequestDeleteAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
+450 -10
View File
@@ -1,7 +1,7 @@
import XCTest
import GRDB
private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable {
private struct Player: Codable, Identifiable, PersistableRecord, FetchableRecord, Hashable {
var id: Int64
var name: String
var score: Int
@@ -24,7 +24,45 @@ private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable {
}
}
extension Player: Identifiable { }
private struct PlayerView: Codable, Identifiable, PersistableRecord, FetchableRecord, Hashable {
var id: Int64
var name: String
var score: Int
var bonus: Int
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
static let bonus = Column(CodingKeys.bonus)
}
static func createTable(_ db: Database) throws {
try db.execute(sql: """
CREATE VIEW playerView AS SELECT * FROM player;
-- Insert trigger
CREATE TRIGGER playerView_insert
INSTEAD OF INSERT ON playerView
BEGIN
INSERT INTO player (id, name, score, bonus)
VALUES (NEW.id, NEW.name, NEW.score, NEW.bonus);
END;
-- Update trigger
CREATE TRIGGER playerView_update
INSTEAD OF UPDATE ON playerView
BEGIN
UPDATE player SET name = NEW.name, score = NEW.score, bonus = NEW.bonus
WHERE id = OLD.id;
END;
""")
}
}
private struct ViewSchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
private typealias Columns = Player.Columns
@@ -35,7 +73,7 @@ private extension QueryInterfaceRequest<Player> {
}
class TableRecordUpdateTests: GRDBTestCase {
func testRequestUpdateAll() throws {
func testRequestUpdateAll_table() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
@@ -119,7 +157,95 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAll_DatabaseComponents() throws {
func testRequestUpdateAll_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
let assignment = Columns.score.set(to: 0)
try PlayerView.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.filter { $0.name == "Arthur" }.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE \"name\" = 'Arthur'
""")
try PlayerView.filter(key: 1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" = 1
""")
try PlayerView.filter(keys: [1, 2]).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2)
""")
try PlayerView.filter(id: 1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" = 1
""")
try PlayerView.filter(ids: [1, 2]).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2)
""")
try PlayerView.filter(sql: "id = 1").updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE id = 1
""")
try PlayerView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur')
""")
try PlayerView.select { $0.name }.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.order { $0.name }.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") {
try PlayerView.limit(1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 LIMIT 1
""")
try PlayerView.order { $0.name }.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.order { $0.name }.limit(1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" LIMIT 1
""")
try PlayerView.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2
""")
try PlayerView.limit(1, offset: 2).reversed().updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 LIMIT 1 OFFSET 2
""")
}
}
}
func testRequestUpdateAll_DatabaseComponents_table() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
@@ -202,7 +328,94 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchStatement() throws {
func testRequestUpdateAll_DatabaseComponents_view() throws {
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
try PlayerView.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE \"name\" = 'Arthur'
""")
try PlayerView.filter(key: 1).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" = 1
""")
try PlayerView.filter(keys: [1, 2]).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2)
""")
try PlayerView.filter(id: 1).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" = 1
""")
try PlayerView.filter(ids: [1, 2]).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE "id" IN (1, 2)
""")
try PlayerView.filter(sql: "id = 1").updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE id = 1
""")
try PlayerView.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur')
""")
try PlayerView.select { $0.name }.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.order { $0.name }.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") {
try PlayerView.limit(1).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 LIMIT 1
""")
try PlayerView.order { $0.name }.updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0
""")
try PlayerView.order { $0.name }.limit(1).updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" LIMIT 1
""")
try PlayerView.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2
""")
try PlayerView.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) }
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "playerView" SET "score" = 0 LIMIT 1 OFFSET 2
""")
}
}
}
func testRequestUpdateAndFetchStatement_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -241,7 +454,46 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchStatement_DatabaseComponents() throws {
func testRequestUpdateAndFetchStatement_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
let assignment = Columns.score.set(to: 0)
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [Column("score")])
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"score\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["score"])
}
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns])
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns(excluding: ["name"])])
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"])
}
}
}
func testRequestUpdateAndFetchStatement_DatabaseComponents_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -279,7 +531,46 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchCursor() throws {
func testRequestUpdateAndFetchStatement_DatabaseComponents_view() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { [$0.score] }
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"score\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["score"])
}
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns] }
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
do {
let request = PlayerView.all()
let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns(excluding: ["name"])] }
XCTAssertEqual(statement.sql, "UPDATE \"playerView\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"])
}
}
}
func testRequestUpdateAndFetchCursor_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -306,7 +597,47 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchCursor_DatabaseComponents() throws {
func testRequestUpdateAndFetchCursor_view() throws {
#warning("TODO: document this caveat")
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
// that was fixed in SQLite 3.42. The SQLite test linked below
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
// (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2)
// <https://sqlite.org/src/artifact/db532cde>
guard Database.sqliteLibVersionNumber >= 3042000 else {
throw XCTSkip("RETURNING and INSTEAD OF are buggy")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
// Fail in iOS 15.5 (SQLite 3.37)
// Fail in iOS 16.4 (SQLite 3.39)
// Fail in iOS 17.0 (SQLite 3.39)
// Passes in iOS 17.2 (SQLite 3.43)
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = PlayerView.filter { $0.id != 2 }
let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100])
let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0),
PlayerView(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchCursor_DatabaseComponents_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -333,7 +664,42 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchAll() throws {
func testRequestUpdateAndFetchCursor_DatabaseComponents_view() throws {
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
// that was fixed in SQLite 3.42. The SQLite test linked below
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
// (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2)
// <https://sqlite.org/src/artifact/db532cde>
guard Database.sqliteLibVersionNumber >= 3042000 else {
throw XCTSkip("RETURNING and INSTEAD OF are buggy")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = PlayerView.filter { $0.id != 2 }
let cursor = try request.updateAndFetchCursor(db) { [$0.score += 100] }
let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0),
PlayerView(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchAll_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -361,7 +727,43 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchAll_DatabaseComponents() throws {
func testRequestUpdateAndFetchAll_view() throws {
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
// that was fixed in SQLite 3.42. The SQLite test linked below
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
// (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2)
// <https://sqlite.org/src/artifact/db532cde>
guard Database.sqliteLibVersionNumber >= 3042000 else {
throw XCTSkip("RETURNING and INSTEAD OF are buggy")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = PlayerView.filter { $0.id != 2 }
let updatedPlayers = try request
.updateAndFetchAll(db, [Columns.score += 100])
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0),
PlayerView(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchAll_DatabaseComponents_table() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -389,6 +791,42 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
func testRequestUpdateAndFetchAll_DatabaseComponents_view() throws {
// Mixing INSTEAD OF triggers and RETURNING used to trigger a bug
// that was fixed in SQLite 3.42. The SQLite test linked below
// landed on 2023-03-28, and SQLite 3.42 shipped on 2023-05-16.
// (iOS 17.2, macOS 14.2, tvOS 17.2, watchOS 10.2)
// <https://sqlite.org/src/artifact/db532cde>
guard Database.sqliteLibVersionNumber >= 3042000 else {
throw XCTSkip("RETURNING and INSTEAD OF are buggy")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
// Views need a schema source
dbConfiguration.schemaSource = ViewSchemaSource()
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try PlayerView.createTable(db)
try PlayerView(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try PlayerView(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try PlayerView(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = PlayerView.filter { $0.id != 2 }
let updatedPlayers = try request
.updateAndFetchAll(db) { [$0.score += 100] }
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
PlayerView(id: 1, name: "Arthur", score: 110, bonus: 0),
PlayerView(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchSet() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 3035000 else {
@@ -1242,6 +1680,7 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
// TODO: duplicate test with views?
func testJoinedRequestUpdate() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
@@ -1314,6 +1753,7 @@ class TableRecordUpdateTests: GRDBTestCase {
}
}
// TODO: duplicate test with views?
func testJoinedRequestUpdate_DatabaseComponents() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1400"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"