From 4f8f0e0bf39ac20e9b6def62665fe20596ba43c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 11:31:47 +0100 Subject: [PATCH 001/348] Fix Xcode9.3 warnings --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 163 ++-------------- .../xcschemes/GRDBDemoWatchOS.xcscheme | 2 +- .../xcschemes/GRDBDemoiOS.xcscheme | 2 +- GRDB.xcodeproj/project.pbxproj | 30 ++- .../xcshareddata/xcschemes/GRDBOSX.xcscheme | 6 +- ...GRDBOSXPerformanceComparisonTests.xcscheme | 4 +- .../GRDBOSXPerformanceTests.xcscheme | 4 +- .../xcschemes/GRDBWatchOS.xcscheme | 2 +- .../xcshareddata/xcschemes/GRDBiOS.xcscheme | 6 +- GRDBCipher.xcodeproj/project.pbxproj | 25 ++- .../xcschemes/GRDBCipherOSX.xcscheme | 4 +- .../xcschemes/GRDBCipheriOS.xcscheme | 4 +- GRDBCustom.xcodeproj/project.pbxproj | 19 +- .../xcschemes/GRDBCustomSQLiteOSX.xcscheme | 13 +- .../xcschemes/GRDBCustomSQLiteiOS.xcscheme | 8 +- .../GRDBProfiling.xcodeproj/project.pbxproj | 174 +++--------------- 16 files changed, 132 insertions(+), 334 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index c4acc4319..4ae785152 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -94,41 +94,6 @@ remoteGlobalIDString = 56553C181C3E906C00522B5C; remoteInfo = GRDBOSXCrashTests; }; - 56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 560FC54D1CB003810014AA8E; - remoteInfo = GRDBCipherOSX; - }; - 56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 560FC5B01CB00B880014AA8E; - remoteInfo = GRDBCipherOSXTests; - }; - 56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 5671566C1CB16729007DC145; - remoteInfo = GRDBCipherOSXEncryptedTests; - }; - 56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA; - remoteInfo = GRDBCustomSQLiteOSX; - }; - 56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA; - remoteInfo = GRDBCustomSQLiteOSXTests; - }; 56B0364C1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; @@ -143,41 +108,6 @@ remoteGlobalIDString = 56E5D7D31B4D3FEE00430942; remoteInfo = GRDBiOSTests; }; - 56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96; - remoteInfo = GRDBCipheriOS; - }; - 56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96; - remoteInfo = GRDBCipheriOSTests; - }; - 56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96; - remoteInfo = GRDBCipheriOSEncryptedTests; - }; - 56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA; - remoteInfo = GRDBCustomSQLiteiOS; - }; - 56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA; - remoteInfo = GRDBCustomSQLiteiOSTests; - }; 56B0365A1E8D9F79003B6DA4 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; @@ -369,18 +299,8 @@ 56B0363F1E8D9F79003B6DA4 /* GRDBOSXPerformanceTests.xctest */, 563BD2F11F8364C1006A5390 /* GRDBOSXPerformanceComparisonTests.xctest */, 56B036411E8D9F79003B6DA4 /* GRDBOSXCrashTests.xctest */, - 56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */, - 56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */, - 56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */, - 56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */, - 56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */, 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */, 56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */, - 56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */, - 56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */, - 56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */, - 56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */, - 56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */, 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */, ); name = Products; @@ -455,7 +375,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0830; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 568E5FBE1E926430002582E0 = { @@ -537,41 +457,6 @@ remoteRef = 56B036401E8D9F79003B6DA4 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B036431E8D9F79003B6DA4 /* GRDBCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCipher.framework; - remoteRef = 56B036421E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036451E8D9F79003B6DA4 /* GRDBCipherOSXTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipherOSXTests.xctest; - remoteRef = 56B036441E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036471E8D9F79003B6DA4 /* GRDBCipherOSXEncryptedTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipherOSXEncryptedTests.xctest; - remoteRef = 56B036461E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036491E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCustomSQLite.framework; - remoteRef = 56B036481E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B0364B1E8D9F79003B6DA4 /* GRDBCustomSQLiteOSXTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCustomSQLiteOSXTests.xctest; - remoteRef = 56B0364A1E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -586,41 +471,6 @@ remoteRef = 56B0364E1E8D9F79003B6DA4 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B036511E8D9F79003B6DA4 /* GRDBCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCipher.framework; - remoteRef = 56B036501E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036531E8D9F79003B6DA4 /* GRDBCipheriOSTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipheriOSTests.xctest; - remoteRef = 56B036521E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036551E8D9F79003B6DA4 /* GRDBCipheriOSEncryptedTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipheriOSEncryptedTests.xctest; - remoteRef = 56B036541E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036571E8D9F79003B6DA4 /* GRDBCustomSQLite.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCustomSQLite.framework; - remoteRef = 56B036561E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56B036591E8D9F79003B6DA4 /* GRDBCustomSQLiteiOSTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCustomSQLiteiOSTests.xctest; - remoteRef = 56B036581E8D9F79003B6DA4 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -751,6 +601,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; @@ -767,6 +618,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; @@ -784,6 +636,7 @@ buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; IBSC_MODULE = GRDBDemoWatchOS_Extension; INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist; @@ -801,6 +654,7 @@ buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; IBSC_MODULE = GRDBDemoWatchOS_Extension; INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist; @@ -827,6 +681,7 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; @@ -834,6 +689,7 @@ CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -883,6 +739,7 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; CLANG_WARN_EMPTY_BODY = YES; @@ -890,6 +747,7 @@ CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -912,6 +770,7 @@ GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; @@ -923,6 +782,7 @@ buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = GRDBDemoiOS/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; @@ -936,6 +796,7 @@ buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; DEVELOPMENT_TEAM = AMD8W895CT; INFOPLIST_FILE = GRDBDemoiOS/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index 70ba69fe8..16013f9a2 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -1,6 +1,6 @@ + codeCoverageEnabled = "YES" + shouldUseLaunchSchemeArgsEnv = "YES"> diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme index dc203d353..fc3be5e0e 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceComparisonTests.xcscheme @@ -1,6 +1,6 @@ + codeCoverageEnabled = "YES" + shouldUseLaunchSchemeArgsEnv = "YES"> diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 97c210416..5c5a9aa79 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -1879,7 +1879,7 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 560FC5191CB003810014AA8E = { @@ -2810,6 +2810,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; @@ -2830,6 +2831,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; COMBINE_HIDPI_IMAGES = YES; DEFINES_MODULE = YES; @@ -2839,6 +2841,7 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2847,6 +2850,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; @@ -2863,6 +2867,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -2873,6 +2878,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2881,6 +2887,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; @@ -2897,6 +2904,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -2907,6 +2915,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2918,6 +2927,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; DEBUG_INFORMATION_FORMAT = dwarf; @@ -2942,6 +2952,7 @@ APPLICATION_EXTENSION_API_ONLY = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN_DOCUMENTATION_COMMENTS = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; COPY_PHASE_STRIP = NO; @@ -2955,6 +2966,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -2964,6 +2976,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; @@ -2980,6 +2993,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -2990,6 +3004,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2998,6 +3013,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; DEBUG_INFORMATION_FORMAT = dwarf; GCC_NO_COMMON_BLOCKS = YES; @@ -3014,6 +3030,7 @@ isa = XCBuildConfiguration; baseConfigurationReference = 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */; buildSettings = { + CLANG_ENABLE_OBJC_WEAK = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; @@ -3024,6 +3041,7 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSEncryptedTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3040,12 +3058,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -3093,12 +3113,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -3119,6 +3141,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/GRDBCipher.xcodeproj/xcshareddata/xcschemes/GRDBCipherOSX.xcscheme b/GRDBCipher.xcodeproj/xcshareddata/xcschemes/GRDBCipherOSX.xcscheme index 6ab046b60..1586943d3 100644 --- a/GRDBCipher.xcodeproj/xcshareddata/xcschemes/GRDBCipherOSX.xcscheme +++ b/GRDBCipher.xcodeproj/xcshareddata/xcschemes/GRDBCipherOSX.xcscheme @@ -1,6 +1,6 @@ + + + + diff --git a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme index 7a6690b89..0a3a1bb1c 100644 --- a/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme +++ b/GRDBCustom.xcodeproj/xcshareddata/xcschemes/GRDBCustomSQLiteiOS.xcscheme @@ -1,6 +1,6 @@ + codeCoverageEnabled = "YES" + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -71,7 +70,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - language = "" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj index 7400ab318..f67b4bf18 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj @@ -45,41 +45,6 @@ remoteGlobalIDString = 56553C181C3E906C00522B5C; remoteInfo = GRDBOSXCrashTests; }; - 564C5B6F1F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 560FC54D1CB003810014AA8E; - remoteInfo = GRDBCipherOSX; - }; - 564C5B711F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 560FC5B01CB00B880014AA8E; - remoteInfo = GRDBCipherOSXTests; - }; - 564C5B731F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 5671566C1CB16729007DC145; - remoteInfo = GRDBCipherOSXEncryptedTests; - }; - 564C5B751F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA805A1CFB2BB2003DC1BA; - remoteInfo = GRDBCustomSQLiteOSX; - }; - 564C5B771F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA809B1CFB2F6F003DC1BA; - remoteInfo = GRDBCustomSQLiteOSXTests; - }; 564C5B791F489B8A00176870 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; @@ -94,41 +59,6 @@ remoteGlobalIDString = 56E5D7D31B4D3FEE00430942; remoteInfo = GRDBiOSTests; }; - 564C5B7D1F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCA231CB1A8BB00F48B96; - remoteInfo = GRDBCipheriOS; - }; - 564C5B7F1F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCA7F1CB1AA9900F48B96; - remoteInfo = GRDBCipheriOSTests; - }; - 564C5B811F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56AFCAD71CB1ABC800F48B96; - remoteInfo = GRDBCipheriOSEncryptedTests; - }; - 564C5B831F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA7FFE1CFB25E4003DC1BA; - remoteInfo = GRDBCustomSQLiteiOS; - }; - 564C5B851F489B8A00176870 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = F3BA80411CFB2AD7003DC1BA; - remoteInfo = GRDBCustomSQLiteiOSTests; - }; 564C5B871F489B8A00176870 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; @@ -136,6 +66,13 @@ remoteGlobalIDString = 565490A01D5A4798005622CB; remoteInfo = GRDBWatchOS; }; + 56B1C3BD201C8B7D001938DA /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56537C841BA8874F00E87787 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = 56439B501F4CA1DC0066043F; + remoteInfo = GRDBOSXPerformanceComparisonTests; + }; /* End PBXContainerItemProxy section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -182,19 +119,10 @@ 564C5B681F489B8A00176870 /* GRDB.framework */, 564C5B6A1F489B8A00176870 /* GRDBOSXTests.xctest */, 564C5B6C1F489B8A00176870 /* GRDBOSXPerformanceTests.xctest */, + 56B1C3BE201C8B7D001938DA /* GRDBOSXPerformanceComparisonTests.xctest */, 564C5B6E1F489B8A00176870 /* GRDBOSXCrashTests.xctest */, - 564C5B701F489B8A00176870 /* GRDBCipher.framework */, - 564C5B721F489B8A00176870 /* GRDBCipherOSXTests.xctest */, - 564C5B741F489B8A00176870 /* GRDBCipherOSXEncryptedTests.xctest */, - 564C5B761F489B8A00176870 /* GRDBCustomSQLite.framework */, - 564C5B781F489B8A00176870 /* GRDBCustomSQLiteOSXTests.xctest */, 564C5B7A1F489B8A00176870 /* GRDB.framework */, 564C5B7C1F489B8A00176870 /* GRDBiOSTests.xctest */, - 564C5B7E1F489B8A00176870 /* GRDBCipher.framework */, - 564C5B801F489B8A00176870 /* GRDBCipheriOSTests.xctest */, - 564C5B821F489B8A00176870 /* GRDBCipheriOSEncryptedTests.xctest */, - 564C5B841F489B8A00176870 /* GRDBCustomSQLite.framework */, - 564C5B861F489B8A00176870 /* GRDBCustomSQLiteiOSTests.xctest */, 564C5B881F489B8A00176870 /* GRDB.framework */, ); name = Products; @@ -258,7 +186,7 @@ 56537C6A1BA8871A00E87787 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0900; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { 56537C711BA8871A00E87787 = { @@ -320,41 +248,6 @@ remoteRef = 564C5B6D1F489B8A00176870 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 564C5B701F489B8A00176870 /* GRDBCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCipher.framework; - remoteRef = 564C5B6F1F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B721F489B8A00176870 /* GRDBCipherOSXTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipherOSXTests.xctest; - remoteRef = 564C5B711F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B741F489B8A00176870 /* GRDBCipherOSXEncryptedTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipherOSXEncryptedTests.xctest; - remoteRef = 564C5B731F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B761F489B8A00176870 /* GRDBCustomSQLite.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCustomSQLite.framework; - remoteRef = 564C5B751F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B781F489B8A00176870 /* GRDBCustomSQLiteOSXTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCustomSQLiteOSXTests.xctest; - remoteRef = 564C5B771F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 564C5B7A1F489B8A00176870 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -369,41 +262,6 @@ remoteRef = 564C5B7B1F489B8A00176870 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 564C5B7E1F489B8A00176870 /* GRDBCipher.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCipher.framework; - remoteRef = 564C5B7D1F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B801F489B8A00176870 /* GRDBCipheriOSTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipheriOSTests.xctest; - remoteRef = 564C5B7F1F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B821F489B8A00176870 /* GRDBCipheriOSEncryptedTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCipheriOSEncryptedTests.xctest; - remoteRef = 564C5B811F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B841F489B8A00176870 /* GRDBCustomSQLite.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDBCustomSQLite.framework; - remoteRef = 564C5B831F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 564C5B861F489B8A00176870 /* GRDBCustomSQLiteiOSTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBCustomSQLiteiOSTests.xctest; - remoteRef = 564C5B851F489B8A00176870 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; 564C5B881F489B8A00176870 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -411,6 +269,13 @@ remoteRef = 564C5B871F489B8A00176870 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; + 56B1C3BE201C8B7D001938DA /* GRDBOSXPerformanceComparisonTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBOSXPerformanceComparisonTests.xctest; + remoteRef = 56B1C3BD201C8B7D001938DA /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -462,12 +327,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -514,12 +381,14 @@ CLANG_WARN_BOOL_CONVERSION = YES; CLANG_WARN_COMMA = YES; CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; @@ -550,6 +419,7 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; @@ -563,11 +433,13 @@ isa = XCBuildConfiguration; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_OBJC_WEAK = YES; COMBINE_HIDPI_IMAGES = YES; INFOPLIST_FILE = GRDBProfiling/Info.plist; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBProfiling; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 3.0; }; From d8c411ad52ee506142bfd309f0e305cb59e95e94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 12:09:51 +0100 Subject: [PATCH 002/348] Swift 4.1 compatibility (SE-0184 , SE-0187) --- GRDB.xcodeproj/project.pbxproj | 16 ++++++++-------- GRDB/Core/DatabaseFunction.swift | 2 +- .../Foundation/DatabaseDateComponents.swift | 2 +- GRDB/Core/TransactionObserver.swift | 4 ++-- GRDB/Legacy/Swift4.1.swift | 16 ++++++++++++++++ GRDB/QueryInterface/TableDefinition.swift | 2 +- GRDB/Record/RowConvertible+Decodable.swift | 2 +- GRDBCipher.xcodeproj/project.pbxproj | 6 ++++++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++++++ Tests/GRDBTests/DatabaseAggregateTests.swift | 4 ++++ Tests/GRDBTests/DatabaseFunctionTests.swift | 4 ++++ .../QueryInterfaceExpressionsTests.swift | 4 ++++ 12 files changed, 54 insertions(+), 14 deletions(-) create mode 100644 GRDB/Legacy/Swift4.1.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index eb73b43ab..25c15e753 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -423,6 +423,9 @@ 56B021CD1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; + 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; + 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; + 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; @@ -940,6 +943,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; + 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.0.3/Realm.framework"; sourceTree = ""; }; @@ -1612,6 +1616,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -2252,6 +2257,7 @@ 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, + 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */, @@ -2330,6 +2336,7 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, + 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */, 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, @@ -2735,6 +2742,7 @@ 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, + 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2840,7 +2848,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2886,7 +2893,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OBJC_BRIDGING_HEADER = "Tests/Performance/GRDBPerformanceComparisonTests-Bridging.h"; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; @@ -2974,7 +2980,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3025,7 +3030,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -3063,7 +3067,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3100,7 +3103,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3200,7 +3202,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; @@ -3247,7 +3248,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 8de8d1ed4..a0443c87d 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -274,7 +274,7 @@ public final class DatabaseFunction { let aggregateContextU = Unmanaged.passRetained(aggregateContext) var aggregateContextP = aggregateContextU.toOpaque() withUnsafeBytes(of: &aggregateContextP) { - aggregateContextBufferP.copyBytes(from: $0) + aggregateContextBufferP.copyMemory(from: $0) } return aggregateContextU } diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 1e1385a85..93d7978d4 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -105,7 +105,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { timeString = nil } - return [dateString, timeString].flatMap { $0 }.joined(separator: " ").databaseValue + return [dateString, timeString].compactMap { $0 }.joined(separator: " ").databaseValue } /// Returns a DatabaseDateComponents if *dbValue* contains a diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 0d3f0bfe5..00df65ec3 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -238,7 +238,7 @@ class DatabaseObservationBroker { // For example, if one observes all deletions in the table T, then // all individual deletions of DELETE FROM T are notified: let eventKind = eventKinds[0] - statementObservations = transactionObservations.flatMap { observation in + statementObservations = transactionObservations.compactMap { observation in guard observation.observes(eventsOfKind: eventKind) else { // observation is not interested return nil @@ -260,7 +260,7 @@ class DatabaseObservationBroker { // For example, if DELETE FROM T1 generates deletions in T1 and T2 // by the mean of a foreign key action, then when one only observes // deletions in T1, one must not be notified of deletions in T2: - statementObservations = transactionObservations.flatMap { observation in + statementObservations = transactionObservations.compactMap { observation in let observedKinds = eventKinds.filter(observation.observes) if observedKinds.isEmpty { // observation is not interested diff --git a/GRDB/Legacy/Swift4.1.swift b/GRDB/Legacy/Swift4.1.swift new file mode 100644 index 000000000..1d125c78e --- /dev/null +++ b/GRDB/Legacy/Swift4.1.swift @@ -0,0 +1,16 @@ +// Compatibility layer for Swift < 4.1 + +#if swift(>=4.1) +#else +extension Sequence { + func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { + return try flatMap(transform) + } +} + +extension UnsafeMutableRawBufferPointer { + func copyMemory(from source: C) where C : Collection, C.Element == UInt8 { + copyBytes(from: source) + } +} +#endif diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 9a3242973..52b704542 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -463,7 +463,7 @@ public final class TableDefinition { } let indexStatements = columns - .flatMap { $0.indexDefinition(in: name) } + .compactMap { $0.indexDefinition(in: name) } .map { $0.sql() } statements.append(contentsOf: indexStatements) return statements.joined(separator: "; ") diff --git a/GRDB/Record/RowConvertible+Decodable.swift b/GRDB/Record/RowConvertible+Decodable.swift index c63ae9942..b8ba94af2 100644 --- a/GRDB/Record/RowConvertible+Decodable.swift +++ b/GRDB/Record/RowConvertible+Decodable.swift @@ -14,7 +14,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer let row = decoder.row let columnNames = Set(row.columnNames) let scopeNames = row.scopeNames - return columnNames.union(scopeNames).flatMap { Key(stringValue: $0) } + return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) } } /// Returns whether the `Decoder` contains a value associated with the given key. diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 5c5a9aa79..56d9918cb 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -482,6 +482,8 @@ 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; + 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; @@ -974,6 +976,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 569B7FA6201C904C0069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1607,6 +1610,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 569B7FA6201C904C0069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -2013,6 +2017,7 @@ 5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, + 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6FA1F307F600095F066 /* Persistable+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, @@ -2407,6 +2412,7 @@ 5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, + 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6F71F307F600095F066 /* Persistable+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 8770937ee..314f5d50d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -189,6 +189,8 @@ 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; + 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; @@ -667,6 +669,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 569B7FA2201C90430069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1279,6 +1282,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 569B7FA2201C90430069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -1714,6 +1718,7 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, + 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F61F307F600095F066 /* Persistable+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -1960,6 +1965,7 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, + 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F51F307F600095F066 /* Persistable+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, diff --git a/Tests/GRDBTests/DatabaseAggregateTests.swift b/Tests/GRDBTests/DatabaseAggregateTests.swift index ad0657436..faf882210 100644 --- a/Tests/GRDBTests/DatabaseAggregateTests.swift +++ b/Tests/GRDBTests/DatabaseAggregateTests.swift @@ -295,7 +295,11 @@ class DatabaseAggregateTests: GRDBTestCase { struct Aggregate : DatabaseAggregate { var result: DatabaseValueConvertible? mutating func step(_ dbValues: [DatabaseValue]) { + #if swift(>=4.1) + let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } + #else let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } + #endif result = ints.reduce(0, +) } func finalize() -> DatabaseValueConvertible? { diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 48cd9f874..4fd02a4b7 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -250,7 +250,11 @@ class DatabaseFunctionTests: GRDBTestCase { func testFunctionOfTwoArguments() throws { let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 2) { dbValues in + #if swift(>=4.1) + let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } + #else let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } + #endif return ints.reduce(0, +) } dbQueue.add(function: fn) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index daa2c3e1e..2dbdfa946 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -31,7 +31,11 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { dbWriter.add(collation: collation) customFunction = DatabaseFunction("avgOf", pure: true) { dbValues in + #if swift(>=4.1) + let sum = dbValues.compactMap { Int.fromDatabaseValue($0) }.reduce(0, +) + #else let sum = dbValues.flatMap { Int.fromDatabaseValue($0) }.reduce(0, +) + #endif return Double(sum) / Double(dbValues.count) } dbWriter.add(function: self.customFunction) From b0e126f29dd6aea9860a68a27599aba8c8c7f0af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 12:19:59 +0100 Subject: [PATCH 003/348] SE-0187: deprecate Cursor.flatMap in favor of Cursor.compactMap --- GRDB/Core/Cursor.swift | 13 +++++++++++++ Tests/GRDBTests/CursorTests.swift | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 26ca0b362..7afea0a74 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -132,11 +132,24 @@ extension Cursor { return nil } + #if swift(>=4.1) + /// Returns a cursor over the concatenated non-nil results of mapping + /// transform over this cursor. + public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + return map(transform).filter { $0 != nil }.map { $0! } + } + + @available(*, deprecated, renamed: "compactMap") + public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { + return compactMap(transform) + } + #else /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { return map(transform).filter { $0 != nil }.map { $0! } } + #endif /// Returns a cursor that skips any initial elements that satisfy /// `predicate`. diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 19c9370e3..81debde5d 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -78,12 +78,21 @@ class CursorTests: GRDBTestCase { } } + #if swift(>=4.1) + func testCompactMap() { + let cursor = IteratorCursor(["1", "foo", "2"]).compactMap { Int($0) } + XCTAssertEqual(try cursor.next()!, 1) + XCTAssertEqual(try cursor.next()!, 2) + XCTAssertTrue(try cursor.next() == nil) // end + } + #else func testFlatMapOfOptional() { let cursor = IteratorCursor(["1", "foo", "2"]).flatMap { Int($0) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertTrue(try cursor.next() == nil) // end } + #endif func testForEach() throws { let cursor = IteratorCursor([1, 2]) From b4922f60a245eeaa351ee686b0a7f91c836fb596 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 12:39:40 +0100 Subject: [PATCH 004/348] SE-0185: let Swift 4.1 generate as much Equatable and Hashable conformance as possible --- GRDB/Core/Database.swift | 6 +++ GRDB/Core/DatabaseError.swift | 3 ++ GRDB/Core/DatabaseFunction.swift | 44 ++++++++++++------- GRDB/Core/DatabaseRegion.swift | 3 ++ GRDB/Core/Statement.swift | 3 ++ .../SQLExpression+QueryInterface.swift | 3 ++ GRDB/Record/FetchedRecordsController.swift | 7 +-- GRDB/Record/Persistable.swift | 20 +++++---- 8 files changed, 63 insertions(+), 26 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9a8f4c8eb..0e0097db7 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -841,11 +841,14 @@ extension Database { self.rawValue = rawValue } + #if swift(>=4.1) + #else /// The hash value /// :nodoc: public var hashValue: Int { return rawValue.hashValue } + #endif /// The `BINARY` built-in SQL collation public static let binary = CollationName("BINARY") @@ -878,11 +881,14 @@ extension Database { self.rawValue = rawValue } + #if swift(>=4.1) + #else /// The hash value /// :nodoc: public var hashValue: Int { return rawValue.hashValue } + #endif /// The `TEXT` SQL column type public static let text = ColumnType("TEXT") diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 6833c383f..4c6b39256 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -139,6 +139,8 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) } +#if swift(>=4.1) +#else // Equatable extension ResultCode { /// :nodoc: @@ -146,6 +148,7 @@ extension ResultCode { return lhs.rawValue == rhs.rawValue } } +#endif // CustomStringConvertible extension ResultCode { diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index a0443c87d..702913cf7 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -5,12 +5,28 @@ #endif /// An SQL function or aggregate. -public final class DatabaseFunction { - public let name: String - let argumentCount: Int32? +public final class DatabaseFunction: Hashable { + // SQLite identifies functions by (name + argument count) + private struct Identity: Hashable { + let name: String + let nArg: Int32 // -1 for variadic functions + + #if swift(>=4.1) + #else + var hashValue: Int { + return name.hashValue ^ nArg.hashValue + } + + static func == (lhs: Identity, rhs: Identity) -> Bool { + return lhs.name == rhs.name && lhs.nArg == rhs.nArg + } + #endif + } + + public var name: String { return identity.name } + private let identity: Identity let pure: Bool private let kind: Kind - private var nArg: Int32 { return argumentCount ?? -1 } private var eTextRep: Int32 { return (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) } /// Returns an SQL function. @@ -38,8 +54,7 @@ public final class DatabaseFunction { /// exactly *argumentCount* elements, provided *argumentCount* is /// not nil. public init(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?) { - self.name = name - self.argumentCount = argumentCount + self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .function{ (argc, argv) in let arguments = (0..(_ name: String, argumentCount: Int32? = nil, pure: Bool = false, aggregate: Aggregate.Type) { - self.name = name - self.argumentCount = argumentCount + self.identity = Identity(name: name, nArg: argumentCount ?? -1) self.pure = pure self.kind = .aggregate { return Aggregate() } } @@ -104,8 +118,8 @@ public final class DatabaseFunction { let code = sqlite3_create_function_v2( db.sqliteConnection, - name, - nArg, + identity.name, + identity.nArg, eTextRep, definitionP, kind.xFunc, @@ -127,8 +141,8 @@ public final class DatabaseFunction { func uninstall(in db: Database) { let code = sqlite3_create_function_v2( db.sqliteConnection, - name, - nArg, + identity.name, + identity.nArg, eTextRep, nil, nil, nil, nil, nil) @@ -309,17 +323,17 @@ public final class DatabaseFunction { } } -extension DatabaseFunction : Hashable { +extension DatabaseFunction { /// The hash value /// :nodoc: public var hashValue: Int { - return name.hashValue ^ nArg.hashValue + return identity.hashValue } /// Two functions are equal if they share the same name and arity. /// :nodoc: public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { - return lhs.name == rhs.name && lhs.nArg == rhs.nArg + return lhs.identity == rhs.identity } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 52f67a6fb..8d4b140ad 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -255,11 +255,14 @@ private struct TableRegion: Equatable { return false } + #if swift(>=4.1) + #else static func == (lhs: TableRegion, rhs: TableRegion) -> Bool { if lhs.columns != rhs.columns { return false } if lhs.rowIds != rhs.rowIds { return false } return true } + #endif func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index f29a1536f..dbbcf86e8 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -911,6 +911,8 @@ extension StatementArguments { } } +#if swift(>=4.1) +#else // Equatable extension StatementArguments { /// :nodoc: @@ -920,6 +922,7 @@ extension StatementArguments { return true } } +#endif /// A thread-unsafe statement cache struct StatementCache { diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 786ec9a5d..825774fde 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -486,6 +486,8 @@ public struct SQLFunctionName : Hashable { self.sql = sql } + #if swift(>=4.1) + #else /// The hash value /// /// :nodoc: @@ -499,6 +501,7 @@ public struct SQLFunctionName : Hashable { public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool { return lhs.sql == rhs.sql } + #endif } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 03dd53490..9d23f784b 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -1050,8 +1050,9 @@ private final class Item : RowConvertible, Equatable { init(row: Row) { self.row = row.copy() } + + static func == (lhs: Item, rhs: Item) -> Bool { + return lhs.row == rhs.row + } } -private func == (lhs: Item, rhs: Item) -> Bool { - return lhs.row == rhs.row -} diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 002e78175..824617966 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -977,20 +977,22 @@ final class DAO { // MARK: - InsertQuery -private struct InsertQuery { +private struct InsertQuery: Hashable { let onConflict: Database.ConflictResolution let tableName: String let insertedColumns: [String] -} - -extension InsertQuery : Hashable { + + // Not generated by Swift 4.1 var hashValue: Int { return tableName.hashValue } + #if swift(>=4.1) + #else static func == (lhs: InsertQuery, rhs: InsertQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } if lhs.onConflict != rhs.onConflict { return false } return lhs.insertedColumns == rhs.insertedColumns } + #endif } extension InsertQuery { @@ -1016,22 +1018,24 @@ extension InsertQuery { // MARK: - UpdateQuery -private struct UpdateQuery { +private struct UpdateQuery: Hashable { let onConflict: Database.ConflictResolution let tableName: String let updatedColumns: [String] let conditionColumns: [String] -} - -extension UpdateQuery : Hashable { + + // Not generated by Swift 4.1 var hashValue: Int { return tableName.hashValue } + #if swift(>=4.1) + #else static func == (lhs: UpdateQuery, rhs: UpdateQuery) -> Bool { if lhs.tableName != rhs.tableName { return false } if lhs.onConflict != rhs.onConflict { return false } if lhs.updatedColumns != rhs.updatedColumns { return false } return lhs.conditionColumns == rhs.conditionColumns } + #endif } extension UpdateQuery { From 11ec16494d18f69341f724d7eea24077f6d0c1f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 12:41:38 +0100 Subject: [PATCH 005/348] TODO Swift 4.1 --- TODO.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/TODO.md b/TODO.md index f0baf3825..2c043996f 100644 --- a/TODO.md +++ b/TODO.md @@ -13,6 +13,10 @@ - [ ] Allow concurrent reads from a snapshot - [ ] Decode NSDecimalNumber from text database values +Xcode 9.3, Swift 4.1 + +- [ ] Audit Cursor return types and make it look as much as possible as stdlib's lazy sequence + GRDB 3.0 - [ ] Rename "changes tracking" (ambiguous with database observation) to "record comparison" From 6043b4288e231e0115e9eaf9471234095ba3b91b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 13:03:34 +0100 Subject: [PATCH 006/348] SE-0184: backport UnsafeMutablePointer.deallocate() --- GRDB/FTS/FTS5Tokenizer.swift | 4 ++-- GRDB/Legacy/Swift4.1.swift | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index dcb01d7f7..20efcdad3 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -192,10 +192,10 @@ let api = FTS5.api(self) let xTokenizerPointer: UnsafeMutablePointer = .allocate(capacity: 1) - defer { xTokenizerPointer.deallocate(capacity: 1) } + defer { xTokenizerPointer.deallocate() } let contextHandle: UnsafeMutablePointer = .allocate(capacity: 1) - defer { contextHandle.deallocate(capacity: 1) } + defer { contextHandle.deallocate() } let code = api.pointee.xFindTokenizer!( UnsafeMutablePointer(mutating: api), diff --git a/GRDB/Legacy/Swift4.1.swift b/GRDB/Legacy/Swift4.1.swift index 1d125c78e..418865e83 100644 --- a/GRDB/Legacy/Swift4.1.swift +++ b/GRDB/Legacy/Swift4.1.swift @@ -3,12 +3,21 @@ #if swift(>=4.1) #else extension Sequence { + // From future import SE-0187 func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { return try flatMap(transform) } } +extension UnsafeMutablePointer { + // From future import SE-0184 + func deallocate() { + deallocate(capacity: 0) + } +} + extension UnsafeMutableRawBufferPointer { + // From future import SE-0184 func copyMemory(from source: C) where C : Collection, C.Element == UInt8 { copyBytes(from: source) } From 028093199b906a1458e1a596668d822492aa0bb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 27 Jan 2018 13:13:49 +0100 Subject: [PATCH 007/348] Replace flatMap with compactMap in README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9caefd747..280cd2370 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](ht **Latest release**: February 25, 2018 • version 2.9.0 • [CHANGELOG](CHANGELOG.md) -**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.0 / Xcode 9+ +**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | @@ -666,7 +666,7 @@ Both arrays and cursors can iterate over database results. How do you choose one If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate. -**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.9/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.9/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // All URL hosts @@ -1500,7 +1500,7 @@ When you don't provide any explicit *argumentCount*, the function can take any n ```swift let averageOf = DatabaseFunction("averageOf", pure: true) { (values: [DatabaseValue]) in - let doubles = values.flatMap { Double.fromDatabaseValue($0) } + let doubles = values.compactMap { Double.fromDatabaseValue($0) } return doubles.reduce(0, +) / Double(doubles.count) } dbQueue.add(function: averageOf) From f605e049fd3d4057841e2df1610e21f29bf14eeb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Feb 2018 16:22:24 +0100 Subject: [PATCH 008/348] Rename TypedRequest to FetchRequest, drop Request --- GRDB.xcodeproj/project.pbxproj | 52 +- GRDB/Core/DatabaseValueConvertible.swift | 203 +++--- GRDB/Core/FetchRequest.swift | 262 ++++++++ GRDB/Core/Request.swift | 622 ------------------ GRDB/Core/Row.swift | 134 ++-- GRDB/Core/StatementColumnConvertible.swift | 203 +++--- GRDB/Legacy/Fixits-0-90-1.swift | 8 +- GRDB/Legacy/Fixits-0.109.0.swift | 4 +- GRDB/Legacy/Fixits-3.0.swift | 3 + ...nition.swift => QueryInterfaceQuery.swift} | 21 +- .../QueryInterfaceRequest.swift | 11 +- GRDB/Record/FetchedRecordsController.swift | 44 +- GRDB/Record/RowConvertible.swift | 114 ++-- GRDBCipher.xcodeproj/project.pbxproj | 50 +- GRDBCustom.xcodeproj/project.pbxproj | 42 +- TODO.md | 5 +- .../GRDBTests/CompilationProtocolTests.swift | 23 +- Tests/GRDBTests/DatabaseRegionTests.swift | 18 +- .../DatabaseValueConvertibleFetchTests.swift | 102 +-- Tests/GRDBTests/FetchRequestTests.swift | 139 ++++ Tests/GRDBTests/GRDBTestCase.swift | 12 +- .../QueryInterfaceExtensibilityTests.swift | 4 +- .../QueryInterfaceRequestTests.swift | 16 +- Tests/GRDBTests/RequestTests.swift | 83 --- Tests/GRDBTests/RowAdapterTests.swift | 47 +- ...nvertible+QueryInterfaceRequestTests.swift | 6 +- Tests/GRDBTests/RowConvertibleTests.swift | 60 +- Tests/GRDBTests/RowFetchTests.swift | 60 +- Tests/GRDBTests/SQLRequestTests.swift | 26 +- ...StatementColumnConvertibleFetchTests.swift | 96 +-- ...leMapping+QueryInterfaceRequestTests.swift | 8 +- 31 files changed, 1007 insertions(+), 1471 deletions(-) create mode 100644 GRDB/Core/FetchRequest.swift delete mode 100644 GRDB/Core/Request.swift create mode 100644 GRDB/Legacy/Fixits-3.0.swift rename GRDB/QueryInterface/{QueryInterfaceSelectQueryDefinition.swift => QueryInterfaceQuery.swift} (94%) create mode 100644 Tests/GRDBTests/FetchRequestTests.swift delete mode 100644 Tests/GRDBTests/RequestTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 25c15e753..5b5b41f10 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -27,8 +27,8 @@ 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; - 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; + 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; @@ -113,8 +113,8 @@ 563363D11C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; 563363D61C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; }; 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; - 5636E9BC1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9BF1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 56439B331F4CA1DC0066043F /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86191BA988F2001F9168 /* FMDatabase.m */; }; 56439B341F4CA1DC0066043F /* InsertRecordClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB86121BA9886D001F9168 /* InsertRecordClassTests.swift */; }; 56439B351F4CA1DC0066043F /* FMDatabaseAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 56BB861B1BA988F2001F9168 /* FMDatabaseAdditions.m */; }; @@ -159,7 +159,7 @@ 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; - 565490C11D5AE236005622CB /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 565490C21D5AE236005622CB /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; }; @@ -182,7 +182,7 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; @@ -267,8 +267,8 @@ 5672DE6A1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */; }; 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; - 56741EA81E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAC1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; @@ -364,6 +364,9 @@ 5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; + 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; + 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */; }; 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; }; 569EF0E3200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */; }; @@ -756,7 +759,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -797,7 +800,7 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 563363F81C960711000BE133 /* PerformanceRealmTests.realm */ = {isa = PBXFileReference; lastKnownFileType = file; path = PerformanceRealmTests.realm; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 56439B501F4CA1DC0066043F /* GRDBOSXPerformanceComparisonTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceComparisonTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; @@ -846,7 +849,7 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; @@ -898,6 +901,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1278,8 +1282,8 @@ 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -1426,11 +1430,11 @@ 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1521,7 +1525,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1616,6 +1620,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */, 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */, ); path = Legacy; @@ -2167,6 +2172,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56D51D061EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, @@ -2175,7 +2181,7 @@ 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, - 565490C11D5AE236005622CB /* Request.swift in Sources */, + 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2251,7 +2257,7 @@ 565490D31D5AE252005622CB /* (null) in Sources */, 566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 566B910F1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, - 565490DE1D5AE252005622CB /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */, 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, @@ -2287,7 +2293,7 @@ buildActionMask = 2147483647; files = ( 56BF6D401DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BF1D22574100B9B05F /* Request.swift in Sources */, + 5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2305,6 +2311,7 @@ 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */, + 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 5664759D1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, @@ -2337,7 +2344,7 @@ 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */, - 5605F1941C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, 5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, @@ -2445,7 +2452,7 @@ 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, - 56741EAC1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */, @@ -2593,7 +2600,7 @@ 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */, 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */, - 56741EA81E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56D496831D813147008276D7 /* DatabaseSavepointTests.swift in Sources */, 56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */, 56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, @@ -2682,7 +2689,7 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BC1D22574100B9B05F /* Request.swift in Sources */, + 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -2739,7 +2746,7 @@ 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */, - 5605F1931C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */, @@ -2761,6 +2768,7 @@ 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, + 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 43cbc96f9..ea14adeff 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -194,64 +194,6 @@ extension DatabaseValueConvertible { } } -extension DatabaseValueConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// for let name = try names.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchAll(db, request) // [String] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single value fetched from a fetch request. - /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let name = try String.fetchOne(db, request) // String? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension DatabaseValueConvertible { // MARK: Fetching From SQL @@ -276,7 +218,7 @@ extension DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of values fetched from an SQL query. @@ -291,7 +233,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) } /// Returns a single value fetched from an SQL query. @@ -309,10 +251,64 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) } } +extension FetchRequest where RowDecoder: DatabaseValueConvertible { + + // MARK: Fetching Values + + /// A cursor over fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchCursor(db) // Cursor of String + /// while let string = try strings.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchAll(statement, adapter: adapter) + } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchOne(statement, adapter: adapter) + } +} /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: @@ -368,48 +364,6 @@ extension Optional where Wrapped: DatabaseValueConvertible { } } -extension Optional where Wrapped: DatabaseValueConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - requet: A fetch request. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } -} - extension Optional where Wrapped: DatabaseValueConvertible { // MARK: Fetching From SQL @@ -434,7 +388,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of optional values fetched from an SQL query. @@ -449,6 +403,45 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + } +} + +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { + + // MARK: Fetching Optional values + + /// A cursor over fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchCursor(db) // Cursor of String? + /// while let string = try strings.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { + let (statement, adapter) = try prepare(db) + return try Optional.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { + let (statement, adapter) = try prepare(db) + return try Optional.fetchAll(statement, adapter: adapter) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift new file mode 100644 index 000000000..d6ad9c914 --- /dev/null +++ b/GRDB/Core/FetchRequest.swift @@ -0,0 +1,262 @@ +/// The protocol for all types that define a way to fetch database content. +/// +/// struct Player: RowConvertible { ... } +/// let request: ... // Some FetchRequest that fetches Player +/// try request.fetchCursor(db) // Cursor of Player +/// try request.fetchAll(db) // [Player] +/// try request.fetchOne(db) // Player? +public protocol FetchRequest { + /// The type that can convert raw database rows to fetched values + associatedtype RowDecoder + + /// A tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + + /// The number of rows fetched by the request. + /// + /// Default implementation builds a naive SQL query based on the statement + /// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. + /// + /// Adopting types can refine this countRequest method and return more + /// efficient SQL. + /// + /// - parameter db: A database connection. + func fetchCount(_ db: Database) throws -> Int + + /// The database region that the request looks into. + /// + /// This method has a default implementation. + /// + /// - parameter db: A database connection. + func fetchedRegion(_ db: Database) throws -> DatabaseRegion +} + +extension FetchRequest { + /// The number of rows fetched by the request. + /// + /// This default implementation builds a naive SQL query based on the + /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. + /// + /// - parameter db: A database connection. + public func fetchCount(_ db: Database) throws -> Int { + let (statement, _) = try prepare(db) + let sql = "SELECT COUNT(*) FROM (\(statement.sql))" + return try Int.fetchOne(db, sql, arguments: statement.arguments)! + } + + /// The database region that the request looks into. + /// + /// - parameter db: A database connection. + public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + let (statement, _) = try prepare(db) + return statement.fetchedRegion + } +} + +extension FetchRequest { + /// Returns a request bound to type T. + /// + /// The returned request can fetch if the type T is fetchable (Row, + /// value, record). + /// + /// // Int? + /// let maxScore = Player + /// .select(max(scoreColumn)) + /// .asRequest(of: Int.self) // <-- + /// .fetchOne(db) + /// + /// - parameter type: The fetched type T + /// - returns: A typed request bound to type T. + public func asRequest(of type: T.Type) -> AnyFetchRequest { + return AnyFetchRequest(self) + } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// Returns an adapted request. + public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + return AdaptedFetchRequest(self, adapter) + } +} + +/// An adapted request. +public struct AdaptedFetchRequest : FetchRequest { + public typealias RowDecoder = Base.RowDecoder + + private let base: Base + private let adapter: (Database) throws -> RowAdapter + + /// Creates an adapted request from a base request and a closure that builds + /// a row adapter from a database connection. + init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { + self.base = base + self.adapter = adapter + } + + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let (statement, baseAdapter) = try base.prepare(db) + if let baseAdapter = baseAdapter { + return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db))) + } else { + return try (statement, adapter(db)) + } + } + + /// :nodoc: + public func fetchCount(_ db: Database) throws -> Int { + return try base.fetchCount(db) + } + + /// :nodoc: + public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + return try base.fetchedRegion(db) + } +} + +/// A type-erased FetchRequest. +/// +/// An AnyFetchRequest forwards its operations to an underlying request, +/// hiding its specifics. +public struct AnyFetchRequest : FetchRequest { + public typealias RowDecoder = T + + private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?) + private let _fetchCount: (Database) throws -> Int + private let _fetchedRegion: (Database) throws -> DatabaseRegion + + /// Creates a new request that wraps and forwards operations to `request`. + public init(_ request: Request) { + _prepare = request.prepare + _fetchCount = request.fetchCount + _fetchedRegion = request.fetchedRegion + } + + /// Creates a new request whose `prepare()` method wraps and forwards + /// operations the argument closure. + public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { + _prepare = { db in + try prepare(db) + } + + _fetchCount = { db in + let (statement, _) = try prepare(db) + let sql = "SELECT COUNT(*) FROM (\(statement.sql))" + return try Int.fetchOne(db, sql, arguments: statement.arguments)! + } + + _fetchedRegion = { db in + let (statement, _) = try prepare(db) + return statement.fetchedRegion + } + } + + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try _prepare(db) + } + + /// :nodoc: + public func fetchCount(_ db: Database) throws -> Int { + return try _fetchCount(db) + } + + /// :nodoc: + public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + return try _fetchedRegion(db) + } +} + +/// A Request built from raw SQL. +public struct SQLRequest : FetchRequest { + public typealias RowDecoder = T + + public let sql: String + public let arguments: StatementArguments? + public let adapter: RowAdapter? + private let cache: Cache? + + /// Creates a new request from an SQL string, optional arguments, and + /// optional row adapter. + /// + /// let request = SQLRequest("SELECT * FROM players") + /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. + /// - adapter: Optional RowAdapter. + /// - cached: Defaults to false. If true, the request reuses a cached + /// prepared statement. + /// - returns: A SQLRequest + public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { + self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil) + } + + /// Creates a new SQL request from any other fetch request. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A request. + /// - cached: Defaults to false. If true, the request reuses a cached + /// prepared statement. + /// - returns: An SQLRequest + public init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder { + let (statement, adapter) = try request.prepare(db) + self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached) + } + + /// Creates a new SQL request from an SQL string, optional arguments, and + /// optional row adapter. + /// + /// let request = SQLRequest("SELECT * FROM players") + /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// + /// - parameters: + /// - sql: An SQL query. + /// - arguments: Optional statement arguments. + /// - adapter: Optional RowAdapter. + /// - statementCacheName: Optional statement cache name. + /// - returns: A SQLRequest + init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { + self.sql = sql + self.arguments = arguments + self.adapter = adapter + self.cache = cache + } + + /// A tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + /// + /// - parameter db: A database connection. + /// + /// :nodoc: + public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let statement: SelectStatement + switch cache { + case .none: + statement = try db.makeSelectStatement(sql) + case .public?: + statement = try db.cachedSelectStatement(sql) + case .internal?: + statement = try db.internalCachedSelectStatement(sql) + } + if let arguments = arguments { + try statement.setArgumentsWithValidation(arguments) + } + return (statement, adapter) + } + + /// There are two statement caches: one for statements generated by the + /// user, and one for the statements generated by GRDB. Those are separated + /// so that GRDB has no opportunity to inadvertently modify the arguments of + /// user's cached statements. + enum Cache { + /// The public cache, for library user + case `public` + + /// The internal cache, for grdb + case `internal` + } +} diff --git a/GRDB/Core/Request.swift b/GRDB/Core/Request.swift deleted file mode 100644 index 4e67887fa..000000000 --- a/GRDB/Core/Request.swift +++ /dev/null @@ -1,622 +0,0 @@ -/// The protocol for all types that define a way to fetch database rows. -/// -/// Requests can feed the fetching methods of any fetchable type (Row, -/// value, record): -/// -/// let request: Request = ... -/// try Row.fetchCursor(db, request) // RowCursor -/// try String.fetchAll(db, request) // [String] -/// try Player.fetchOne(db, request) // Player? -public protocol Request { - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) - - /// The number of rows fetched by the request. - /// - /// Default implementation builds a naive SQL query based on the statement - /// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. - /// - /// Adopting types can refine this countRequest method and return more - /// efficient SQL. - /// - /// - parameter db: A database connection. - func fetchCount(_ db: Database) throws -> Int - - /// The database region that the request looks into. - /// - /// This method has a default implementation. - /// - /// - parameter db: A database connection. - func fetchedRegion(_ db: Database) throws -> DatabaseRegion -} - -extension Request { - /// The number of rows fetched by the request. - /// - /// This default implementation builds a naive SQL query based on the - /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. - /// - /// - parameter db: A database connection. - public func fetchCount(_ db: Database) throws -> Int { - let (statement, _) = try prepare(db) - let sql = "SELECT COUNT(*) FROM (\(statement.sql))" - return try Int.fetchOne(db, sql, arguments: statement.arguments)! - } - - /// Returns an equivalent SQLRequest. - /// - /// - parameters: - /// - db: A database connection. - /// - cached: Defaults to false. If true, the request reuses a cached - /// prepared statement. - /// - returns: An SQLRequest - public func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest { - let (statement, adapter) = try prepare(db) - return SQLRequest(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached) - } - - /// The database region that the request looks into. - /// - /// - parameter db: A database connection. - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db) - return statement.fetchedRegion - } -} - -extension Request { - /// Returns a request bound to type T. - /// - /// The returned request can fetch if the type T is fetchable (Row, - /// value, record). - /// - /// // Int? - /// let maxScore = Player - /// .select(max(scoreColumn)) - /// .asRequest(of: Int.self) // <-- - /// .fetchOne(db) - /// - /// - parameter type: The fetched type T - /// - returns: A typed request bound to type T. - public func asRequest(of type: T.Type) -> AnyTypedRequest { - return AnyTypedRequest(self) - } - - /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest { - return AdaptedRequest(self, adapter) - } -} - -/// An adapted request. -public struct AdaptedRequest : Request { - private let base: Base - private let adapter: (Database) throws -> RowAdapter - - /// Creates an adapted request from a base request and a closure that builds - /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { - self.base = base - self.adapter = adapter - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let (statement, baseAdapter) = try base.prepare(db) - if let baseAdapter = baseAdapter { - return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db))) - } else { - return try (statement, adapter(db)) - } - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A type-erased Request. -/// -/// An instance of AnyRequest forwards its operations to an underlying request, -/// hiding its specifics. -public struct AnyRequest : Request { - private let base: Request - - /// Creates a new request that wraps and forwards operations to `request`. - public init(_ request: Request) { - base = request - } - - /// Creates a new request whose `prepare()` method wraps and forwards - /// operations the argument closure. - public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { - struct PrepareRequest: Request { - let base: (Database) throws -> (SelectStatement, RowAdapter?) - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base(db) - } - } - base = PrepareRequest(base: prepare) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A Request built from raw SQL. -public struct SQLRequest : Request { - public let sql: String - public let arguments: StatementArguments? - public let adapter: RowAdapter? - private let cache: Cache? - - /// Creates a new request from an SQL string, optional arguments, and - /// optional row adapter. - /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) - /// - /// - parameters: - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter. - /// - cached: Defaults to false. If true, the request reuses a cached - /// prepared statement. - /// - returns: A SQLRequest - public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { - self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil) - } - - /// Creates a new request from an SQL string, optional arguments, and - /// optional row adapter. - /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) - /// - /// - parameters: - /// - sql: An SQL query. - /// - arguments: Optional statement arguments. - /// - adapter: Optional RowAdapter. - /// - statementCacheName: Optional statement cache name. - /// - returns: A SQLRequest - init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { - self.sql = sql - self.arguments = arguments - self.adapter = adapter - self.cache = cache - } - - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - /// - /// - parameter db: A database connection. - /// - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let statement: SelectStatement - switch cache { - case .none: - statement = try db.makeSelectStatement(sql) - case .public?: - statement = try db.cachedSelectStatement(sql) - case .internal?: - statement = try db.internalCachedSelectStatement(sql) - } - if let arguments = arguments { - try statement.setArgumentsWithValidation(arguments) - } - return (statement, adapter) - } - - /// There are two statement caches: one for statements generated by the - /// user, and one for the statements generated by GRDB. Those are separated - /// so that GRDB has no opportunity to inadvertently modify the arguments of - /// user's cached statements. - enum Cache { - /// The public cache, for library user - case `public` - - /// The internal cache, for grdb - case `internal` - } -} - -/// The protocol for requests that know how to decode database rows. -/// -/// Typed requests can fetch if their associated type RowDecoder is able to -/// decode rows (Row, value, record) -/// -/// struct Player: RowConvertible { ... } -/// let request: ... // Some TypedRequest that fetches Player -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchOne(db) // Player? -public protocol TypedRequest : Request { - - /// The type that can convert raw database rows to fetched values - associatedtype RowDecoder -} - -extension TypedRequest { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// Returns an adapted typed request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest { - return AdaptedTypedRequest(self, adapter) - } -} - -/// An adapted typed request. -public struct AdaptedTypedRequest : TypedRequest { - /// The type that can convert raw database rows to fetched values - public typealias RowDecoder = Base.RowDecoder - - private let base: AdaptedRequest - - /// Creates an adapted request from a base request and a closure that builds - /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> RowAdapter) { - self.base = AdaptedRequest(base, adapter) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -/// A type-erased TypedRequest. -/// -/// An instance of AnyTypedRequest forwards its operations to an underlying -/// typed request, hiding its specifics. -public struct AnyTypedRequest : TypedRequest { - /// The type that can convert raw database rows to fetched values - public typealias RowDecoder = T - private let base: Request - - /// Support for Request.asRequest(of:) - /// Not public because not type-safe. - fileprivate init(_ request: Request) { - base = request - } - - /// Creates a new request that wraps and forwards operations to `request`. - public init(_ request: Request) where Request: TypedRequest, Request.RowDecoder == RowDecoder { - base = request - } - - /// Creates a new request whose `prepare()` method wraps and forwards - /// operations the argument closure. - public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { - base = AnyRequest(prepare) - } - - /// :nodoc: - public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try base.prepare(db) - } - - /// :nodoc: - public func fetchCount(_ db: Database) throws -> Int { - return try base.fetchCount(db) - } - - /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) - } -} - -extension TypedRequest where RowDecoder: RowConvertible { - - // MARK: Fetching Record and RowConvertible - - /// A cursor over fetched records. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let players = try request.fetchCursor(db) // Cursor of Player - /// while let player = try players.next() { // Player - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RecordCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched records. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let players = try request.fetchAll(db) // [Player] - /// - /// - parameter db: A database connection. - /// - returns: An array of records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched record. - /// - /// let request: ... // Some TypedRequest that fetches Player - /// let player = try request.fetchOne(db) // Player? - /// - /// - parameter db: A database connection. - /// - returns: An optional record. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: DatabaseValueConvertible { - - // MARK: Fetching Values - - /// A cursor over fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchAll(db) // [String] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching Values - - /// A cursor over fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchCursor(db) // Cursor of String - /// while let string = try strings.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> ColumnCursor { - return try RowDecoder.fetchCursor(db, self) - } - - /// An array of fetched values. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let strings = try request.fetchAll(db) // [String] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder] { - return try RowDecoder.fetchAll(db, self) - } - - /// The first fetched value. - /// - /// The result is nil if the request returns no row, or if no value can be - /// extracted from the first row. - /// - /// let request: ... // Some TypedRequest that fetches String - /// let string = try request.fetchOne(db) // String? - /// - /// - parameter db: A database connection. - /// - returns: An optional value. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> RowDecoder? { - return try RowDecoder.fetchOne(db, self) - } -} - -extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - return try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) - } -} - -extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching Optional values - - /// A cursor over fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchCursor(db) // Cursor of String? - /// while let string = try strings.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> NullableColumnCursor { - return try Optional.fetchCursor(db, self) - } - - /// An array of fetched optional values. - /// - /// let request: ... // Some TypedRequest that fetches Optional - /// let strings = try request.fetchAll(db) // [String?] - /// - /// - parameter db: A database connection. - /// - returns: An array of values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - return try Optional.fetchAll(db, self) - } -} - -extension TypedRequest where RowDecoder: Row { - - // MARK: Fetching Rows - - /// A cursor over fetched rows. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let rows = try request.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameter db: A database connection. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchCursor(_ db: Database) throws -> RowCursor { - return try Row.fetchCursor(db, self) - } - - /// An array of fetched rows. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let rows = try request.fetchAll(db) - /// - /// - parameter db: A database connection. - /// - returns: An array of fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchAll(_ db: Database) throws -> [Row] { - return try Row.fetchAll(db, self) - } - - /// The first fetched row. - /// - /// let request: ... // Some TypedRequest that fetches Row - /// let row = try request.fetchOne(db) - /// - /// - parameter db: A database connection. - /// - returns: A,n optional rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public func fetchOne(_ db: Database) throws -> Row? { - return try Row.fetchOne(db, self) - } -} diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 348c6976a..f999ba905 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -652,73 +652,6 @@ extension Row { } } -extension Row { - - // MARK: - Fetching From Request - - /// Returns a cursor over rows fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let rows = try Row.fetchCursor(db) // RowCursor - /// while let row = try rows.next() { // Row - /// let id: Int64 = row[0] - /// let name: String = row[1] - /// } - /// - /// Fetched rows are reused during the cursor iteration: don't turn a row - /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since - /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` - /// instead. - /// - /// For the same reason, make sure you make a copy whenever you extract a - /// row for later use: `row.copy()`. - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched rows. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of rows fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let rows = try Row.fetchAll(db, request) - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single row fetched from a fetch request. - /// - /// let idColumn = Column("id") - /// let nameColumn = Column("name") - /// let request = Player.select(idColumn, nameColumn) - /// let row = try Row.fetchOne(db, request) - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Row? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension Row { // MARK: - Fetching From SQL @@ -752,7 +685,7 @@ extension Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of rows fetched from an SQL query. @@ -767,7 +700,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) } /// Returns a single row fetched from an SQL query. @@ -782,7 +715,68 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) + } +} + +extension FetchRequest where RowDecoder: Row { + + // MARK: Fetching Rows + + /// A cursor over fetched rows. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let rows = try request.fetchCursor(db) // RowCursor + /// while let row = try rows.next() { // Row + /// let id: Int64 = row[0] + /// let name: String = row[1] + /// } + /// + /// Fetched rows are reused during the cursor iteration: don't turn a row + /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since + /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` + /// instead. + /// + /// For the same reason, make sure you make a copy whenever you extract a + /// row for later use: `row.copy()`. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RowCursor { + let (statement, adapter) = try prepare(db) + return try Row.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched rows. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let rows = try request.fetchAll(db) + /// + /// - parameter db: A database connection. + /// - returns: An array of fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [Row] { + let (statement, adapter) = try prepare(db) + return try Row.fetchAll(statement, adapter: adapter) + } + + /// The first fetched row. + /// + /// let request: ... // Some TypedRequest that fetches Row + /// let row = try request.fetchOne(db) + /// + /// - parameter db: A database connection. + /// - returns: A,n optional rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> Row? { + let (statement, adapter) = try prepare(db) + return try Row.fetchOne(statement, adapter: adapter) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index f0ade5e43..1df56baf0 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -225,64 +225,6 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { } } -extension DatabaseValueConvertible where Self: StatementColumnConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchCursor(db, request) // Cursor of String - /// while let name = try names.next() { // String - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> ColumnCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try String.fetchAll(db, request) // [String] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single value fetched from a fetch request. - /// - /// The result is nil if the query returns no row, or if no value can be - /// extracted from the first row. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let name = try String.fetchOne(db, request) // String? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension DatabaseValueConvertible where Self: StatementColumnConvertible { // MARK: Fetching From SQL @@ -307,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of values fetched from an SQL query. @@ -322,7 +264,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) } /// Returns a single value fetched from an SQL query. @@ -337,10 +279,64 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) } } +extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching Values + + /// A cursor over fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchCursor(db) // Cursor of String + /// while let string = try strings.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> ColumnCursor { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched values. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let strings = try request.fetchAll(db) // [String] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchAll(statement, adapter: adapter) + } + + /// The first fetched value. + /// + /// The result is nil if the request returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request: ... // Some TypedRequest that fetches String + /// let string = try request.fetchOne(db) // String? + /// + /// - parameter db: A database connection. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchOne(statement, adapter: adapter) + } +} /// Swift's Optional comes with built-in methods that allow to fetch cursors /// and arrays of optional DatabaseValueConvertible: @@ -396,48 +392,6 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } -extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchCursor(db, request) // Cursor of String? - /// while let name = try names.next() { // String? - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - requet: A fetch request. - /// - returns: A cursor over fetched optional values. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableColumnCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of optional values fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn) - /// let names = try Optional.fetchAll(db, request) // [String?] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } -} - extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { // MARK: Fetching From SQL @@ -462,7 +416,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of optional values fetched from an SQL query. @@ -477,6 +431,45 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + } +} + +extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching Optional values + + /// A cursor over fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchCursor(db) // Cursor of String? + /// while let string = try strings.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> NullableColumnCursor { + let (statement, adapter) = try prepare(db) + return try Optional.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched optional values. + /// + /// let request: ... // Some TypedRequest that fetches Optional + /// let strings = try request.fetchAll(db) // [String?] + /// + /// - parameter db: A database connection. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { + let (statement, adapter) = try prepare(db) + return try Optional.fetchAll(statement, adapter: adapter) } } diff --git a/GRDB/Legacy/Fixits-0-90-1.swift b/GRDB/Legacy/Fixits-0-90-1.swift index 681937a45..12835dd45 100644 --- a/GRDB/Legacy/Fixits-0-90-1.swift +++ b/GRDB/Legacy/Fixits-0-90-1.swift @@ -2,7 +2,7 @@ extension Row { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -11,7 +11,7 @@ extension DatabaseValueConvertible { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -20,7 +20,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } @@ -34,7 +34,7 @@ extension RowConvertible { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") - public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } + public static func fetch(_ db: Database, _ request: Request) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } diff --git a/GRDB/Legacy/Fixits-0.109.0.swift b/GRDB/Legacy/Fixits-0.109.0.swift index d26a5d501..6c2034ea6 100644 --- a/GRDB/Legacy/Fixits-0.109.0.swift +++ b/GRDB/Legacy/Fixits-0.109.0.swift @@ -1,4 +1,4 @@ -extension Request { +extension FetchRequest { @available(*, unavailable, renamed:"asRequest(of:)") - public func bound(to type: T.Type) -> AnyTypedRequest { preconditionFailure() } + public func bound(to type: T.Type) -> AnyFetchRequest { preconditionFailure() } } diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift new file mode 100644 index 000000000..a2e9f8b8c --- /dev/null +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -0,0 +1,3 @@ +@available(*, unavailable, renamed:"FetchRequest") +public typealias Request = FetchRequest + diff --git a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift similarity index 94% rename from GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift rename to GRDB/QueryInterface/QueryInterfaceQuery.swift index a15c19729..40319ee3b 100644 --- a/GRDB/QueryInterface/QueryInterfaceSelectQueryDefinition.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -1,5 +1,3 @@ -// MARK: - QueryInterfaceSelectQueryDefinition - struct DatabasePromise { let resolve: (Database) throws -> T @@ -18,7 +16,7 @@ struct DatabasePromise { } } -struct QueryInterfaceSelectQueryDefinition { +struct QueryInterfaceQuery { var selection: [SQLSelectable] var isDistinct: Bool var source: SQLSource? @@ -51,7 +49,7 @@ struct QueryInterfaceSelectQueryDefinition { self.limit = limit } - func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceSelectQueryDefinition { + func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceQuery { var query = self query.wherePromise = query.wherePromise.map(transform) return query @@ -160,7 +158,7 @@ struct QueryInterfaceSelectQueryDefinition { } /// Remove ordering - var unorderedQuery: QueryInterfaceSelectQueryDefinition { + var unorderedQuery: QueryInterfaceQuery { var query = self query.isReversed = false query.orderings = [] @@ -168,7 +166,7 @@ struct QueryInterfaceSelectQueryDefinition { } } -extension QueryInterfaceSelectQueryDefinition : Request { +extension QueryInterfaceQuery { func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { var arguments: StatementArguments? = StatementArguments() let sql = try self.sql(db, &arguments) @@ -178,7 +176,8 @@ extension QueryInterfaceSelectQueryDefinition : Request { } func fetchCount(_ db: Database) throws -> Int { - return try Int.fetchOne(db, countQuery)! + let (statement, adapter) = try countQuery.prepare(db) + return try Int.fetchOne(statement, adapter: adapter)! } /// The database region that the request looks into. @@ -217,7 +216,7 @@ extension QueryInterfaceSelectQueryDefinition : Request { return region.tableIntersection(canonicalTableName, rowIds: rowIds) } - private var countQuery: QueryInterfaceSelectQueryDefinition { + private var countQuery: QueryInterfaceQuery { guard groupByExpressions.isEmpty && limit == nil else { // SELECT ... GROUP BY ... // SELECT ... LIMIT ... @@ -255,8 +254,8 @@ extension QueryInterfaceSelectQueryDefinition : Request { } // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: QueryInterfaceSelectQueryDefinition { - return QueryInterfaceSelectQueryDefinition( + private var trivialCountQuery: QueryInterfaceQuery { + return QueryInterfaceQuery( select: [SQLExpressionCount(AllColumns())], from: .query(query: unorderedQuery, alias: nil)) } @@ -264,7 +263,7 @@ extension QueryInterfaceSelectQueryDefinition : Request { indirect enum SQLSource { case table(name: String, alias: String?) - case query(query: QueryInterfaceSelectQueryDefinition, alias: String?) + case query(query: QueryInterfaceQuery, alias: String?) func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { switch self { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 8cd1c29fc..420d10c57 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -2,14 +2,14 @@ /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct QueryInterfaceRequest { - let query: QueryInterfaceSelectQueryDefinition + let query: QueryInterfaceQuery - init(query: QueryInterfaceSelectQueryDefinition) { + init(query: QueryInterfaceQuery) { self.query = query } } -extension QueryInterfaceRequest : TypedRequest { +extension QueryInterfaceRequest : FetchRequest { public typealias RowDecoder = T /// A tuple that contains a prepared statement that is ready to be @@ -394,7 +394,10 @@ extension TableMapping { /// all requests by the `TableMapping.databaseSelection` property, or /// for individual requests with the `TableMapping.select` method. public static func all() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: QueryInterfaceSelectQueryDefinition(select: databaseSelection, from: .table(name: databaseTableName, alias: nil))) + let query = QueryInterfaceQuery( + select: databaseSelection, + from: .table(name: databaseTableName, alias: nil)) + return QueryInterfaceRequest(query: query) } /// Creates a QueryInterfaceRequest which fetches no record. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 9d23f784b..4892eb859 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -47,7 +47,7 @@ public final class FetchedRecordsController { { try self.init( databaseWriter, - request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), + request: SQLRequest(sql, arguments: arguments, adapter: adapter), queue: queue, isSameRecord: isSameRecord) } @@ -79,7 +79,7 @@ public final class FetchedRecordsController { request: Request, queue: DispatchQueue = .main, isSameRecord: ((Record, Record) -> Bool)? = nil) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { let itemsAreIdenticalFactory: ItemComparatorFactory if let isSameRecord = isSameRecord { @@ -100,12 +100,14 @@ public final class FetchedRecordsController { request: Request, queue: DispatchQueue, itemsAreIdenticalFactory: @escaping ItemComparatorFactory) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { self.itemsAreIdenticalFactory = itemsAreIdenticalFactory - self.request = request + self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) + let region = try request.fetchedRegion(db) + let itemsAreIdentical = try itemsAreIdenticalFactory(db) + return (region, itemsAreIdentical) } self.databaseWriter = databaseWriter self.queue = queue @@ -130,7 +132,7 @@ public final class FetchedRecordsController { // observer is added on the same serialized queue as transaction // callbacks. try databaseWriter.write { db in - let initialItems = try Item.fetchAll(db, request) + let initialItems = try request.fetchAll(db) fetchedItems = initialItems if let fetchAndNotifyChanges = fetchAndNotifyChanges { let observer = FetchedRecordsObserver(region: self.region, fetchAndNotifyChanges: fetchAndNotifyChanges) @@ -160,10 +162,12 @@ public final class FetchedRecordsController { /// /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). - public func setRequest(_ request: Request) throws where Request: TypedRequest, Request.RowDecoder == Record { - self.request = request + public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { + self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - try FetchedRecordsController.fetchRegionAndComparator(db, request: request, itemsAreIdenticalFactory: itemsAreIdenticalFactory) + let region = try request.fetchedRegion(db) + let itemsAreIdentical = try itemsAreIdenticalFactory(db) + return (region, itemsAreIdentical) } // No observer: don't look for changes @@ -193,7 +197,7 @@ public final class FetchedRecordsController { /// This method must be used from the controller's dispatch queue (the /// main queue unless stated otherwise in the controller's initializer). public func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws { - try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self)) + try setRequest(SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Registers changes notification callbacks. @@ -376,7 +380,8 @@ public final class FetchedRecordsController { private let itemsAreIdenticalFactory: ItemComparatorFactory /// The request - fileprivate var request: Request + fileprivate typealias ItemRequest = AnyFetchRequest> + fileprivate var request: ItemRequest /// The observed database region private var region : DatabaseRegion @@ -386,17 +391,6 @@ public final class FetchedRecordsController { /// The eventual error handler fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? - - private static func fetchRegionAndComparator( - _ db: Database, - request: Request, - itemsAreIdenticalFactory: ItemComparatorFactory) throws - -> (DatabaseRegion, ItemComparator) - { - let region = try request.fetchedRegion(db) - let itemsAreIdentical = try itemsAreIdenticalFactory(db) - return (region, itemsAreIdentical) - } } extension FetchedRecordsController where Record: TableMapping { @@ -441,7 +435,7 @@ extension FetchedRecordsController where Record: TableMapping { { try self.init( databaseWriter, - request: SQLRequest(sql, arguments: arguments, adapter: adapter).asRequest(of: Record.self), + request: SQLRequest(sql, arguments: arguments, adapter: adapter), queue: queue) } @@ -475,7 +469,7 @@ extension FetchedRecordsController where Record: TableMapping { _ databaseWriter: DatabaseWriter, request: Request, queue: DispatchQueue = .main) throws - where Request: TypedRequest, Request.RowDecoder == Record + where Request: FetchRequest, Request.RowDecoder == Record { // Builds a function that returns true if and only if two items // have the same primary key and primary keys contain at least one @@ -620,7 +614,7 @@ private func makeFetchFunction( do { try databaseWriter.readFromCurrentState { db in result = Result { try ( - fetchedItems: Item.fetchAll(db, request), + fetchedItems: request.fetchAll(db), fetchedAlongside: fetchAlongside(db)) } semaphore.signal() } diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/RowConvertible.swift index 3162400e8..d85efe7d2 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/RowConvertible.swift @@ -125,61 +125,6 @@ extension RowConvertible { } } -extension RowConvertible { - - // MARK: Fetching From Request - - /// Returns a cursor over records fetched from a fetch request. - /// - /// let nameColumn = Column("firstName") - /// let request = Player.order(nameColumn) - /// let identities = try Identity.fetchCursor(db, request) // Cursor of Identity - /// while let identity = try identities.next() { // Identity - /// ... - /// } - /// - /// If the database is modified during the cursor iteration, the remaining - /// elements are undefined. - /// - /// The cursor must be iterated in a protected dispath queue. - /// - /// - parameters: - /// - db: A database connection. - /// - request: A fetch request. - /// - returns: A cursor over fetched records. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor { - let (statement, adapter) = try request.prepare(db) - return try fetchCursor(statement, adapter: adapter) - } - - /// Returns an array of records fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.order(nameColumn) - /// let identities = try Identity.fetchAll(db, request) // [Identity] - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] { - let (statement, adapter) = try request.prepare(db) - return try fetchAll(statement, adapter: adapter) - } - - /// Returns a single record fetched from a fetch request. - /// - /// let nameColumn = Column("name") - /// let request = Player.order(nameColumn) - /// let identity = try Identity.fetchOne(db, request) // Identity? - /// - /// - parameter db: A database connection. - /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. - public static func fetchOne(_ db: Database, _ request: Request) throws -> Self? { - let (statement, adapter) = try request.prepare(db) - return try fetchOne(statement, adapter: adapter) - } -} - extension RowConvertible { // MARK: Fetching From SQL @@ -204,7 +149,7 @@ extension RowConvertible { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) } /// Returns an array of records fetched from an SQL query. @@ -219,7 +164,7 @@ extension RowConvertible { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) } /// Returns a single record fetched from an SQL query. @@ -234,6 +179,59 @@ extension RowConvertible { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) } } + +extension FetchRequest where RowDecoder: RowConvertible { + + // MARK: Fetching Record and RowConvertible + + /// A cursor over fetched records. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let players = try request.fetchCursor(db) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameter db: A database connection. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchCursor(_ db: Database) throws -> RecordCursor { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchCursor(statement, adapter: adapter) + } + + /// An array of fetched records. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let players = try request.fetchAll(db) // [Player] + /// + /// - parameter db: A database connection. + /// - returns: An array of records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchAll(_ db: Database) throws -> [RowDecoder] { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchAll(statement, adapter: adapter) + } + + /// The first fetched record. + /// + /// let request: ... // Some TypedRequest that fetches Player + /// let player = try request.fetchOne(db) // Player? + /// + /// - parameter db: A database connection. + /// - returns: An optional record. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public func fetchOne(_ db: Database) throws -> RowDecoder? { + let (statement, adapter) = try prepare(db) + return try RowDecoder.fetchOne(statement, adapter: adapter) + } +} + diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 56d9918cb..6988346fe 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -25,7 +25,7 @@ 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; - 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 560FC5351CB003810014AA8E /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -181,8 +181,8 @@ 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */; }; - 5636E9BD1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9C01D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; @@ -350,10 +350,10 @@ 5672DE6C1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */; }; 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567404871CEF84C8003ED5CC /* RowAdapter.swift */; }; - 56741EA91E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAA1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAD1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAE1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; @@ -482,6 +482,8 @@ 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; + 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; @@ -529,7 +531,7 @@ 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */; }; @@ -839,7 +841,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -879,7 +881,7 @@ 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; @@ -926,7 +928,7 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; @@ -976,6 +978,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; 569B7FA6201C904C0069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; @@ -1333,8 +1336,8 @@ 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -1467,10 +1470,10 @@ 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1561,7 +1564,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1610,6 +1613,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */, 569B7FA6201C904C0069DE70 /* Swift4.1.swift */, ); path = Legacy; @@ -1989,7 +1993,7 @@ files = ( 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BD1D22574100B9B05F /* Request.swift in Sources */, + 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -2047,7 +2051,7 @@ 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, 560FC5331CB003810014AA8E /* Migration.swift in Sources */, - 560FC5341CB003810014AA8E /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, @@ -2068,6 +2072,7 @@ 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, + 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, @@ -2160,7 +2165,7 @@ 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */, 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, - 56741EA91E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, @@ -2308,7 +2313,7 @@ 5657AB501D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */, 5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */, - 56741EAA1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C6A1EACCCC8000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, @@ -2384,7 +2389,7 @@ files = ( 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9C01D22574100B9B05F /* Request.swift in Sources */, + 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -2442,7 +2447,7 @@ 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */, 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */, - 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, @@ -2463,6 +2468,7 @@ 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, + 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, @@ -2555,7 +2561,7 @@ 5698ACBB1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, - 56741EAD1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C761EACCCCA000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, @@ -2703,7 +2709,7 @@ 5698ACBC1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 56741EAE1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C7C1EACCCCB000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 314f5d50d..d02cf9602 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -41,8 +41,8 @@ 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; }; 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; - 5636E9BE1D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; - 5636E9C11D22574100B9B05F /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* Request.swift */; }; + 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; }; 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564E73E7203DA278000C443C /* JoinSupportTests.swift */; }; @@ -113,8 +113,8 @@ 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; - 56741EAB1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; - 56741EAF1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; + 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; + 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; }; 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; @@ -189,6 +189,8 @@ 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; }; 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; + 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; + 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; @@ -313,7 +315,7 @@ F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -357,7 +359,7 @@ F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */; }; - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */; }; + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; @@ -541,7 +543,7 @@ 5605F1581C672E4000235C62 /* StandardLibrary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StandardLibrary.swift; sourceTree = ""; }; 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = ""; }; 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLCollatedExpression.swift; sourceTree = ""; }; - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceSelectQueryDefinition.swift; sourceTree = ""; }; + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceQuery.swift; sourceTree = ""; }; 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = ""; }; 560A37A31C8F625000949E71 /* DatabasePool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePool.swift; sourceTree = ""; }; 560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SerializedDatabase.swift; sourceTree = ""; }; @@ -578,7 +580,7 @@ 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = ""; }; 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; - 5636E9BB1D22574100B9B05F /* Request.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Request.swift; sourceTree = ""; }; + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = ""; }; 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = ""; }; 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; @@ -624,7 +626,7 @@ 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueBackupTests.swift; sourceTree = ""; }; 5672DE661CDB751D0022BA81 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 567404871CEF84C8003ED5CC /* RowAdapter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowAdapter.swift; sourceTree = ""; }; - 56741EA71E66A8B3003E422D /* RequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestTests.swift; sourceTree = ""; }; + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; @@ -669,6 +671,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 569A98F62039B716008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; 569B7FA2201C90430069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; @@ -1005,8 +1008,8 @@ 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, + 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, - 5605F18C1C6B1A8700235C62 /* QueryInterfaceSelectQueryDefinition.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -1138,11 +1141,11 @@ 56A238191B9C74A90082EB20 /* DatabaseValueConvertible */, 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */, 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */, + 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */, 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */, 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */, 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */, 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */, - 56741EA71E66A8B3003E422D /* RequestTests.swift */, 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */, 56A2381D1B9C74A90082EB20 /* Row */, 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */, @@ -1233,7 +1236,7 @@ 56A238751B9C75030082EB20 /* DatabaseValue.swift */, 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */, 563363C31C942C37000BE133 /* DatabaseWriter.swift */, - 5636E9BB1D22574100B9B05F /* Request.swift */, + 5636E9BB1D22574100B9B05F /* FetchRequest.swift */, 56A238761B9C75030082EB20 /* Row.swift */, 567404871CEF84C8003ED5CC /* RowAdapter.swift */, 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */, @@ -1282,6 +1285,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */, 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, + 569A98F62039B716008D7DBF /* Fixits-3.0.swift */, 569B7FA2201C90430069DE70 /* Swift4.1.swift */, ); path = Legacy; @@ -1690,7 +1694,7 @@ files = ( 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9C11D22574100B9B05F /* Request.swift in Sources */, + 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -1731,7 +1735,7 @@ F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */, 56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */, - F3BA802F1CFB289B003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + F3BA802F1CFB289B003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5061EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55F1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, @@ -1769,6 +1773,7 @@ 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, + 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -1909,7 +1914,7 @@ 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, F3BA80DB1CFB300E003DC1BA /* DatabaseValueConversionTests.swift in Sources */, - 56741EAF1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, @@ -1937,7 +1942,7 @@ files = ( 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, - 5636E9BE1D22574100B9B05F /* Request.swift in Sources */, + 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */, @@ -1978,7 +1983,7 @@ F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, - F3BA808B1CFB2E70003DC1BA /* QueryInterfaceSelectQueryDefinition.swift in Sources */, + F3BA808B1CFB2E70003DC1BA /* QueryInterfaceQuery.swift in Sources */, 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 56CEB55C1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, @@ -2016,6 +2021,7 @@ 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, + 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -2157,7 +2163,7 @@ F3BA81351CFB3064003DC1BA /* RecordEditedTests.swift in Sources */, 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 56741EAB1E66A8B3003E422D /* RequestTests.swift in Sources */, + 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, diff --git a/TODO.md b/TODO.md index 2c043996f..ae14caca0 100644 --- a/TODO.md +++ b/TODO.md @@ -20,7 +20,7 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 - [ ] Rename "changes tracking" (ambiguous with database observation) to "record comparison" -- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. +- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. Remove QueryInterfaceExtensibilityTests.swift - [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: @@ -34,7 +34,8 @@ GRDB 3.0 - [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. - [ ] Drop IteratorCursor, use AnyCursor instead -- [ ] Drop TypedRequest, have FetchRequest defaults to Row requests. +<<<<<<< HEAD +- [X] Rename TypedRequest to FetchRequest, drop Request - [ ] Rename columnCount -> numberOfColumns - [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help? diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 882d246ea..2069056dd 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -134,13 +134,11 @@ private class UserPersistable2 : Persistable { func encode(to container: inout PersistenceContainer) { } } -// MARK: - Request +// MARK: - FetchRequest -private struct UserRequest1 : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } -} - -private class UserRequest2 : Request { +private struct UserRowRequest : FetchRequest { + struct CustomType { } + typealias RowDecoder = CustomType func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } } @@ -174,19 +172,6 @@ private class UserTableMapping2 : TableMapping { static let databaseTableName = "UserTableMapping2" } -// MARK: - TypedRequest - -private struct UserTypedRequest1 : TypedRequest { - struct CustomType { } - typealias RowDecoder = CustomType - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } -} - -private class UserTypedRequest2 : TypedRequest { - typealias RowDecoder = T - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } -} - // MARK: - TransactionObserver private class UserTransactionObserver : TransactionObserver { diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index ba0a0f401..55406b398 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -422,28 +422,16 @@ class DatabaseRegionTests : GRDBTestCase { try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") do { - let derivedRequest: AnyRequest = AnyRequest(request) + let derivedRequest: AnyFetchRequest = AnyFetchRequest(request) try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") } do { - let derivedRequest: AnyTypedRequest = AnyTypedRequest(request) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AnyTypedRequest = request.asRequest(of: Row.self) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AdaptedTypedRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") - } - do { - let derivedRequest: AdaptedRequest = AnyRequest(request).adapted { db in SuffixRowAdapter(fromIndex: 1) } + let derivedRequest: AdaptedFetchRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") } do { // SQL request loses region info - let derivedRequest: SQLRequest = try request.asSQLRequest(db) + let derivedRequest = try SQLRequest(db, request: request) try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)") } } diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index 1e41287a2..ffdd12fe6 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -41,8 +41,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -50,8 +49,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -85,16 +83,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -117,16 +113,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -142,8 +136,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -151,8 +144,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -177,16 +169,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -209,16 +199,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -235,8 +223,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -244,8 +231,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -257,8 +243,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, NULL" @@ -266,8 +251,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -279,8 +263,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1" @@ -288,8 +271,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -315,16 +297,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -347,16 +327,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -376,8 +354,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) - try test(Optional.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -385,8 +362,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -420,16 +396,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -452,16 +426,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -479,8 +451,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) - try test(Optional.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -488,8 +459,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -514,16 +484,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -546,16 +514,14 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift new file mode 100644 index 000000000..a0a407ae7 --- /dev/null +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -0,0 +1,139 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class FetchRequestTests: GRDBTestCase { + + func testRequestFetchRows() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT * FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let rows = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0], ["id": 1]) + XCTAssertEqual(rows[1], ["id": 2]) + } + } + + func testRequestFetchValues() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Int + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT id FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let ints = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT id FROM table1") + XCTAssertEqual(ints.count, 2) + XCTAssertEqual(ints[0], 1) + XCTAssertEqual(ints[1], 2) + } + } + + func testRequestFetchRecords() throws { + struct CustomRecord: RowConvertible, Decodable { + var id: Int + } + struct CustomRequest : FetchRequest { + typealias RowDecoder = CustomRecord + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT id FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let records = try request.fetchAll(db) + XCTAssertEqual(lastSQLQuery, "SELECT id FROM table1") + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[1].id, 2) + } + } + + func testRequestFetchCount() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("SELECT * FROM table1"), nil) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let count = try request.fetchCount(db) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM table1)") + XCTAssertEqual(count, 2) + } + } + + func testRequestCustomizedFetchCount() throws { + struct CustomRequest : FetchRequest { + typealias RowDecoder = Row + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (db.makeSelectStatement("INVALID"), nil) + } + + func fetchCount(_ db: Database) throws -> Int { + return 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "table1") { t in + t.column("id", .integer).primaryKey() + } + try db.execute("INSERT INTO table1 DEFAULT VALUES") + try db.execute("INSERT INTO table1 DEFAULT VALUES") + + let request = CustomRequest() + let count = try request.fetchCount(db) + XCTAssertEqual(lastSQLQuery, "INSERT INTO table1 DEFAULT VALUES") + XCTAssertEqual(count, 2) + } + } +} diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 0a02d380f..e505717f3 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -145,21 +145,23 @@ class GRDBTestCase: XCTestCase { } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { - _ = try Row.fetchOne(db, request) + func assertEqualSQL(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + let (statement, _) = try request.prepare(db) + try statement.cursor().next() assertEqualSQL(lastSQLQuery, sql, file: file, line: line) } // Compare SQL strings (ignoring leading and trailing white space and semicolons. - func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { + func assertEqualSQL(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws { try databaseReader.unsafeRead { db in try assertEqualSQL(db, request, sql, file: file, line: line) } } - func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { + func sql(_ databaseReader: DatabaseReader, _ request: Request) -> String { return try! databaseReader.unsafeRead { db in - _ = try Row.fetchOne(db, request) + let (statement, _) = try request.prepare(db) + try statement.cursor().next() return lastSQLQuery } } diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 8fc0c11f0..235f64585 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -68,7 +68,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.execute("INSERT INTO records (date) VALUES (?)", arguments: [date]) let request = Record.select(strftime("%Y", Column("date"))) - let year = try Int.fetchOne(db, request) + let year = try request.asRequest(of: Int.self).fetchOne(db) XCTAssertEqual(year, 1970) XCTAssertEqual(self.lastSQLQuery, "SELECT STRFTIME('%Y', \"date\") FROM \"records\"") } @@ -105,7 +105,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.execute("INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) let request = Record.select(cast(Column("text"), as: .blob)) - let dbValue = try DatabaseValue.fetchOne(db, request)! + let dbValue = try request.asRequest(of: DatabaseValue.self).fetchOne(db)! switch dbValue.storage { case .blob: break diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index b2f18fd74..f32069f12 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -51,7 +51,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) do { - let rows = try Row.fetchAll(db, tableRequest) + let rows = try tableRequest.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, 1) @@ -63,7 +63,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { } do { - let row = try Row.fetchOne(db, tableRequest)! + let row = try tableRequest.asRequest(of: Row.self).fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(row["id"] as Int64, 1) XCTAssertEqual(row["name"] as String, "Arthur") @@ -72,7 +72,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { var names: [String] = [] - let rows = try Row.fetchCursor(db, tableRequest) + let rows = try tableRequest.asRequest(of: Row.self).fetchCursor(db) while let row = try rows.next() { names.append(row["name"]) } @@ -139,7 +139,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - 1") - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -156,7 +156,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - ?", arguments: [1]) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -173,7 +173,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - :n", arguments: ["n": 1]) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -190,7 +190,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(Col.name, Col.id - 1) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -206,7 +206,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne")) - let row = try Row.fetchOne(db, request)! + let row = try request.asRequest(of: Row.self).fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", (\"age\" + 1) AS \"agePlusOne\" FROM \"readers\"") XCTAssertEqual(row["nom"] as String, "Arthur") XCTAssertEqual(row["agePlusOne"] as Int, 43) diff --git a/Tests/GRDBTests/RequestTests.swift b/Tests/GRDBTests/RequestTests.swift deleted file mode 100644 index 93f5d74a8..000000000 --- a/Tests/GRDBTests/RequestTests.swift +++ /dev/null @@ -1,83 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -class RequestTests: GRDBTestCase { - - func testRequestFetch() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("SELECT * FROM table1"), nil) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let rows = try Row.fetchAll(db, request) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM table1") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0], ["id": 1]) - XCTAssertEqual(rows[1], ["id": 2]) - } - } - - func testRequestFetchCount() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("SELECT * FROM table1"), nil) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let count = try request.fetchCount(db) - XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM table1)") - XCTAssertEqual(count, 2) - } - } - - func testRequestCustomizedFetchCount() throws { - struct CustomRequest : Request { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (db.makeSelectStatement("INVALID"), nil) - } - - func fetchCount(_ db: Database) throws -> Int { - return 2 - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "table1") { t in - t.column("id", .integer).primaryKey() - } - try db.execute("INSERT INTO table1 DEFAULT VALUES") - try db.execute("INSERT INTO table1 DEFAULT VALUES") - - let request: Request = CustomRequest() // Lose type - let count = try request.fetchCount(db) - XCTAssertEqual(lastSQLQuery, "INSERT INTO table1 DEFAULT VALUES") - XCTAssertEqual(count, 2) - } - } -} diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 3cda7f89a..ac079ff3a 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -676,71 +676,38 @@ class AdapterRowTests : RowTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) + let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [2.databaseValue]) } do { - let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) + let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) .adapted { _ in ColumnMapping(["a2": "a1"]) } - .asRequest(of: Row.self) .fetchOne(db)! XCTAssertEqual(Array(row.columnNames), ["a2"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } - } - } - - func testTypedRequestAdapter() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2") - .asRequest(of: Row.self) - .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(row.databaseValues), [1.databaseValue, 2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0, 1 AS a1, 2 AS a2", adapter: SuffixRowAdapter(fromIndex: 1)) - .asRequest(of: Row.self) - .adapted { _ in SuffixRowAdapter(fromIndex: 1) } - .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a2"]) - XCTAssertEqual(Array(row.databaseValues), [2.databaseValue]) - } - do { - let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) - .asRequest(of: Row.self) + let row = try SQLRequest("SELECT 0 AS a0", adapter: ColumnMapping(["a1": "a0"])) .adapted { _ in ColumnMapping(["a2": "a1"]) } + .adapted { _ in ColumnMapping(["a3": "a2"]) } .fetchOne(db)! - XCTAssertEqual(Array(row.columnNames), ["a2"]) + XCTAssertEqual(Array(row.columnNames), ["a3"]) XCTAssertEqual(Array(row.databaseValues), [0.databaseValue]) } } diff --git a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift index 5f2c5c9d2..63c1e8d69 100644 --- a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift @@ -158,7 +158,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { let request = Reader.all() do { - let readers = try AltReader.fetchAll(db, request) + let readers = try request.asRequest(of: AltReader.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(readers.count, 2) XCTAssertEqual(readers[0].id!, arthur.id!) @@ -170,7 +170,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { } do { - let reader = try AltReader.fetchOne(db, request)! + let reader = try request.asRequest(of: AltReader.self).fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(reader.id!, arthur.id!) XCTAssertEqual(reader.name, arthur.name) @@ -178,7 +178,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { } do { - let names = try AltReader.fetchCursor(db, request).map { $0.name } + let names = try request.asRequest(of: AltReader.self).fetchCursor(db).map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(try names.next()!, arthur.name) XCTAssertEqual(try names.next()!, barbara.name) diff --git a/Tests/GRDBTests/RowConvertibleTests.swift b/Tests/GRDBTests/RowConvertibleTests.swift index 367eaddb6..d796e710f 100644 --- a/Tests/GRDBTests/RowConvertibleTests.swift +++ b/Tests/GRDBTests/RowConvertibleTests.swift @@ -45,8 +45,7 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -54,8 +53,7 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -89,16 +87,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -121,16 +117,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -147,8 +141,7 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -156,8 +149,7 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -182,16 +174,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -214,16 +204,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -240,8 +228,7 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -249,8 +236,7 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -263,8 +249,7 @@ class RowConvertibleTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" @@ -272,8 +257,7 @@ class RowConvertibleTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -299,16 +283,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -331,16 +313,14 @@ class RowConvertibleTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } diff --git a/Tests/GRDBTests/RowFetchTests.swift b/Tests/GRDBTests/RowFetchTests.swift index 45446a830..0586ebc28 100644 --- a/Tests/GRDBTests/RowFetchTests.swift +++ b/Tests/GRDBTests/RowFetchTests.swift @@ -34,8 +34,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchCursor(db, sql)) try test(Row.fetchCursor(statement)) - try test(Row.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -43,8 +42,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter)) try test(Row.fetchCursor(statement, adapter: adapter)) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -78,16 +76,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw(), NULL" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -110,16 +106,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -136,8 +130,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchAll(db, sql)) try test(Row.fetchAll(statement)) - try test(Row.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName UNION ALL SELECT 0, 'Barbara', 'Gourde'" @@ -145,8 +138,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter)) try test(Row.fetchAll(statement, adapter: adapter)) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -171,16 +163,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -203,16 +193,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -229,8 +217,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) - try test(Row.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -238,8 +225,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -252,8 +238,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) - try test(Row.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0 AS firstName, 'Arthur' AS firstName, 'Martin' AS lastName" @@ -261,8 +246,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -288,16 +272,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -320,16 +302,14 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Row.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 207f1f913..68c2beb6a 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -12,21 +12,23 @@ class SQLRequestTests: GRDBTestCase { func testSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1") + let request = SQLRequest("SELECT 1") let (statement, adapter) = try request.prepare(db) XCTAssertEqual(statement.sql, "SELECT 1") XCTAssertNil(adapter) + let row = try request.fetchOne(db) + XCTAssertEqual(row, ["1": 1]) } } func testSQLRequestWithArgumentsAndAdapter() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1)) + let request = SQLRequest("SELECT ?, ?", arguments: [1, 2], adapter: SuffixRowAdapter(fromIndex: 1)) let (statement, adapter) = try request.prepare(db) XCTAssertEqual(statement.sql, "SELECT ?, ?") XCTAssertNotNil(adapter) - let int = try Int.fetchOne(db, request)! + let int = try request.fetchOne(db)! XCTAssertEqual(int, 2) } } @@ -34,7 +36,7 @@ class SQLRequestTests: GRDBTestCase { func testNotCachedSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1") + let request = SQLRequest("SELECT 1") let (statement1, _) = try request.prepare(db) let (statement2, _) = try request.prepare(db) XCTAssertTrue(statement1 !== statement2) @@ -44,25 +46,29 @@ class SQLRequestTests: GRDBTestCase { func testCachedSQLRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest("SELECT 1", cached: true) + let request = SQLRequest("SELECT 1", cached: true) let (statement1, _) = try request.prepare(db) let (statement2, _) = try request.prepare(db) XCTAssertTrue(statement1 === statement2) } } - func testAsSQLRequest() throws { - struct CustomRequest: Request { + func testRequestInitializer() throws { + struct CustomRequest: FetchRequest { + typealias RowDecoder = Row func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try SQLRequest("SELECT ?, ?", arguments: [1, "foo"]).prepare(db) + let statement = try db.makeSelectStatement("SELECT ? AS a, ? AS b") + statement.arguments = [1, "foo"] + return (statement, nil) } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = CustomRequest() - let sqlRequest = try request.asSQLRequest(db) - XCTAssertEqual(sqlRequest.sql, "SELECT ?, ?") + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT ? AS a, ? AS b") XCTAssertEqual(sqlRequest.arguments, [1, "foo"]) + XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"]) } } } diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index 5b3cdcb9d..a97363c0a 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -100,8 +100,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) - try test(Fetched.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -109,8 +108,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -144,16 +142,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -176,16 +172,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -202,8 +196,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) - try test(Fetched.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, 2" @@ -211,8 +204,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -237,16 +229,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -269,16 +259,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -295,8 +283,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1 WHERE 0" @@ -304,8 +291,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -317,8 +303,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, NULL" @@ -326,8 +311,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } do { @@ -339,8 +323,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) - try test(Fetched.fetchOne(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql).fetchOne(db)) } do { let sql = "SELECT 0, 1" @@ -348,8 +331,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db)) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } } @@ -375,16 +357,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -407,16 +387,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Fetched.self).fetchOne(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } } @@ -438,8 +416,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) - try test(Optional.fetchCursor(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db)) + try test(SQLRequest(sql).fetchCursor(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -447,8 +424,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db)) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } } @@ -471,16 +447,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchCursor(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } } @@ -499,8 +473,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) - try test(Optional.fetchAll(db, SQLRequest(sql))) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db)) + try test(SQLRequest(sql).fetchAll(db)) } do { let sql = "SELECT 0, 1 UNION ALL SELECT 0, NULL" @@ -508,8 +481,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db)) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } } @@ -534,16 +506,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT 0, throw()" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } @@ -566,16 +536,14 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) - try test(SQLRequest(sql).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { let sql = "SELECT * FROM nonExistingTable" let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) - try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) - try test(SQLRequest(sql, adapter: adapter).asRequest(of: Optional.self).fetchAll(db), sql: sql) + try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } } diff --git a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift index a3ac07434..88799416b 100644 --- a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift @@ -91,7 +91,7 @@ class TableMappingQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - 1") - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -108,7 +108,7 @@ class TableMappingQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - ?", arguments: [1]) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -125,7 +125,7 @@ class TableMappingQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - :n", arguments: ["n": 1]) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -142,7 +142,7 @@ class TableMappingQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(Col.name, Col.id - 1) - let rows = try Row.fetchAll(db, request) + let rows = try request.asRequest(of: Row.self).fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") From 769c67e7d398df7b9410263a586925747ff8c7f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Feb 2018 19:34:16 +0100 Subject: [PATCH 009/348] FetchRequest.adapted(_:) in not experimental --- GRDB/Core/FetchRequest.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d6ad9c914..872128408 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -72,8 +72,6 @@ extension FetchRequest { return AnyFetchRequest(self) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) From c108094aa579993df0c3601d08a7ec03111f5299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Feb 2018 19:34:29 +0100 Subject: [PATCH 010/348] FetchRequest changelog --- CHANGELOG.md | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7df2fd449..1470197e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,104 @@ Release Notes ============= +## Next Version + +### Breaking Changes + +- `Request` and `TypedRequest` protocols have been merged into `FetchRequest`. + +### API diff + +FetchRequest + +```diff ++protocol FetchRequest { ++ associatedtype RowDecoder ++ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) ++ func fetchCount(_ db: Database) throws -> Int ++ func fetchedRegion(_ db: Database) throws -> DatabaseRegion ++} ++extension FetchRequest { ++ func fetchCount(_ db: Database) throws -> Int ++ func fetchedRegion(_ db: Database) throws -> DatabaseRegion ++ func asRequest(of type: T.Type) -> AnyFetchRequest ++ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest ++} ++struct AdaptedFetchRequest : FetchRequest { ++ typealias RowDecoder = Base.RowDecoder ++} ++struct AnyFetchRequest : FetchRequest { ++ typealias RowDecoder = T ++ init(_ request: Request) ++ init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) ++} ++struct SQLRequest : FetchRequest { ++ typealias RowDecoder = T ++ let sql: String ++ let arguments: StatementArguments? ++ let adapter: RowAdapter? ++ init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) ++ init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder ++} + ++extension FetchRequest where RowDecoder: DatabaseValueConvertible { ++ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor ++ func fetchAll(_ db: Database) throws -> [RowDecoder] ++ func fetchOne(_ db: Database) throws -> RowDecoder? ++ +} ++extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible ++ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor ++ func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] ++} + ++extension FetchRequest where RowDecoder: Row { ++ func fetchCursor(_ db: Database) throws -> RowCursor ++ func fetchAll(_ db: Database) throws -> [Row] ++ func fetchOne(_ db: Database) throws -> Row? ++} + ++extension FetchRequest where RowDecoder: RowConvertible { ++ func fetchCursor(_ db: Database) throws -> RecordCursor ++ func fetchAll(_ db: Database) throws -> [RowDecoder] ++ func fetchOne(_ db: Database) throws -> RowDecoder? ++} + +-protocol Request { } +-struct AdaptedRequest : Request { } +-struct AnyRequest : Request { } +-struct SQLRequest : Request { } +-protocol TypedRequest : Request { } +-struct AdaptedTypedRequest : TypedRequest { } +-struct AnyTypedRequest : TypedRequest { } + +-extension DatabaseValueConvertible { +- static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor +- static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] +- static func fetchOne(_ db: Database, _ request: Request) throws -> Self? +-} + +-extension Optional where Wrapped: DatabaseValueConvertible { +- static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor +- static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] +-} + +-extension Row { +- static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor +- static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] +- static func fetchOne(_ db: Database, _ request: Request) throws -> Row? +-} + +-extension RowConvertible { +- static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor +- static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] +- static func fetchOne(_ db: Database, _ request: Request) throws -> Self? +-} + +-extension QueryInterfaceRequest : TypedRequest { } ++extension QueryInterfaceRequest : FetchRequest { } +``` + ## 2.9.0 Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.8.0...v2.9.0) From a552e7d25c7e4ce70d9a860a419822ecbbf4cc2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Feb 2018 22:18:35 +0100 Subject: [PATCH 011/348] Update README.md for FetchRequest --- README.md | 135 ++++++++++++++++++++++++++++++------------------------ 1 file changed, 75 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 280cd2370..32b1bd898 100644 --- a/README.md +++ b/README.md @@ -3707,14 +3707,13 @@ Until now, we have seen [requests](#requests) created from any type that adopts let request = Player.all() // QueryInterfaceRequest ``` -Those requests of type `QueryInterfaceRequest` can fetch, count, and delete records: +Those requests of type `QueryInterfaceRequest` can fetch and count: ```swift try request.fetchCursor(db) // A Cursor of Player try request.fetchAll(db) // [Player] try request.fetchOne(db) // Player? try request.fetchCount(db) // Int -try request.deleteAll(db) ``` **When the query interface can not generate the SQL you need**, you can still fallback to [raw SQL](#fetch-queries): @@ -3724,86 +3723,104 @@ try request.deleteAll(db) try Player.fetchAll(db, "SELECT ...") // [Player] ``` -But you may prefer to bring some elegance back in, and build custom requests on top of the `Request` and `TypedRequest` protocols: +But you may prefer to bring some elegance back in, and build custom requests on top of the `FetchRequest` protocol: ```swift // No custom SQL in sight try Player.customRequest().fetchAll(db) // [Player] ``` -Unlike QueryInterfaceRequest, these protocols can't delete. But they can fetch and count: +Custom requests also grant [FetchedRecordsController](#fetchedrecordscontroller) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) the ability to observe the database: ```swift -/// The protocol for all types that define a way to fetch database rows. -protocol Request { - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. +Player.customRequest(...).rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { players: [Player] in + print("Players have changed") + }) +``` + + +### FetchRequest Protocol + +**FetchRequest is the protocol for all types that define a way to fetch database rows:** + +```swift +protocol FetchRequest { + /// The type that tells how fetched rows should be decoded + associatedtype RowDecoder + + /// A tuple that contains a prepared statement, and an eventual row adapter. func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int -} - -/// The protocol for requests that know how to decode database rows. -protocol TypedRequest : Request { - /// The type that can convert raw database rows to fetched values - associatedtype RowDecoder + + /// The database region that the request looks into. + func fetchedRegion(_ db: Database) throws -> DatabaseRegion } ``` -The `prepare` method returns a tuple made of a [prepared statement](#prepared-statements) and an optional [row adapter](#row-adapters). The prepared statement tells which SQL query should be executed. The row adapter can help *presenting* the fetched rows in the way expected by the row consumers (we'll see an example below). +The `RowDecoder` tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. + +The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. - -### Fetching From Custom Requests - -A Request doesn't know what to fetch, but it can feed the [fetching methods](#fetching-methods) of any fetchable type ([Row](#fetching-rows), [value](#value-queries), or [record](#records)): - -```swift -let request: Request = ... -try Row.fetchCursor(db, request) // A Cursor of Row -try String.fetchAll(db, request) // [String] -try Player.fetchOne(db, request) // Player? -``` - -On top of that, a TypedRequest knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)): - -```swift -let request = ... // Some TypedRequest that fetches Player -try request.fetchCursor(db) // A Cursor of Player -try request.fetchAll(db) // [Player] -try request.fetchOne(db) // Player? -``` +The `fetchedRegion` method helps [transaction observers](#transactionobserver-protocol) efficiently track modifications in requests results. It has a default implementation that you can't really improve in the current state of the API. ### Building Custom Requests -**To build custom requests**, you can create your own type that adopts the protocols, or derive requests from other requests, or use one of the built-in concrete types: +**To build custom requests**, you can create your own type that adopts the [FetchRequest](#fetchrequest-protocol) protocol, derive requests from other requests, or use one of the built-in concrete types: -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/SQLRequest.html): a Request built from raw SQL -- [AnyRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/AnyRequest.html): a type-erased Request -- [AnyTypedRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/AnyTypedRequest.html): a type-erased TypedRequest +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: + + ```swift + extension Player { + static func filter(color: Color) -> SQLRequest { + let request = SQLRequest( + "SELECT * FROM players WHERE color = ?" + arguments: [color]) + }s + } + + // [Player] + try Player.filter(color: .red).fetchAll(db) + ``` + +- The `asRequest(of:)` method changes the type fetched by the request: -Use the `asRequest(of:)` method to define the type fetched by the request: + ```swift + // Int? + let maxScore = Player.select(max(Column("score"))) + .asRequest(of: Int.self) + .fetchOne(db) + ``` + +- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. + +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/AnyFetchRequest.html): a type-erased request + + +### Fetching From Custom Requests + +A fetch request knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)): ```swift -let maxScore = Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) +let rowRequest = ... // Some TypedRequest that fetches Row +try request.fetchCursor(db) // A cursor of rows -extension Player { - static func customRequest(...) -> AnyTypedRequest { - let request = SQLRequest("SELECT ...", arguments: ...) - return request.asRequest(of: Player.self) - } -} +let playerRequest = ... // Some TypedRequest that fetches Player +try request.fetchAll(db) // [Player] -try Player.customRequest(...).fetchAll(db) // [Player] -try Player.customRequest(...).fetchCount(db) // Int +let intRequest = ... // Some TypedRequest that fetches Int +try request.fetchOne(db) // Int? ``` -Finally, use the `adapted(_:)` method to ease the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for more information. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. + +When RowDecoder is another type, you can write your own convenience methods. Application Tools @@ -4822,7 +4839,7 @@ Now we write a method that returns a request, and build the fetching method on t ```swift extension Item { /// The request for all items - static func all() -> AnyTypedRequest { + static func all() -> AdaptedFetchRequest> { let sql = """ SELECT \(Player.selectionSQL()), @@ -4833,15 +4850,14 @@ extension Item { LEFT JOIN rounds ON ... GROUP BY ... """ - return SQLRequest(sql).adapted { db in + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) return ScopeAdapter([ Scopes.player: adapters[0], Scopes.team: adapters[1]]) - } - .asRequest(of: Item.self) + } } /// Fetches all items @@ -4896,7 +4912,7 @@ struct Item: Decodable, RowConvertible { extension Item { /// The request for all items - static func all() -> AnyTypedRequest { + static func all() -> AdaptedFetchRequest> { let sql = """ SELECT \(Player.selectionSQL()), @@ -4907,15 +4923,14 @@ extension Item { LEFT JOIN rounds ON ... GROUP BY ... """ - return SQLRequest(sql).adapted { db in + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) return ScopeAdapter([ CodingKeys.player.stringValue: adapters[0], CodingKeys.team.stringValue: adapters[1]]) - } - .asRequest(of: Item.self) + } } /// Fetches all items From c7b9358bc7555126685e5c879bb74f6db0728db5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Feb 2018 22:29:58 +0100 Subject: [PATCH 012/348] Documentation polish --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 32b1bd898..82f2e4340 100644 --- a/README.md +++ b/README.md @@ -3761,7 +3761,7 @@ protocol FetchRequest { } ``` -The `RowDecoder` tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. +The `RowDecoder` associated type tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). @@ -3782,7 +3782,7 @@ The `fetchedRegion` method helps [transaction observers](#transactionobserver-pr let request = SQLRequest( "SELECT * FROM players WHERE color = ?" arguments: [color]) - }s + } } // [Player] @@ -3800,7 +3800,7 @@ The `fetchedRegion` method helps [transaction observers](#transactionobserver-pr - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/AnyFetchRequest.html): a type-erased request +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/2.9/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests From 3bbcb8151d4d726e89cf2dc0da25fdf7a884dd04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 26 Feb 2018 22:34:46 +0100 Subject: [PATCH 013/348] Update JoinSupportTests for FetchRequest --- Tests/GRDBTests/JoinSupportTests.swift | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 6a1c2419a..07027fa21 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -98,8 +98,8 @@ private struct FlatModel: RowConvertible { self.t5count = row.scoped(on: Scopes.suffix)!["t5count"] } - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -111,8 +111,7 @@ private struct FlatModel: RowConvertible { Scopes.t2Right: adapters[2], Scopes.t3: adapters[3], Scopes.suffix: adapters[4]]) // The only test for adapters[4] - } - .asRequest(of: FlatModel.self) + } } } @@ -123,8 +122,8 @@ private struct CodableFlatModel: RowConvertible, Codable { var t3: T3? var t5count: Int - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -135,8 +134,7 @@ private struct CodableFlatModel: RowConvertible, Codable { CodingKeys.t2Left.stringValue: adapters[1], CodingKeys.t2Right.stringValue: adapters[2], CodingKeys.t3.stringValue: adapters[3]]) - } - .asRequest(of: CodableFlatModel.self) + } } } @@ -151,8 +149,8 @@ private struct CodableNestedModel: RowConvertible, Codable { var t3: T3? var t5count: Int - static func all() -> AnyTypedRequest { - return SQLRequest(testedSQL).adapted { db in + static func all() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -167,8 +165,7 @@ private struct CodableNestedModel: RowConvertible, Codable { "left": adapters[1], "right": adapters[2]]), CodingKeys.t3.stringValue: adapters[3]]) - } - .asRequest(of: CodableNestedModel.self) + } } } @@ -274,7 +271,7 @@ class JoinSupportTests: GRDBTestCase { func testSplittingRowAdapters() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let request = SQLRequest(testedSQL).adapted { db in + let request = SQLRequest(testedSQL).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ T1.numberOfSelectedColumns(db), T2.numberOfSelectedColumns(db), @@ -288,7 +285,7 @@ class JoinSupportTests: GRDBTestCase { "t3": adapters[3], "suffix": adapters[4]]) } - let rows = try Row.fetchAll(db, request) + let rows = try request.fetchAll(db) XCTAssertEqual(rows.count, 3) XCTAssertEqual(rows[0].unscoped, [ From 49e624e532993b50ab5c42cba3e1efc370919eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 07:47:05 +0100 Subject: [PATCH 014/348] Update WhyAdoptGRDB.md for FetchRequest --- Documentation/WhyAdoptGRDB.md | 45 ++++++++++++++++------------------- 1 file changed, 20 insertions(+), 25 deletions(-) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 75d3257e5..3d9f6322a 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -175,7 +175,7 @@ For further information about GRDB concurrency, check its detailed [Concurrency SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful. -GRDB provides high-level record methods that generate SQL for you: +GRDB records can generate SQL for you: ```swift // SELECT * FROM players ORDER BY score DESC LIMIT 10 @@ -196,7 +196,7 @@ let exAequoCount: Int = try Player .fetchCount(db) ``` -But you can *always* switch to SQL when you want to: +But you can always switch to SQL when you want to: ```swift let bestPlayers: [Player] = try Player.fetchAll(db, """ @@ -212,26 +212,14 @@ let exAequoCount: Int? = try Int.fetchOne(db, """ """, arguments: [maximumScore]) ``` -SQL is also welcome in high-level database observation tools like [FetchedRecordsController] and [RxGRDB]: +In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays: ```swift -SQLRequest("SELECT * FROM players ORDER BY score DESC LIMIT 10") - .asRequest(of: Player.self) - .rx - .fetchAll(in: dbQueue) - .subscribe(onNext: { players: [Player] in - print("Best 10 players have changed") - }) -``` - -You can of course deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays: - -```swift -let rows = try Row.fetchCursor(db, "SELECT * FROM players") +let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM players") while let row = try rows.next() { - let id: Int64 = row["id"] - let name: String = row["name"] - let score: Int = row["score"] + let id: Int64 = row[0] + let name: String = row[1] + let score: Int = row[2] } ``` @@ -239,15 +227,22 @@ When you feel like your code clarity would be enhanced by hiding your custom SQL ```swift extension Player { - static func customRequest(...) -> AnyTypedRequest { - return SQLRequest(""" - SELECT ... - """, arguments: ...) - .asRequestOf(Player.self) + static func customRequest(...) -> SQLRequest { + return SQLRequest("SELECT ...", arguments: ...) } } -let players = Player.customRequest(...).fetchAll(db) +let players = try Player.customRequest(...).fetchAll(db) +``` + +Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]: + +```swift +Player.customRequest(...) + .rx.fetchAll(in: dbQueue) + .subscribe(onNext: { players: [Player] in + print("Players have changed") + }) ``` --- From 15a0ea79b0f1c1ba694d30739f6dd7a045016035 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 18 Feb 2018 17:01:48 +0100 Subject: [PATCH 015/348] Drop IteratorCursor, use AnyCursor instead --- GRDB.xcodeproj/project.pbxproj | 6 -- GRDB/Core/Cursor.swift | 57 ++++++++----------- GRDBCipher.xcodeproj/project.pbxproj | 10 ---- GRDBCustom.xcodeproj/project.pbxproj | 6 -- TODO.md | 3 +- Tests/GRDBTests/AnyCursorTests.swift | 20 ++++++- Tests/GRDBTests/CursorTests.swift | 58 ++++++++++---------- Tests/GRDBTests/DropFirstCursorTests.swift | 10 ++-- Tests/GRDBTests/DropWhileCursorTests.swift | 8 +-- Tests/GRDBTests/EnumeratedCursorTests.swift | 2 +- Tests/GRDBTests/FilterCursorTests.swift | 4 +- Tests/GRDBTests/FlattenCursorTests.swift | 10 ++-- Tests/GRDBTests/IteratorCursorTests.swift | 27 --------- Tests/GRDBTests/MapCursorTests.swift | 2 +- Tests/GRDBTests/PrefixCursorTests.swift | 8 +-- Tests/GRDBTests/PrefixWhileCursorTests.swift | 8 +-- 16 files changed, 98 insertions(+), 141 deletions(-) delete mode 100644 Tests/GRDBTests/IteratorCursorTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5b5b41f10..f077d9133 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -76,8 +76,6 @@ 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393451DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393561DEE013C00A6B01F /* FilterCursorTests.swift */; }; @@ -775,7 +773,6 @@ 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -1651,7 +1648,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */, 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */, @@ -2414,7 +2410,6 @@ 56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */, 56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */, 5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, - 562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, 56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */, 56EE573E1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift in Sources */, @@ -2656,7 +2651,6 @@ 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 56D496681D813086008276D7 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, - 562393451DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 7afea0a74..555512181 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -28,8 +28,8 @@ extension Sequence { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { - return IteratorCursor(self).flatMap(transform) + public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + return AnyCursor(self).flatMap(transform) } } @@ -168,7 +168,7 @@ extension Cursor { /// If the number of elements to drop exceeds the number of elements in /// the cursor, the result is an empty cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropFirst(2)) /// // Prints "[3, 4, 5]" /// try print(numbers.dropFirst(10)) @@ -186,7 +186,7 @@ extension Cursor { /// /// The following example drops the first element from a cursor of integers. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropFirst()) /// // Prints "[2, 3, 4, 5]" /// @@ -203,7 +203,7 @@ extension Cursor { /// The cursor must be finite. If the number of elements to drop exceeds /// the number of elements in the cursor, the result is an empty array. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// try print(numbers.dropLast(10)) @@ -236,7 +236,7 @@ extension Cursor { /// /// The following example drops the last element from a cursor of integers. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.dropLast()) /// // Prints "[1, 2, 3, 4]" /// @@ -249,8 +249,8 @@ extension Cursor { /// Returns a cursor over the concatenated results of mapping transform /// over self. - public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { - return flatMap { try IteratorCursor(transform($0)) } + public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { + return flatMap { try AnyCursor(transform($0)) } } /// Returns a cursor over the concatenated results of mapping transform @@ -318,7 +318,7 @@ extension Cursor { /// If the maximum length exceeds the number of elements in the cursor, /// the result contains all the elements in the cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.prefix(2)) /// // Prints "[1, 2]" /// try print(numbers.prefix(10)) @@ -378,7 +378,7 @@ extension Cursor { /// elements in the cursor, the result contains all the elements in the /// cursor. /// - /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// let numbers = AnyCursor([1, 2, 3, 4, 5]) /// try print(numbers.suffix(2)) /// // Prints "[4, 5]" /// try print(numbers.suffix(10)) @@ -472,7 +472,7 @@ extension Cursor where Element: Cursor { extension Cursor where Element: Sequence { /// Returns the elements of this cursor of sequences, concatenated. - public func joined() -> FlattenCursor>> { + public func joined() -> FlattenCursor>> { return flatMap { $0 } } } @@ -518,6 +518,19 @@ public class AnyCursor : Cursor { element = base.next } + /// Creates a cursor that wraps a base iterator but whose type depends only + /// on the base iterator’s element type + public convenience init(iterator: I) where I.Element == Element { + var iterator = iterator + self.init { iterator.next() } + } + + /// Creates a cursor that wraps a base sequence but whose type depends only + /// on the base sequence’s element type + public convenience init(_ s: S) where S.Element == Element { + self.init(iterator: s.makeIterator()) + } + /// Creates a cursor that wraps the given closure in its next() method public init(_ body: @escaping () throws -> Element?) { element = body @@ -749,25 +762,3 @@ public final class PrefixWhileCursor : Cursor { return nil } } - -/// A Cursor whose elements are those of a sequence iterator. -public final class IteratorCursor : Cursor { - private var base: Base - - /// Creates a cursor from a sequence iterator. - public init(_ base: Base) { - self.base = base - } - - /// Creates a cursor from a sequence. - public init(_ s: S) where S.Iterator == Base { - self.base = s.makeIterator() - } - - /// Advances to the next element and returns it, or nil if no next - /// element exists. - /// :nodoc: - public func next() -> Base.Element? { - return base.next() - } -} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 6988346fe..bb104a6f2 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -141,10 +141,6 @@ 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934A1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934B1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; @@ -857,7 +853,6 @@ 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -1630,7 +1625,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */, 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */, @@ -2137,7 +2131,6 @@ 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */, 560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */, 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */, - 562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5698AC971DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5657AB4F1D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, @@ -2287,7 +2280,6 @@ 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */, - 562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5698AC981DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */, 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, @@ -2597,7 +2589,6 @@ 56176C741EACCCCA000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 5657AB3B1D108BA9006283EF /* FoundationDataTests.swift in Sources */, 5698AC081D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, - 5623934A1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56AFCA661CB1AA9900F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, @@ -2745,7 +2736,6 @@ 56176C7A1EACCCCB000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 5698AC091D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, - 5623934B1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 56AFCABD1CB1ABC800F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56AFCABE1CB1ABC800F48B96 /* DatabaseErrorTests.swift in Sources */, 56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d02cf9602..d287e61dc 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -23,8 +23,6 @@ 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; - 562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; - 5623934C1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */; }; 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 562393551DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393561DEE013C00A6B01F /* FilterCursorTests.swift */; }; @@ -556,7 +554,6 @@ 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IteratorCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; 562393561DEE013C00A6B01F /* FilterCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FilterCursorTests.swift; sourceTree = ""; }; 5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = ""; }; @@ -1302,7 +1299,6 @@ 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, - 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, 56CC9253201E094600CB597E /* PrefixCursorTests.swift */, 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */, @@ -1799,7 +1795,6 @@ F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, - 5623934C1DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, @@ -2085,7 +2080,6 @@ F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, 5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */, - 562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */, 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, diff --git a/TODO.md b/TODO.md index ae14caca0..9d6bde776 100644 --- a/TODO.md +++ b/TODO.md @@ -33,8 +33,7 @@ GRDB 3.0 - [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528 - [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. -- [ ] Drop IteratorCursor, use AnyCursor instead -<<<<<<< HEAD +- [X] Drop IteratorCursor, use AnyCursor instead - [X] Rename TypedRequest to FetchRequest, drop Request - [ ] Rename columnCount -> numberOfColumns - [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help? diff --git a/Tests/GRDBTests/AnyCursorTests.swift b/Tests/GRDBTests/AnyCursorTests.swift index 611bf94c4..7a8a86675 100644 --- a/Tests/GRDBTests/AnyCursorTests.swift +++ b/Tests/GRDBTests/AnyCursorTests.swift @@ -42,9 +42,9 @@ class AnyCursorTests: GRDBTestCase { } func testAnyCursorFromCursor() { - let base = IteratorCursor([0, 1]) + let base = AnyCursor([0, 1]) // This helper function makes sure AnyCursor initializer accepts any cursor, - // and not only IteratorCursor: + // and not only AnyCursor: func makeAnyCursor(_ cursor: C) -> AnyCursor where C.Element == Int { return AnyCursor(cursor) } @@ -75,4 +75,20 @@ class AnyCursorTests: GRDBTestCase { XCTFail() } } + + func testAnyCursorFromIterator() { + let cursor = AnyCursor(iterator: [0, 1].makeIterator()) + XCTAssertEqual(try cursor.next()!, 0) + XCTAssertEqual(try cursor.next()!, 1) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + + func testAnyCursorFromSequence() { + let cursor = AnyCursor([0, 1]) + XCTAssertEqual(try cursor.next()!, 0) + XCTAssertEqual(try cursor.next()!, 1) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } } diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index 81debde5d..f73f99419 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -12,15 +12,15 @@ private struct TestError : Error { } class CursorTests: GRDBTestCase { func testContainsEquatable() { - XCTAssertTrue(try IteratorCursor([1, 2]).contains(1)) - XCTAssertFalse(try IteratorCursor([1, 2]).contains(3)) + XCTAssertTrue(try AnyCursor([1, 2]).contains(1)) + XCTAssertFalse(try AnyCursor([1, 2]).contains(3)) } func testContainsClosure() { - XCTAssertTrue(try IteratorCursor([1, 2]).contains { $0 == 1 }) - XCTAssertFalse(try IteratorCursor([1, 2]).contains { $0 == 3 }) + XCTAssertTrue(try AnyCursor([1, 2]).contains { $0 == 1 }) + XCTAssertFalse(try AnyCursor([1, 2]).contains { $0 == 3 }) do { - _ = try IteratorCursor([1, 2]).contains { _ -> Bool in throw TestError() } + _ = try AnyCursor([1, 2]).contains { _ -> Bool in throw TestError() } XCTFail() } catch is TestError { } catch { @@ -29,10 +29,10 @@ class CursorTests: GRDBTestCase { } func testDropLast() { - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5]) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3]) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(10) == []) - XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3]) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast(10) == []) + XCTAssertTrue(try AnyCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4]) } func testContainsIsLazy() { @@ -55,8 +55,8 @@ class CursorTests: GRDBTestCase { } func testFirst() { - XCTAssertEqual(try IteratorCursor([1, 2]).first { $0 == 1 }!, 1) - XCTAssertTrue(try IteratorCursor([1, 2]).first { $0 == 3 } == nil) + XCTAssertEqual(try AnyCursor([1, 2]).first { $0 == 1 }!, 1) + XCTAssertTrue(try AnyCursor([1, 2]).first { $0 == 3 } == nil) } func testFirstIsLazy() { @@ -80,14 +80,14 @@ class CursorTests: GRDBTestCase { #if swift(>=4.1) func testCompactMap() { - let cursor = IteratorCursor(["1", "foo", "2"]).compactMap { Int($0) } + let cursor = AnyCursor(["1", "foo", "2"]).compactMap { Int($0) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertTrue(try cursor.next() == nil) // end } #else func testFlatMapOfOptional() { - let cursor = IteratorCursor(["1", "foo", "2"]).flatMap { Int($0) } + let cursor = AnyCursor(["1", "foo", "2"]).flatMap { Int($0) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertTrue(try cursor.next() == nil) // end @@ -95,7 +95,7 @@ class CursorTests: GRDBTestCase { #endif func testForEach() throws { - let cursor = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) var ints: [Int] = [] try cursor.forEach { ints.append($0) } XCTAssertEqual(ints, [1, 2]) @@ -121,66 +121,66 @@ class CursorTests: GRDBTestCase { func testJoinedWithSeparator() throws { do { - let x = try IteratorCursor([String]()).joined() + let x = try AnyCursor([String]()).joined() XCTAssertEqual(x, "") } do { - let x = try IteratorCursor([String]()).joined(separator: "><") + let x = try AnyCursor([String]()).joined(separator: "><") XCTAssertEqual(x, "") } do { - let x = try IteratorCursor(["foo"]).joined() + let x = try AnyCursor(["foo"]).joined() XCTAssertEqual(x, "foo") } do { - let x = try IteratorCursor(["foo"]).joined(separator: "><") + let x = try AnyCursor(["foo"]).joined(separator: "><") XCTAssertEqual(x, "foo") } do { - let x = try IteratorCursor(["foo", "bar", "baz"]).joined() + let x = try AnyCursor(["foo", "bar", "baz"]).joined() XCTAssertEqual(x, "foobarbaz") } do { - let x = try IteratorCursor(["foo", "bar", "baz"]).joined(separator: "><") + let x = try AnyCursor(["foo", "bar", "baz"]).joined(separator: "><") XCTAssertEqual(x, "foo>), 1) + XCTAssertEqual(try AnyCursor([1, 2, 3]).max(), 3) + XCTAssertEqual(try AnyCursor([1, 2, 3]).max(by: >), 1) } func testMin() { - XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(), 1) - XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(by: >), 3) + XCTAssertEqual(try AnyCursor([1, 2, 3]).min(), 1) + XCTAssertEqual(try AnyCursor([1, 2, 3]).min(by: >), 3) } func testReduce() throws { - let cursor = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) let squareSum = try cursor.reduce(0) { (acc, int) in acc + int * int } XCTAssertEqual(squareSum, 5) } func testReduceInto() throws { - let cursor = IteratorCursor([1, 2]) + let cursor = AnyCursor([1, 2]) let squareSum = try cursor.reduce(into: 0) { (acc, int) in acc += int * int } XCTAssertEqual(squareSum, 5) } func testSuffix() throws { do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(0) XCTAssertTrue(suffix == []) } do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(2) XCTAssertTrue(suffix == [4, 5]) } do { - let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = AnyCursor([1, 2, 3, 4, 5]) let suffix = try cursor.suffix(10) XCTAssertTrue(suffix == [1, 2, 3, 4, 5]) } diff --git a/Tests/GRDBTests/DropFirstCursorTests.swift b/Tests/GRDBTests/DropFirstCursorTests.swift index 889b21c5f..2343305c5 100644 --- a/Tests/GRDBTests/DropFirstCursorTests.swift +++ b/Tests/GRDBTests/DropFirstCursorTests.swift @@ -13,7 +13,7 @@ class DropFirstCursorTests: GRDBTestCase { func testDropFirstCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(0) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -24,7 +24,7 @@ class DropFirstCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(2) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 4) @@ -33,13 +33,13 @@ class DropFirstCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(10) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst() try XCTAssertEqual(cursor.next()!, 2) try XCTAssertEqual(cursor.next()!, 3) @@ -70,7 +70,7 @@ class DropFirstCursorTests: GRDBTestCase { } func testDropFirstChain() throws { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.dropFirst(1).dropFirst(1) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 4) diff --git a/Tests/GRDBTests/DropWhileCursorTests.swift b/Tests/GRDBTests/DropWhileCursorTests.swift index 63e9b0832..7cbcc336d 100644 --- a/Tests/GRDBTests/DropWhileCursorTests.swift +++ b/Tests/GRDBTests/DropWhileCursorTests.swift @@ -13,7 +13,7 @@ class DropWhileCursorTests: GRDBTestCase { func testDropWhileCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 3) try XCTAssertEqual(cursor.next()!, 1) @@ -22,13 +22,13 @@ class DropWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in true }) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in false }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -39,7 +39,7 @@ class DropWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.drop(while: { _ in throw TestError() }) _ = try cursor.next() XCTFail() diff --git a/Tests/GRDBTests/EnumeratedCursorTests.swift b/Tests/GRDBTests/EnumeratedCursorTests.swift index b89211877..c4625be92 100644 --- a/Tests/GRDBTests/EnumeratedCursorTests.swift +++ b/Tests/GRDBTests/EnumeratedCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class EnumeratedCursorTests: GRDBTestCase { func testEnumeratedCursorFromCursor() throws { - let base = IteratorCursor(["foo", "bar"]) + let base = AnyCursor(["foo", "bar"]) let cursor = base.enumerated() var (n, x) = try cursor.next()! XCTAssertEqual(x, "foo") diff --git a/Tests/GRDBTests/FilterCursorTests.swift b/Tests/GRDBTests/FilterCursorTests.swift index 10b68d8f1..dbde9254e 100644 --- a/Tests/GRDBTests/FilterCursorTests.swift +++ b/Tests/GRDBTests/FilterCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class FilterCursorTests: GRDBTestCase { func testFilterCursorFromCursor() { - let base = IteratorCursor([1, 2, 3, 4]) + let base = AnyCursor([1, 2, 3, 4]) let cursor = base.filter { $0 % 2 == 0 } XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 4) @@ -39,7 +39,7 @@ class FilterCursorTests: GRDBTestCase { } func testThrowingFilterCursorFromCursor() { - let base = IteratorCursor([0, 1]) + let base = AnyCursor([0, 1]) let cursor = base.filter { if $0 > 0 { throw TestError() } return true diff --git a/Tests/GRDBTests/FlattenCursorTests.swift b/Tests/GRDBTests/FlattenCursorTests.swift index 41a160879..f2fa00338 100644 --- a/Tests/GRDBTests/FlattenCursorTests.swift +++ b/Tests/GRDBTests/FlattenCursorTests.swift @@ -10,7 +10,7 @@ import XCTest class FlattenCursorTests: GRDBTestCase { func testFlatMapOfSequence() { - let cursor = IteratorCursor([1, 2]).flatMap { [$0, $0+1] } + let cursor = AnyCursor([1, 2]).flatMap { [$0, $0+1] } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -20,7 +20,7 @@ class FlattenCursorTests: GRDBTestCase { } func testFlatMapOfCursor() { - let cursor = IteratorCursor([1, 2]).flatMap { IteratorCursor([$0, $0+1]) } + let cursor = AnyCursor([1, 2]).flatMap { AnyCursor([$0, $0+1]) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -30,7 +30,7 @@ class FlattenCursorTests: GRDBTestCase { } func testSequenceFlatMapOfCursor() { - let cursor = [1, 2].flatMap { IteratorCursor([$0, $0+1]) } + let cursor = [1, 2].flatMap { AnyCursor([$0, $0+1]) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -40,7 +40,7 @@ class FlattenCursorTests: GRDBTestCase { } func testJoinedSequences() { - let cursor = IteratorCursor([[1, 2], [2, 3]]).joined() + let cursor = AnyCursor([[1, 2], [2, 3]]).joined() XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) @@ -50,7 +50,7 @@ class FlattenCursorTests: GRDBTestCase { } func testJoinedCursors() { - let cursor = IteratorCursor([IteratorCursor([1, 2]), IteratorCursor([2, 3])]).joined() + let cursor = AnyCursor([AnyCursor([1, 2]), AnyCursor([2, 3])]).joined() XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertEqual(try cursor.next()!, 2) diff --git a/Tests/GRDBTests/IteratorCursorTests.swift b/Tests/GRDBTests/IteratorCursorTests.swift deleted file mode 100644 index 39b01dd8f..000000000 --- a/Tests/GRDBTests/IteratorCursorTests.swift +++ /dev/null @@ -1,27 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite -#else - import GRDB -#endif - -class IteratorCursorTests: GRDBTestCase { - - func testIteratorCursorFromIterator() { - let cursor = IteratorCursor([0, 1].makeIterator()) - XCTAssertEqual(cursor.next()!, 0) - XCTAssertEqual(cursor.next()!, 1) - XCTAssertTrue(cursor.next() == nil) // end - XCTAssertTrue(cursor.next() == nil) // past the end - } - - func testIteratorCursorFromSequence() { - let cursor = IteratorCursor([0, 1]) - XCTAssertEqual(cursor.next()!, 0) - XCTAssertEqual(cursor.next()!, 1) - XCTAssertTrue(cursor.next() == nil) // end - XCTAssertTrue(cursor.next() == nil) // past the end - } -} diff --git a/Tests/GRDBTests/MapCursorTests.swift b/Tests/GRDBTests/MapCursorTests.swift index 52789379c..56a647325 100644 --- a/Tests/GRDBTests/MapCursorTests.swift +++ b/Tests/GRDBTests/MapCursorTests.swift @@ -12,7 +12,7 @@ private struct TestError : Error { } class MapCursorTests: GRDBTestCase { func testMap() { - let base = IteratorCursor([1, 2]) + let base = AnyCursor([1, 2]) let cursor = base.map { $0 * $0 } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 4) diff --git a/Tests/GRDBTests/PrefixCursorTests.swift b/Tests/GRDBTests/PrefixCursorTests.swift index fdffab97d..5ee9d2094 100644 --- a/Tests/GRDBTests/PrefixCursorTests.swift +++ b/Tests/GRDBTests/PrefixCursorTests.swift @@ -13,13 +13,13 @@ class PrefixCursorTests: GRDBTestCase { func testPrefixCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(0) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(2) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -27,7 +27,7 @@ class PrefixCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(10) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -60,7 +60,7 @@ class PrefixCursorTests: GRDBTestCase { } func testPrefixCursorChain() throws { - let base = IteratorCursor([1, 2, 3, 4, 5]) + let base = AnyCursor([1, 2, 3, 4, 5]) let cursor = base.prefix(2).prefix(1) try XCTAssertEqual(cursor.next()!, 1) XCTAssertTrue(try cursor.next() == nil) // end diff --git a/Tests/GRDBTests/PrefixWhileCursorTests.swift b/Tests/GRDBTests/PrefixWhileCursorTests.swift index 9c0228938..9300b5faf 100644 --- a/Tests/GRDBTests/PrefixWhileCursorTests.swift +++ b/Tests/GRDBTests/PrefixWhileCursorTests.swift @@ -13,7 +13,7 @@ class PrefixWhileCursorTests: GRDBTestCase { func testPrefixWhileCursorFromCursor() throws { do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { $0 < 3 }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -21,7 +21,7 @@ class PrefixWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in true }) try XCTAssertEqual(cursor.next()!, 1) try XCTAssertEqual(cursor.next()!, 2) @@ -32,13 +32,13 @@ class PrefixWhileCursorTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in false }) XCTAssertTrue(try cursor.next() == nil) // end XCTAssertTrue(try cursor.next() == nil) // past the end } do { - let base = IteratorCursor([1, 2, 3, 1, 5]) + let base = AnyCursor([1, 2, 3, 1, 5]) let cursor = base.prefix(while: { _ in throw TestError() }) _ = try cursor.next() XCTFail() From 4faa9964bddd09ed78afb6eb3eb385340b581514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 08:15:49 +0100 Subject: [PATCH 016/348] Make AnyCursor final --- GRDB/Core/Cursor.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 555512181..8de34aebe 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -509,7 +509,7 @@ extension Cursor where Element: StringProtocol { /// This cursor forwards its next() method to an arbitrary underlying cursor /// having the same Element type, hiding the specifics of the underlying /// cursor. -public class AnyCursor : Cursor { +public final class AnyCursor : Cursor { private let element: () throws -> Element? /// Creates a cursor that wraps a base cursor but whose type depends only on From e8d0af93fcfdc77c2fe65c1b36bc89bb8ea8e9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 08:17:55 +0100 Subject: [PATCH 017/348] Cursor changelog --- CHANGELOG.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1470197e4..e153e9f9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,13 @@ Release Notes ### Breaking Changes -- `Request` and `TypedRequest` protocols have been merged into `FetchRequest`. +- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([311](https://github.com/groue/GRDB.swift/pull/311)) +- The `IteratorCursor` type has been removed. Use `AnyCursor` instead. + ### API diff -FetchRequest +**FetchRequest** ```diff +protocol FetchRequest { @@ -99,6 +101,17 @@ FetchRequest +extension QueryInterfaceRequest : FetchRequest { } ``` +**Cursor** + +```diff + final class AnyCursor : Cursor { ++ convenience init(iterator: I) where I.Element == Element ++ convenience init(_ s: S) where S.Element == Element + } +-final class IteratorCursor : Cursor { } +``` + + ## 2.9.0 Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.8.0...v2.9.0) From 07634229f9c7697e73a175ac547b4f1ca00ccd5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 12:44:34 +0100 Subject: [PATCH 018/348] GRDB3 TODO --- TODO.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/TODO.md b/TODO.md index 9d6bde776..5fc8da458 100644 --- a/TODO.md +++ b/TODO.md @@ -26,11 +26,10 @@ GRDB 3.0 - [ ] Do one of those two: 1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API. 2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type. -- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column) +- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column). If so, allow type to change the set of changed columns. - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename Request to FetchRequest, because Request is a bad name: https://github.com/swift-server/http/pull/7#issuecomment-308448528 - [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. - [X] Drop IteratorCursor, use AnyCursor instead From ba6a026cdca084a64e568668631556bb2e5c3a5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 13:17:51 +0100 Subject: [PATCH 019/348] Rename RowConvertible to DecodableRecord --- Documentation/WhyAdoptGRDB.md | 6 +- GRDB.xcodeproj/project.pbxproj | 90 +++++++------- GRDB/Core/Database+Schema.swift | 2 +- GRDB/Core/FetchRequest.swift | 2 +- GRDB/Core/Row.swift | 4 +- GRDB/Legacy/Fixits-0-90-1.swift | 4 +- ....swift => DecodableRecord+Decodable.swift} | 2 +- ...ift => DecodableRecord+TableMapping.swift} | 6 +- ...onvertible.swift => DecodableRecord.swift} | 18 +-- GRDB/Record/FetchedRecordsController.swift | 14 +-- GRDB/Record/Record.swift | 2 +- GRDB/Record/RecordBox.swift | 6 +- GRDB/Record/TableMapping.swift | 2 +- GRDBCipher.xcodeproj/project.pbxproj | 102 ++++++++-------- GRDBCustom.xcodeproj/project.pbxproj | 78 ++++++------ .../Issue156.playground/Contents.swift | 2 +- Playgrounds/Tour.playground/Contents.swift | 4 +- README.md | 113 ++++++++++-------- .../GRDBTests/CompilationProtocolTests.swift | 6 +- ...leRecord+QueryInterfaceRequestTests.swift} | 8 +- ...ft => DecodableRecordDecodableTests.swift} | 38 +++--- ...Tests.swift => DecodableRecordTests.swift} | 4 +- Tests/GRDBTests/FTS3RecordTests.swift | 2 +- Tests/GRDBTests/FTS4RecordTests.swift | 2 +- Tests/GRDBTests/FTS5RecordTests.swift | 2 +- Tests/GRDBTests/FetchRequestTests.swift | 2 +- .../FetchedRecordsControllerTests.swift | 4 +- Tests/GRDBTests/JoinSupportTests.swift | 16 +-- .../MutablePersistableChangesTests.swift | 2 +- Tests/GRDBTests/RecordBoxTests.swift | 2 +- Tests/GRDBTests/RecordUniqueIndexTests.swift | 2 +- .../GRDBTests/TransactionObserverTests.swift | 4 +- Tests/Performance/PerformanceTests.swift | 2 +- Tests/generatePerformanceReport.rb | 2 +- 34 files changed, 282 insertions(+), 273 deletions(-) rename GRDB/Record/{RowConvertible+Decodable.swift => DecodableRecord+Decodable.swift} (99%) rename GRDB/Record/{RowConvertible+TableMapping.swift => DecodableRecord+TableMapping.swift} (97%) rename GRDB/Record/{RowConvertible.swift => DecodableRecord.swift} (95%) rename Tests/GRDBTests/{RowConvertible+QueryInterfaceRequestTests.swift => DecodableRecord+QueryInterfaceRequestTests.swift} (97%) rename Tests/GRDBTests/{RowConvertibleDecodableTests.swift => DecodableRecordDecodableTests.swift} (89%) rename Tests/GRDBTests/{RowConvertibleTests.swift => DecodableRecordTests.swift} (99%) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 3d9f6322a..cb51bf465 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -65,10 +65,10 @@ struct Place { } ``` -By adopting the [RowConvertible] protocol, places can be loaded from SQL requests: +By adopting the [DecodableRecord] protocol, places can be loaded from SQL requests: ```swift -extension Place: RowConvertible { ... } +extension Place: DecodableRecord { ... } let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] ``` @@ -265,7 +265,7 @@ Happy GRDB! :gift: [GRDBObjc]: http://github.com/groue/GRDBObjc [Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [Realm]: http://realm.io -[RowConvertible]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[DecodableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [RxSwift]: https://github.com/ReactiveX/RxSwift [SQLite.swift]: http://github.com/stephencelis/SQLite.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index f077d9133..910714da5 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -95,7 +95,7 @@ 562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; - 56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56300B621C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56300B6C1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; @@ -211,7 +211,7 @@ 5659F4A01EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A31EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A61EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 565B0FF01BBC7D980098DE03 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; 565EFAF21D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; @@ -276,9 +276,9 @@ 5674A6F41F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; 5674A6F81F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; 5674A6F91F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FB1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A6FF1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6FB1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A6FF1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A7001F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; @@ -288,8 +288,8 @@ 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7201F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; + 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; 567517C920131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; 567517CA20131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; @@ -459,9 +459,9 @@ 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F11EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F41EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F71EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; @@ -513,7 +513,7 @@ 56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 56D496681D813086008276D7 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56D4966A1D813086008276D7 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; @@ -550,7 +550,7 @@ 56D496901D81316E008276D7 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; - 56D496931D81316E008276D7 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56D496931D81316E008276D7 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 56D496951D81317B008276D7 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; @@ -577,9 +577,9 @@ 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; 56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; - 56D51D001EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D031EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D061EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D001EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D031EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D061EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -783,7 +783,7 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; @@ -819,7 +819,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -849,13 +849,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; @@ -983,7 +983,7 @@ 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -997,7 +997,7 @@ 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRecordStructTests.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1261,11 +1261,11 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -1330,13 +1330,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, ); - name = RowConvertible; + name = DecodableRecord; sourceTree = ""; }; 569530FA1C9067CC00CF1A2B /* Crash */ = { @@ -1491,12 +1491,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680520F201320E600E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, 56176C9C1EACEA8C000F3F2B /* TableMapping */, ); name = Record; @@ -1548,14 +1548,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 567517C720131B220094BF41 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, 560D92461C672C4B00F4F92B /* TableMapping.swift */, ); path = Record; @@ -2170,7 +2170,7 @@ files = ( 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D51D061EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D061EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 565490E41D5AE252005622CB /* TableMapping.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, @@ -2206,7 +2206,7 @@ 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6FF1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FF1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, @@ -2238,7 +2238,7 @@ 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, 56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F71EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -2328,7 +2328,7 @@ 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56D51D031EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D031EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */, 567517C920131B220094BF41 /* RecordBox.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, @@ -2343,12 +2343,12 @@ 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, - 5674A7001F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A7001F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, - 56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F41EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, @@ -2439,7 +2439,7 @@ 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, - 56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56300B621C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, @@ -2465,7 +2465,7 @@ 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 5674A72D1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */, @@ -2477,7 +2477,7 @@ 5698AC441DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5698ACBA1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56176C6F1EACCCC9000F3F2B /* FTS5TokenizerTests.swift in Sources */, - 565B0FF01BBC7D980098DE03 /* RowConvertibleTests.swift in Sources */, + 565B0FF01BBC7D980098DE03 /* DecodableRecordTests.swift in Sources */, 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2575,7 +2575,7 @@ 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 56D496AE1D813345008276D7 /* DatabasePoolCollationTests.swift in Sources */, 5698AC491DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, - 56D496931D81316E008276D7 /* RowConvertibleTests.swift in Sources */, + 56D496931D81316E008276D7 /* DecodableRecordTests.swift in Sources */, 56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */, 56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */, @@ -2613,7 +2613,7 @@ 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, - 5674A72A1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */, @@ -2650,7 +2650,7 @@ 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 56D496681D813086008276D7 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, @@ -2691,7 +2691,7 @@ 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, - 56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F11EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2728,7 +2728,7 @@ 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D2F1DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, - 56D51D001EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D001EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2756,7 +2756,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FB1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FB1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 24a4d7b42..602be97d6 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -325,7 +325,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : RowConvertible { +public struct ColumnInfo : DecodableRecord { let cid: Int /// The column name diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 872128408..e8db16821 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,6 +1,6 @@ /// The protocol for all types that define a way to fetch database content. /// -/// struct Player: RowConvertible { ... } +/// struct Player: DecodableRecord { ... } /// let request: ... // Some FetchRequest that fetches Player /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index f999ba905..8e222fb08 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -482,7 +482,7 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record { + public subscript(_ scope: String) -> Record { guard let scopedRow = scoped(on: scope) else { // Programmer error fatalError("no such scope: \(scope)") @@ -498,7 +498,7 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record? { + public subscript(_ scope: String) -> Record? { guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else { return nil } diff --git a/GRDB/Legacy/Fixits-0-90-1.swift b/GRDB/Legacy/Fixits-0-90-1.swift index 12835dd45..e3f6f7b35 100644 --- a/GRDB/Legacy/Fixits-0-90-1.swift +++ b/GRDB/Legacy/Fixits-0-90-1.swift @@ -30,7 +30,7 @@ extension QueryInterfaceRequest { public func fetch(_ db: Database) -> Any { preconditionFailure() } } -extension RowConvertible { +extension DecodableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") @@ -39,7 +39,7 @@ extension RowConvertible { public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } -extension RowConvertible where Self: TableMapping { +extension DecodableRecord where Self: TableMapping { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") diff --git a/GRDB/Record/RowConvertible+Decodable.swift b/GRDB/Record/DecodableRecord+Decodable.swift similarity index 99% rename from GRDB/Record/RowConvertible+Decodable.swift rename to GRDB/Record/DecodableRecord+Decodable.swift index b8ba94af2..5871de4a6 100644 --- a/GRDB/Record/RowConvertible+Decodable.swift +++ b/GRDB/Record/DecodableRecord+Decodable.swift @@ -249,7 +249,7 @@ private struct RowDecoder: Decoder { } } -extension RowConvertible where Self: Decodable { +extension DecodableRecord where Self: Decodable { /// Initializes a record from `row`. public init(row: Row) { try! self.init(from: RowDecoder(row: row, codingPath: [])) diff --git a/GRDB/Record/RowConvertible+TableMapping.swift b/GRDB/Record/DecodableRecord+TableMapping.swift similarity index 97% rename from GRDB/Record/RowConvertible+TableMapping.swift rename to GRDB/Record/DecodableRecord+TableMapping.swift index 409ac2709..38872aeb7 100644 --- a/GRDB/Record/RowConvertible+TableMapping.swift +++ b/GRDB/Record/DecodableRecord+TableMapping.swift @@ -1,4 +1,4 @@ -extension RowConvertible where Self: TableMapping { +extension DecodableRecord where Self: TableMapping { // MARK: Fetching All @@ -59,7 +59,7 @@ extension RowConvertible where Self: TableMapping { } } -extension RowConvertible where Self: TableMapping { +extension DecodableRecord where Self: TableMapping { // MARK: Fetching by Single-Column Primary Key @@ -119,7 +119,7 @@ extension RowConvertible where Self: TableMapping { } } -extension RowConvertible where Self: TableMapping { +extension DecodableRecord where Self: TableMapping { // MARK: Fetching by Key diff --git a/GRDB/Record/RowConvertible.swift b/GRDB/Record/DecodableRecord.swift similarity index 95% rename from GRDB/Record/RowConvertible.swift rename to GRDB/Record/DecodableRecord.swift index d85efe7d2..cb3e4b1b0 100644 --- a/GRDB/Record/RowConvertible.swift +++ b/GRDB/Record/DecodableRecord.swift @@ -4,7 +4,7 @@ import SQLite3 #endif -/// Types that adopt RowConvertible can be initialized from a database Row. +/// Types that adopt DecodableRecord can be initialized from a database Row. /// /// let row = try Row.fetchOne(db, "SELECT ...")! /// let player = Player(row) @@ -21,8 +21,8 @@ /// try Player.fetchAll(statement, arguments:...) // [Player] /// try Player.fetchOne(statement, arguments:...) // Player? /// -/// RowConvertible is adopted by Record. -public protocol RowConvertible { +/// DecodableRecord is adopted by Record. +public protocol DecodableRecord { /// Creates a record from `row`. /// @@ -34,11 +34,11 @@ public protocol RowConvertible { /// A cursor of records. For example: /// -/// struct Player : RowConvertible { ... } +/// struct Player : DecodableRecord { ... } /// try dbQueue.inDatabase { db in /// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor : Cursor { private let statement: SelectStatement private let row: Row // Reused for performance private let sqliteStatement: SQLiteStatement @@ -67,7 +67,7 @@ public final class RecordCursor : Cursor { } } -extension RowConvertible { +extension DecodableRecord { // MARK: Fetching From SelectStatement @@ -125,7 +125,7 @@ extension RowConvertible { } } -extension RowConvertible { +extension DecodableRecord { // MARK: Fetching From SQL @@ -183,9 +183,9 @@ extension RowConvertible { } } -extension FetchRequest where RowDecoder: RowConvertible { +extension FetchRequest where RowDecoder: DecodableRecord { - // MARK: Fetching Record and RowConvertible + // MARK: Fetching Record and DecodableRecord /// A cursor over fetched records. /// diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 4892eb859..280db9460 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -9,7 +9,7 @@ import Foundation /// /// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for /// more information. -public final class FetchedRecordsController { +public final class FetchedRecordsController { // MARK: - Initialization @@ -510,7 +510,7 @@ extension FetchedRecordsController where Record: TableMapping { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver : TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions @@ -861,8 +861,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item = (Item, Item) -> Bool -private typealias ItemComparatorFactory = (Database) throws -> ItemComparator +private typealias ItemComparator = (Item, Item) -> Bool +private typealias ItemComparatorFactory = (Database) throws -> ItemComparator extension FetchedRecordsController { @@ -915,7 +915,7 @@ extension FetchedRecordsController where Record: MutablePersistable { } } -private enum ItemChange { +private enum ItemChange { case insertion(item: Item, indexPath: IndexPath) case deletion(item: Item, indexPath: IndexPath) case move(item: Item, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) @@ -1010,7 +1010,7 @@ extension FetchedRecordChange: CustomStringConvertible { } /// A section given by a FetchedRecordsController. -public struct FetchedRecordsSectionInfo { +public struct FetchedRecordsSectionInfo { fileprivate let controller: FetchedRecordsController /// The number of records (rows) in the section. @@ -1035,7 +1035,7 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : RowConvertible, Equatable { +private final class Item : DecodableRecord, Equatable { let row: Row // Records are lazily loaded diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index b2fddac34..cbaf30d13 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : RowConvertible, TableMapping, Persistable { +open class Record : DecodableRecord, TableMapping, Persistable { // MARK: - Initializers diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift index cccfa4794..8a368fcbe 100644 --- a/GRDB/Record/RecordBox.swift +++ b/GRDB/Record/RecordBox.swift @@ -2,7 +2,7 @@ /// changes tracking provided by the Record class. /// /// // A Regular record struct -/// struct Player: RowConvertible, MutablePersistable, Codable { +/// struct Player: DecodableRecord, MutablePersistable, Codable { /// static let databaseTableName = "players" /// var id: Int64? /// var name: String @@ -22,7 +22,7 @@ /// playerRecord.persistentChangedValues["score"] // 100 (the old value) /// } @available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") -public final class RecordBox: Record { +public final class RecordBox: Record { /// The boxed record public var value: T @@ -32,7 +32,7 @@ public final class RecordBox: Record { super.init() } - // MARK: - RowConvertible + // MARK: - DecodableRecord /// Initializes a record from `row`. public required init(row: Row) { diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableMapping.swift index 250ba39aa..1029fd30a 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableMapping.swift @@ -1,7 +1,7 @@ /// Types that adopt TableMapping declare a particular relationship with /// a database table. /// -/// Types that adopt both TableMapping and RowConvertible are granted with +/// Types that adopt both TableMapping and DecodableRecord are granted with /// built-in methods that allow to fetch instances identified by key: /// /// try Player.fetchOne(db, key: 123) // Player? diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index bb104a6f2..52531e732 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -60,7 +60,7 @@ 560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 560FC57F1CB00B880014AA8E /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; @@ -72,7 +72,7 @@ 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 560FC5921CB00B880014AA8E /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; @@ -305,7 +305,7 @@ 5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 5671563D1CB16729007DC145 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 567156411CB16729007DC145 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; @@ -319,7 +319,7 @@ 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 567156511CB16729007DC145 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; @@ -356,8 +356,8 @@ 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F71F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; 5674A6FA1F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FE1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A7011F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6FE1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A7011F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70D1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; @@ -372,10 +372,10 @@ 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; 5674A7221F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; 5674A7241F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7281F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72B1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72C1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A72E1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; + 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A72E1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; @@ -568,7 +568,7 @@ 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; @@ -582,7 +582,7 @@ 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56AFCA5E1CB1AA9900F48B96 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -628,7 +628,7 @@ 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; @@ -642,7 +642,7 @@ 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + 56AFCAB71CB1ABC800F48B96 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -710,8 +710,8 @@ 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F21EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F51EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5021EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -736,8 +736,8 @@ 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D011EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D041EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D011EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D041EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -863,7 +863,7 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; @@ -895,7 +895,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -926,13 +926,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1044,7 +1044,7 @@ 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -1056,7 +1056,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1313,11 +1313,11 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -1382,13 +1382,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, ); - name = RowConvertible; + name = DecodableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1528,12 +1528,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73EB203DA29B000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680521C2013296800E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, 56176C9C1EACEA8C000F3F2B /* TableMapping */, ); name = Record; @@ -1585,14 +1585,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 5680520A2013209300E87861 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, 560D92461C672C4B00F4F92B /* TableMapping.swift */, ); path = Record; @@ -1994,7 +1994,7 @@ 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F21EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2033,7 +2033,7 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 56D51D011EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D011EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2060,7 +2060,7 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A7011F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A7011F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2147,7 +2147,7 @@ 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, - 560FC57F1CB00B880014AA8E /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, @@ -2163,7 +2163,7 @@ 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, - 5674A72C1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2180,7 +2180,7 @@ 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393311DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, - 560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */, + 560FC5921CB00B880014AA8E /* DecodableRecordTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5657AB371D108BA9006283EF /* FoundationDataTests.swift in Sources */, 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */, @@ -2292,7 +2292,7 @@ 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */, - 5671563D1CB16729007DC145 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, 5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, @@ -2310,7 +2310,7 @@ 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, - 5674A72E1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72E1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2323,7 +2323,7 @@ 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, - 567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */, + 567156511CB16729007DC145 /* DecodableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2388,7 +2388,7 @@ 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F51EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2427,7 +2427,7 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 56D51D041EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D041EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2454,7 +2454,7 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FE1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FE1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2528,7 +2528,7 @@ 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */, 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */, @@ -2558,7 +2558,7 @@ 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, - 5674A72B1F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2570,7 +2570,7 @@ 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, - 56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */, + 56AFCA5E1CB1AA9900F48B96 /* DecodableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2682,7 +2682,7 @@ 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */, 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, - 56AFCAA51CB1ABC800F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, @@ -2705,7 +2705,7 @@ 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 5674A7281F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */, 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2721,7 +2721,7 @@ 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, 56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */, - 56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */, + 56AFCAB71CB1ABC800F48B96 /* DecodableRecordTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5623931E1DECC02000A6B01F /* RowFetchTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index d287e61dc..bd0f1dcba 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -119,8 +119,8 @@ 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F51F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; 5674A6F61F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FC1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; - 5674A6FD1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */; }; + 5674A6FC1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A6FD1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; @@ -129,8 +129,8 @@ 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7271F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; - 5674A7291F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */; }; + 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -238,8 +238,8 @@ 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; }; 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; 56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; - 56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; + 56CEB4F31EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F61EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -262,8 +262,8 @@ 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D021EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; - 56D51D051EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */; }; + 56D51D021EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D051EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -423,12 +423,12 @@ F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80EB1CFB3016003DC1BA /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + F3BA80EB1CFB3016003DC1BA /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* RowCopiedFromStatementTests.swift */; }; F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */; }; + F3BA80F01CFB3017003DC1BA /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; }; @@ -457,12 +457,12 @@ F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA811B1CFB305F003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */; }; + F3BA811B1CFB305F003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; @@ -564,7 +564,7 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; @@ -596,7 +596,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertibleTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -626,13 +626,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RowConvertible+Decodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowConvertibleDecodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -736,7 +736,7 @@ 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9253201E094600CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -748,7 +748,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "RowConvertible+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -987,11 +987,11 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56300B601C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -1056,13 +1056,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* RowConvertible */ = { + 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* RowConvertibleDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* RowConvertibleTests.swift */, + 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, ); - name = RowConvertible; + name = DecodableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1202,12 +1202,12 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( + 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73E7203DA278000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 568052182013295100E87861 /* RecordBoxTests.swift */, - 5674A7251F30A8EF0095F066 /* RowConvertible */, 56176C9C1EACEA8C000F3F2B /* TableMapping */, ); name = Record; @@ -1259,14 +1259,14 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( + 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, + 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 568052072013206F00E87861 /* RecordBox.swift */, - 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */, - 5674A6F21F307F600095F066 /* RowConvertible+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* RowConvertible+TableMapping.swift */, 560D92461C672C4B00F4F92B /* TableMapping.swift */, ); path = Record; @@ -1697,7 +1697,7 @@ 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F61EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -1737,7 +1737,7 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D051EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D051EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -1763,7 +1763,7 @@ 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FD1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FD1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -1802,7 +1802,7 @@ 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */, 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */, - F3BA81161CFB305E003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */, @@ -1849,7 +1849,7 @@ 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, - F3BA80EB1CFB3016003DC1BA /* RowConvertibleTests.swift in Sources */, + F3BA80EB1CFB3016003DC1BA /* DecodableRecordTests.swift in Sources */, F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, @@ -1867,7 +1867,7 @@ 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, - 5674A7291F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, @@ -1944,7 +1944,7 @@ 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */, + 56CEB4F31EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -1984,7 +1984,7 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D021EA789FA0074638A /* RowConvertible+TableMapping.swift in Sources */, + 56D51D021EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -2010,7 +2010,7 @@ 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FC1F307F600095F066 /* RowConvertible+Decodable.swift in Sources */, + 5674A6FC1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2107,14 +2107,14 @@ 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, - F3BA80F01CFB3017003DC1BA /* RowConvertibleTests.swift in Sources */, + F3BA80F01CFB3017003DC1BA /* DecodableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, - 5674A7271F30A9090095F066 /* RowConvertibleDecodableTests.swift in Sources */, + 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, @@ -2163,7 +2163,7 @@ 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, - F3BA811B1CFB305F003DC1BA /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + F3BA811B1CFB305F003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Playgrounds/Issue156.playground/Contents.swift index f07131dcf..e34392e90 100644 --- a/Playgrounds/Issue156.playground/Contents.swift +++ b/Playgrounds/Issue156.playground/Contents.swift @@ -76,7 +76,7 @@ class TestDeleteAll: NSObject { } -struct MyRecord: RowConvertible, TableMapping, Persistable { +struct MyRecord: DecodableRecord, TableMapping, Persistable { static let MyColumn = Column("MyColumn") static var databaseTableName: String { return String(describing: self) } diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index defcf6d6f..3da4dc315 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -64,8 +64,8 @@ struct PointOfInterest { var coordinate: CLLocationCoordinate2D } -// Adopt RowConvertible -extension PointOfInterest : RowConvertible { +// Adopt DecodableRecord +extension PointOfInterest : DecodableRecord { init(row: Row) { id = row["id"] title = row["title"] diff --git a/README.md b/README.md index 82f2e4340..c60d193bb 100644 --- a/README.md +++ b/README.md @@ -1857,7 +1857,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in **Protocols and the Record class** - [Record Protocols Overview](#record-protocols-overview) -- [RowConvertible Protocol](#rowconvertible-protocol) +- [DecodableRecord Protocol](#decodablerecord-protocol) - [TableMapping Protocol](#tablemapping-protocol) - [Persistable Protocol](#persistable-protocol) - [Persistence Methods](#persistence-methods) @@ -1884,7 +1884,7 @@ try player.insert(db) ### Fetching Records -[Record](#record-class) subclasses and types that adopt the [RowConvertible](#rowconvertible-protocol) protocol can be fetched from the database: +[Record](#record-class) subclasses and types that adopt the [DecodableRecord] protocol can be fetched from the database: ```swift class Player : Record { ... } @@ -1967,7 +1967,7 @@ let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db) Details follow: - [Record Protocols Overview](#record-protocols-overview) -- [RowConvertible Protocol](#rowconvertible-protocol) +- [DecodableRecord Protocol](#decodablerecord-protocol) - [TableMapping Protocol](#tablemapping-protocol) - [Persistable Protocol](#persistable-protocol) - [Codable Records](#codable-records) @@ -1982,7 +1982,7 @@ Details follow: **GRDB ships with three record protocols**. Your own types will adopt one or several of them, according to the abilities you want to extend your types with. -- [RowConvertible](#rowconvertible-protocol) is able to **read**: it grants the ability to efficiently decode raw database row. +- [DecodableRecord] is able to **read**: it grants the ability to efficiently decode raw database row. Imagine you want to load places from the `places` database table. @@ -2040,10 +2040,10 @@ Details follow: } ``` - That's better. And that's what RowConvertible does, with a little performance bonus, and in a single line: + That's better. And that's what DecodableRecord does, with a little performance bonus, and in a single line: ```swift - struct Place : RowConvertible { + struct Place : DecodableRecord { init(row: Row) { ... } } func fetchPlaces(_ db: Database) throws -> [Place] { @@ -2051,7 +2051,7 @@ Details follow: } ``` - RowConvertible is not able to build SQL requests, though. For that, you also need TableMapping: + DecodableRecord is not able to build SQL requests, though. For that, you also need TableMapping: - [TableMapping](#tablemapping-protocol) is able to **build requests without SQL**: @@ -2061,10 +2061,10 @@ Details follow: let request = Place.order(Column("title")) ``` - When a type adopts both TableMapping and RowConvertible, it can load from those requests: + When a type adopts both TableMapping and DecodableRecord, it can load from those requests: ```swift - struct Place : TableMapping, RowConvertible { ... } + struct Place : TableMapping, DecodableRecord { ... } try dbQueue.inDatabase { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) @@ -2082,18 +2082,18 @@ Details follow: ``` -## RowConvertible Protocol +## DecodableRecord Protocol -**The RowConvertible protocol grants fetching methods to any type** that can be built from a database row: +**The DecodableRecord protocol grants fetching methods to any type** that can be built from a database row: ```swift -protocol RowConvertible { +protocol DecodableRecord { /// Row initializer init(row: Row) } ``` -**To use RowConvertible**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: +**To use DecodableRecord**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: ```swift struct Place { @@ -2102,7 +2102,7 @@ struct Place { var coordinate: CLLocationCoordinate2D } -extension Place : RowConvertible { +extension Place : DecodableRecord { init(row: Row) { id = row["id"] title = row["title"] @@ -2116,7 +2116,7 @@ extension Place : RowConvertible { Rows also accept keys of type `Column`: ```swift -extension Place : RowConvertible { +extension Place : DecodableRecord { enum Columns { static let id = Column("id") static let title = Column("title") @@ -2140,7 +2140,7 @@ See [column values](#column-values) for more information about the `row[]` subsc > > :bulb: **Tip**: the `init(row:)` initializer can be automatically generated when your type adopts the standard `Decodable` protocol. See [Codable Records](#codable-records) for more information. -RowConvertible allows adopting types to be fetched from SQL queries: +DecodableRecord allows adopting types to be fetched from SQL queries: ```swift try Place.fetchCursor(db, "SELECT ...", arguments:...) // A Cursor of Place @@ -2153,7 +2153,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor ## TableMapping Protocol -**Adopt the TableMapping protocol** on top of [RowConvertible](#rowconvertible-protocol), and you are granted with the full [query interface](#the-query-interface). +**Adopt the TableMapping protocol** on top of [DecodableRecord], and you are granted with the full [query interface](#the-query-interface). ```swift protocol TableMapping { @@ -2384,7 +2384,7 @@ struct Link : Persistable { [Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4. -GRDB provides default implementations for [`RowConvertible.init(row:)`](#rowconvertible-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: +GRDB provides default implementations for [`DecodableRecord.init(row:)`](#decodablerecord-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: ```swift // Declare a plain Codable struct or class... @@ -2394,7 +2394,7 @@ struct Player: Codable { } // Adopt Record protocols... -extension Player: RowConvertible, Persistable { +extension Player: DecodableRecord, Persistable { static let databaseTableName = "players" } @@ -2409,7 +2409,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: -struct Place: RowConvertible, Persistable, Codable { +struct Place: DecodableRecord, Persistable, Codable { static let databaseTableName = "places" var title: String @@ -2441,7 +2441,7 @@ struct Place: Codable { } // Free database support! -extension Place: RowConvertible, Persistable { +extension Place: DecodableRecord, Persistable { static let databaseTableName = "places" } ``` @@ -2459,7 +2459,7 @@ struct Place: Codable { var coordinate: CLLocationCoordinate2D { ... } } -extension Place: RowConvertible, MutablePersistable { +extension Place: DecodableRecord, MutablePersistable { static let databaseTableName = "places" mutating func didInsert(with rowID: Int64, for column: String?) { @@ -2479,7 +2479,7 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [RowConvertible, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). Record subclasses define their custom database relationship by overriding database methods: @@ -2732,10 +2732,10 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu let events = try Event.fetchAll(db) ``` -2. Have `init(row:)` from the [RowConvertible](#rowconvertible-protocol) protocol consume the "rowid" column: +2. Have `init(row:)` from the [DecodableRecord] protocol consume the "rowid" column: ```swift - struct Event : RowConvertible { + struct Event : DecodableRecord { var id: Int64? init(row: Row) { @@ -2802,7 +2802,7 @@ This is the list of record methods, along with their required protocols. The [Re | Method | Protocols | Notes | | ------ | --------- | :---: | | **Core Methods** | | | -| `init(row:)` | [RowConvertible](#rowconvertible-protocol) | | +| `init(row:)` | [DecodableRecord] | | | `Type.databaseTableName` | [TableMapping](#tablemapping-protocol) | | | `Type.databaseSelection` | [TableMapping](#tablemapping-protocol) | [*](#columns-selected-by-a-request) | | `Type.persistenceConflictPolicy` | [Persistable](#persistable-protocol) | [*](#conflict-resolution) | @@ -2829,23 +2829,23 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.fetchCount(db)` | [TableMapping](#tablemapping-protocol) | | | `Type.filter(...).fetchCount(db)` | [TableMapping](#tablemapping-protocol) | ² | | **Fetch Record [Cursors](#cursors)** | | | -| `Type.fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchCursor(db, keys:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchCursor(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchCursor(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchCursor(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchCursor(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | +| `Type.fetchCursor(db, keys:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchCursor(db, sql)` | [DecodableRecord] | ³ | +| `Type.fetchCursor(statement)` | [DecodableRecord] | ⁴ | +| `Type.filter(...).fetchCursor(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | | **Fetch Record Arrays** | | | -| `Type.fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchAll(db, keys:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchAll(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchAll(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchAll(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchAll(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | +| `Type.fetchAll(db, keys:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchAll(db, sql)` | [DecodableRecord] | ³ | +| `Type.fetchAll(statement)` | [DecodableRecord] | ⁴ | +| `Type.filter(...).fetchAll(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | | **Fetch Individual Records** | | | -| `Type.fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchOne(db, key:...)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ¹ | -| `Type.fetchOne(db, sql)` | [RowConvertible](#rowconvertible-protocol) | ³ | -| `Type.fetchOne(statement)` | [RowConvertible](#rowconvertible-protocol) | ⁴ | -| `Type.filter(...).fetchOne(db)` | [RowConvertible](#rowconvertible-protocol) & [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchOne(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | +| `Type.fetchOne(db, key:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchOne(db, sql)` | [DecodableRecord] | ³ | +| `Type.fetchOne(statement)` | [DecodableRecord] | ⁴ | +| `Type.filter(...).fetchOne(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | | **[Changes Tracking](#changes-tracking)** | | | | `record.databaseEqual(...)` | [Persistable](#persistable-protocol) | | | `record.databaseChanges(from:...)` | [Persistable](#persistable-protocol) | | @@ -3526,7 +3526,7 @@ let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player? ``` -**When the selected columns don't fit the source type**, change your target: any other type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, plain [database rows](#fetching-rows), and even [values](#values): +**When the selected columns don't fit the source type**, change your target: any other type that adopts the [DecodableRecord] protocol, plain [database rows](#fetching-rows), and even [values](#values): ```swift let maxScore = try Player.select(max(scoreColumn)) @@ -4606,7 +4606,7 @@ This technique works pretty well, but it has three drawbacks: 1. The selection becomes hard to read and understand. 2. Such queries are difficult to write by hand. -3. The mangled names are a *very* bad fit for [RowConvertible](#rowconvertible-protocol) records that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. +3. The mangled names are a *very* bad fit for [DecodableRecord] records that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. We thus need another technique. **Below we'll see how to split rows into slices, and preserve column names.** @@ -4715,7 +4715,7 @@ But we may want to make it more usable and robust: 2. Joined records not always need all columns from a table (see `TableMapping.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). 3. Building row adapters is long and error prone. -To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [RowConvertible](#rowconvertible-protocol) protocol: +To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [DecodableRecord] protocol: ```swift struct Item { @@ -4725,7 +4725,7 @@ struct Item { } /// Item can decode rows: -extension Item: RowConvertible { +extension Item: DecodableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4800,7 +4800,7 @@ let items = try dbQueue.inDatabase { db in > :bulb: In this chapter, we have learned: > -> - how to define a `RowConvertible` record that consumes rows fetched from a joined query. +> - how to define a `DecodableRecord` record that consumes rows fetched from a joined query. > - how to use `selectionSQL` and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection. > - how to use `splittingRowAdapters` in order to streamline the definition of row slices. > - how to gather all relevant methods and constants in a record type, fully responsible of its relationship with the database. @@ -4820,7 +4820,7 @@ struct Item { } /// Item can decode rows: -extension Item: RowConvertible { +extension Item: DecodableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4893,18 +4893,18 @@ Item.all() You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code: ```swift -struct Player: Decodable, RowConvertible, TableMapping { +struct Player: Decodable, DecodableRecord, TableMapping { static let databaseTableName = "players" var id: Int64 var name: String } -struct Team: Decodable, RowConvertible, TableMapping { +struct Team: Decodable, DecodableRecord, TableMapping { static let databaseTableName = "teams" var id: Int64 var name: String var color: Color } -struct Item: Decodable, RowConvertible { +struct Item: Decodable, DecodableRecord { var player: Player var team: Team? var maxScore: Int @@ -5303,7 +5303,7 @@ protocol TransactionObserverType : class { It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). -Given a fetch request, and a type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. +Given a fetch request, and a type that adopts the [DecodableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController. @@ -5324,7 +5324,7 @@ See also [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), an [RxSwift](https When you initialize a fetched records controller, you provide the following mandatory information: - A [database connection](#database-connections) -- The type of the fetched records. It must be a type that adopts the [RowConvertible](#rowconvertible-protocol) protocol, such as a subclass of the [Record](#record-class) class +- The type of the fetched records. It must be a type that adopts the [DecodableRecord] protocol, such as a subclass of the [Record](#record-class) class - A fetch request ```swift @@ -6912,3 +6912,12 @@ Sample Code - [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. + +Legacy +====== + +## RowConvertible Protocol + +This protocol has been renamed [DecodableRecord] in GRDB 3.0. + +[DecodableRecord]: #decodablerecord-protocol diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 2069056dd..f140b34d3 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -142,13 +142,13 @@ private struct UserRowRequest : FetchRequest { func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } } -// MARK: - RowConvertible +// MARK: - DecodableRecord -private struct UserRowConvertible1 : RowConvertible { +private struct UserDecodableRecord1 : DecodableRecord { init(row: Row) { } } -private class UserRowConvertible2 : RowConvertible { +private class UserDecodableRecord2 : DecodableRecord { required init(row: Row) { } } diff --git a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift similarity index 97% rename from Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift rename to Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift index 63c1e8d69..61bd7f54d 100644 --- a/Tests/GRDBTests/RowConvertible+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift @@ -13,7 +13,7 @@ private struct Reader { let age: Int? } -extension Reader : RowConvertible { +extension Reader : DecodableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -41,7 +41,7 @@ private struct AltReader { let age: Int? } -extension AltReader : RowConvertible { +extension AltReader : DecodableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -50,7 +50,7 @@ extension AltReader : RowConvertible { } -class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { +class DecodableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -66,7 +66,7 @@ class RowConvertibleQueryInterfaceRequestTests: GRDBTestCase { } - // MARK: - Fetch RowConvertible + // MARK: - Fetch DecodableRecord func testAll() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/RowConvertibleDecodableTests.swift b/Tests/GRDBTests/DecodableRecordDecodableTests.swift similarity index 89% rename from Tests/GRDBTests/RowConvertibleDecodableTests.swift rename to Tests/GRDBTests/DecodableRecordDecodableTests.swift index 1389ec3c3..35b469c0b 100644 --- a/Tests/GRDBTests/RowConvertibleDecodableTests.swift +++ b/Tests/GRDBTests/DecodableRecordDecodableTests.swift @@ -8,14 +8,14 @@ import XCTest import GRDB #endif -class RowConvertibleDecodableTests: GRDBTestCase { } +class DecodableRecordDecodableTests: GRDBTestCase { } -// MARK: - RowConvertible conformance derived from Decodable +// MARK: - DecodableRecord conformance derived from Decodable -extension RowConvertibleDecodableTests { +extension DecodableRecordDecodableTests { func testTrivialDecodable() { - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: String } @@ -26,7 +26,7 @@ extension RowConvertibleDecodableTests { } func testCustomDecodable() { - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: String private enum CodingKeys : String, CodingKey { @@ -45,28 +45,28 @@ extension RowConvertibleDecodableTests { } } - func testCustomRowConvertible() { - struct Struct : RowConvertible, Decodable { + func testCustomDecodableRecord() { + struct Struct : DecodableRecord, Decodable { let value: String init(row: Row) { - value = (row["value"] as String) + " (RowConvertible)" + value = (row["value"] as String) + " (DecodableRecord)" } } do { let s = Struct(row: ["value": "foo"]) - XCTAssertEqual(s.value, "foo (RowConvertible)") + XCTAssertEqual(s.value, "foo (DecodableRecord)") } } } // MARK: - Different kinds of single-value properties -extension RowConvertibleDecodableTests { +extension DecodableRecordDecodableTests { func testTrivialProperty() { - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let int64: Int64 let optionalInt64: Int64? } @@ -100,7 +100,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -144,7 +144,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -181,7 +181,7 @@ extension RowConvertibleDecodableTests { case foo, bar } - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -239,7 +239,7 @@ extension RowConvertibleDecodableTests { } } - struct Struct : RowConvertible, Decodable { + struct Struct : DecodableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -269,10 +269,10 @@ extension RowConvertibleDecodableTests { // MARK: - Foundation Codable Types -extension RowConvertibleDecodableTests { +extension DecodableRecordDecodableTests { func testStructWithDate() { - struct StructWithDate : RowConvertible, Decodable { + struct StructWithDate : DecodableRecord, Decodable { let date: Date } @@ -282,7 +282,7 @@ extension RowConvertibleDecodableTests { } func testStructWithURL() { - struct StructWithURL : RowConvertible, Decodable { + struct StructWithURL : DecodableRecord, Decodable { let url: URL } @@ -292,7 +292,7 @@ extension RowConvertibleDecodableTests { } func testStructWithUUID() { - struct StructWithUUID : RowConvertible, Decodable { + struct StructWithUUID : DecodableRecord, Decodable { let uuid: UUID } diff --git a/Tests/GRDBTests/RowConvertibleTests.swift b/Tests/GRDBTests/DecodableRecordTests.swift similarity index 99% rename from Tests/GRDBTests/RowConvertibleTests.swift rename to Tests/GRDBTests/DecodableRecordTests.swift index d796e710f..94468a520 100644 --- a/Tests/GRDBTests/RowConvertibleTests.swift +++ b/Tests/GRDBTests/DecodableRecordTests.swift @@ -12,14 +12,14 @@ private struct Fetched { var lastName: String } -extension Fetched : RowConvertible { +extension Fetched : DecodableRecord { init(row: Row) { firstName = row["firstName"] lastName = row["lastName"] } } -class RowConvertibleTests: GRDBTestCase { +class DecodableRecordTests: GRDBTestCase { func testRowInitializer() { let row = Row(["firstName": "Arthur", "lastName": "Martin"]) diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 1d0404233..22dc0c7ac 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -14,7 +14,7 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : DecodableRecord { init(row: Row) { id = row[.rowID] title = row["title"] diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 107176e91..61cbee6fc 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -14,7 +14,7 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : DecodableRecord { init(row: Row) { id = row[.rowID] title = row["title"] diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 8906440d2..985cbd642 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -15,7 +15,7 @@ private struct Book { let body: String } -extension Book : RowConvertible { +extension Book : DecodableRecord { init(row: Row) { id = row[.rowID] title = row["title"] diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index a0a407ae7..181422123 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -60,7 +60,7 @@ class FetchRequestTests: GRDBTestCase { } func testRequestFetchRecords() throws { - struct CustomRecord: RowConvertible, Decodable { + struct CustomRecord: DecodableRecord, Decodable { var id: Int } struct CustomRequest : FetchRequest { diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift index 148573696..2037cbba0 100644 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ b/Tests/GRDBTests/FetchedRecordsControllerTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private class ChangesRecorder { +private class ChangesRecorder { var changes: [(record: Record, change: FetchedRecordChange)] = [] var recordsBeforeChanges: [Record]! var recordsAfterChanges: [Record]! @@ -85,7 +85,7 @@ private class Person : Record { } } -private struct Book : RowConvertible { +private struct Book : DecodableRecord { var id: Int64 var authorID: Int64 var title: String diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index 07027fa21..b4c171fa5 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -41,33 +41,33 @@ let testedSQL = """ ORDER BY t1.id """ -private struct T1: Codable, RowConvertible, TableMapping { +private struct T1: Codable, DecodableRecord, TableMapping { static let databaseTableName = "t1" var id: Int64 var name: String } -private struct T2: Codable, RowConvertible, TableMapping { +private struct T2: Codable, DecodableRecord, TableMapping { static let databaseTableName = "t2" var id: Int64 var t1id: Int64 var name: String } -private struct T3: Codable, RowConvertible, TableMapping { +private struct T3: Codable, DecodableRecord, TableMapping { static let databaseTableName = "t3" static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] var t1id: Int64 var name: String } -private struct T4: Codable, RowConvertible, TableMapping { +private struct T4: Codable, DecodableRecord, TableMapping { static let databaseTableName = "t4" var t1id: Int64 var name: String } -private struct T5: Codable, RowConvertible, TableMapping { +private struct T5: Codable, DecodableRecord, TableMapping { static let databaseTableName = "t5" var id: Int64 var t3id: Int64? @@ -75,7 +75,7 @@ private struct T5: Codable, RowConvertible, TableMapping { var name: String } -private struct FlatModel: RowConvertible { +private struct FlatModel: DecodableRecord { private enum Scopes { static let t1 = "t1" static let t2Left = "t2Left" @@ -115,7 +115,7 @@ private struct FlatModel: RowConvertible { } } -private struct CodableFlatModel: RowConvertible, Codable { +private struct CodableFlatModel: DecodableRecord, Codable { var t1: T1 var t2Left: T2? var t2Right: T2? @@ -138,7 +138,7 @@ private struct CodableFlatModel: RowConvertible, Codable { } } -private struct CodableNestedModel: RowConvertible, Codable { +private struct CodableNestedModel: DecodableRecord, Codable { struct T2Pair: Codable { var left: T2? var right: T2? diff --git a/Tests/GRDBTests/MutablePersistableChangesTests.swift b/Tests/GRDBTests/MutablePersistableChangesTests.swift index a79a2d185..c5f015d5c 100644 --- a/Tests/GRDBTests/MutablePersistableChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableChangesTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct Player: RowConvertible, MutablePersistable, Codable { +private struct Player: DecodableRecord, MutablePersistable, Codable { static let databaseTableName = "players" var id: Int64? diff --git a/Tests/GRDBTests/RecordBoxTests.swift b/Tests/GRDBTests/RecordBoxTests.swift index 7c7af40bc..81e800dfb 100644 --- a/Tests/GRDBTests/RecordBoxTests.swift +++ b/Tests/GRDBTests/RecordBoxTests.swift @@ -10,7 +10,7 @@ import XCTest typealias RecordBox = GRDB.RecordBox // Single deprecation warning #endif -private struct Player: RowConvertible, MutablePersistable, Codable { +private struct Player: DecodableRecord, MutablePersistable, Codable { static let databaseTableName = "players" var id: Int64? diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index efee44855..9224d3ef6 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -7,7 +7,7 @@ import XCTest @testable import GRDB #endif -private struct Person : RowConvertible, TableMapping { +private struct Person : DecodableRecord, TableMapping { static let databaseTableName = "persons" init(row: Row) { } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index a5a586429..d0c3dd945 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -100,7 +100,7 @@ private final class Artist: Codable { } } -extension Artist : RowConvertible, Persistable { +extension Artist : DecodableRecord, Persistable { static let databaseTableName = "artists" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID @@ -119,7 +119,7 @@ private final class Artwork : Codable { } } -extension Artwork : RowConvertible, Persistable { +extension Artwork : DecodableRecord, Persistable { static let databaseTableName = "artworks" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID diff --git a/Tests/Performance/PerformanceTests.swift b/Tests/Performance/PerformanceTests.swift index 8400778b9..dfb0407a3 100644 --- a/Tests/Performance/PerformanceTests.swift +++ b/Tests/Performance/PerformanceTests.swift @@ -7,7 +7,7 @@ import RealmSwift // MARK:- GRDB -struct ItemStruct : RowConvertible, Persistable { +struct ItemStruct : DecodableRecord, Persistable { var i0: Int var i1: Int var i2: Int diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index f57c96d94..84de5e2ff 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -103,7 +103,7 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [RowConvertible](https://github.com/groue/GRDB.swift#rowconvertible-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift#rowconvertible-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift)) From 639de6ca11b132969ecb103e95ee6dc8fa0eacc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 13:28:29 +0100 Subject: [PATCH 020/348] Rename TableMapping to TableRecord --- Documentation/WhyAdoptGRDB.md | 6 +- GRDB.xcodeproj/project.pbxproj | 62 ++++++------- GRDB/Legacy/Fixits-0-90-1.swift | 2 +- .../FTS3+QueryInterfaceRequest.swift | 6 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 6 +- .../QueryInterfaceRequest.swift | 64 ++++++------- .../SQLSelectable+QueryInterface.swift | 4 +- ...wift => DecodableRecord+TableRecord.swift} | 18 ++-- GRDB/Record/FetchedRecordsController.swift | 2 +- GRDB/Record/Persistable.swift | 2 +- GRDB/Record/Record.swift | 2 +- GRDB/Record/RecordBox.swift | 2 +- .../{TableMapping.swift => TableRecord.swift} | 24 ++--- GRDBCipher.xcodeproj/project.pbxproj | 70 +++++++------- GRDBCustom.xcodeproj/project.pbxproj | 54 +++++------ .../Issue156.playground/Contents.swift | 2 +- Playgrounds/Tour.playground/Contents.swift | 4 +- README.md | 91 ++++++++++--------- TODO.md | 2 +- .../GRDBTests/CompilationProtocolTests.swift | 10 +- Tests/GRDBTests/DatabaseRegionTests.swift | 4 +- Tests/GRDBTests/JoinSupportTests.swift | 10 +- .../QueryInterfaceExpressionsTests.swift | 2 +- .../QueryInterfaceExtensibilityTests.swift | 6 +- .../QueryInterfaceRequestTests.swift | 2 +- Tests/GRDBTests/RecordUniqueIndexTests.swift | 2 +- ...leRecord+QueryInterfaceRequestTests.swift} | 4 +- ...pingTests.swift => TableRecordTests.swift} | 8 +- Tests/generatePerformanceReport.rb | 2 +- 29 files changed, 239 insertions(+), 234 deletions(-) rename GRDB/Record/{DecodableRecord+TableMapping.swift => DecodableRecord+TableRecord.swift} (91%) rename GRDB/Record/{TableMapping.swift => TableRecord.swift} (87%) rename Tests/GRDBTests/{TableMapping+QueryInterfaceRequestTests.swift => TableRecord+QueryInterfaceRequestTests.swift} (99%) rename Tests/GRDBTests/{TableMappingTests.swift => TableRecordTests.swift} (90%) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index cb51bf465..29ecf731a 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -72,10 +72,10 @@ extension Place: DecodableRecord { ... } let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] ``` -Add the [TableMapping] protocol, and SQL requests are generated for you: +Add the [TableRecord] protocol, and SQL requests are generated for you: ```swift -extension Place: TableMapping { ... } +extension Place: TableRecord { ... } let place = try Place.fetchOne(db, key: 1) // Place? ``` @@ -271,5 +271,5 @@ Happy GRDB! :gift: [SQLite.swift]: http://github.com/stephencelis/SQLite.swift [StORM]: https://www.perfect.org/docs/StORM.html [Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery -[TableMapping]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[TableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 910714da5..18b21cf1d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -47,8 +47,8 @@ 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560D92471C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; - 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; - 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; + 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; }; 56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; @@ -97,7 +97,7 @@ 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; 56300B621C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - 56300B6C1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; @@ -185,7 +185,7 @@ 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 565490E11D5AE252005622CB /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 565490E41D5AE252005622CB /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; @@ -515,7 +515,7 @@ 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - 56D4966A1D813086008276D7 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; @@ -577,9 +577,9 @@ 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; 56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; - 56D51D001EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; - 56D51D031EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; - 56D51D061EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D001EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D031EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D061EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -620,8 +620,8 @@ 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FF45441D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -768,7 +768,7 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -785,7 +785,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; @@ -997,7 +997,7 @@ 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRecordStructTests.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1025,7 +1025,7 @@ 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; @@ -1203,12 +1203,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -1267,7 +1267,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1497,7 +1497,7 @@ 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680520F201320E600E87861 /* RecordBoxTests.swift */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1550,13 +1550,13 @@ children = ( 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 567517C720131B220094BF41 /* RecordBox.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -2170,9 +2170,9 @@ files = ( 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D51D061EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D061EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, - 565490E41D5AE252005622CB /* TableMapping.swift in Sources */, + 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, @@ -2328,8 +2328,8 @@ 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56D51D031EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, - 560D924C1C672C4B00F4F92B /* TableMapping.swift in Sources */, + 56D51D031EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 567517C920131B220094BF41 /* RecordBox.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, @@ -2468,7 +2468,7 @@ 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 56FEE7FF1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, 56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */, 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2510,7 +2510,7 @@ 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, - 56300B6C1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, @@ -2616,7 +2616,7 @@ 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 56FEE7FB1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */, 562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -2660,7 +2660,7 @@ 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, 5674A7201F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, - 56D4966A1D813086008276D7 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */, @@ -2728,14 +2728,14 @@ 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D2F1DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, - 56D51D001EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D001EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB0F1D10899D006283EF /* URL.swift in Sources */, - 560D924B1C672C4B00F4F92B /* TableMapping.swift in Sources */, + 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */, 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560A37A41C8F625000949E71 /* DatabasePool.swift in Sources */, diff --git a/GRDB/Legacy/Fixits-0-90-1.swift b/GRDB/Legacy/Fixits-0-90-1.swift index e3f6f7b35..9dcb57781 100644 --- a/GRDB/Legacy/Fixits-0-90-1.swift +++ b/GRDB/Legacy/Fixits-0-90-1.swift @@ -39,7 +39,7 @@ extension DecodableRecord { public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } -extension DecodableRecord where Self: TableMapping { +extension DecodableRecord where Self: TableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index aa1229783..7d958533e 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -22,7 +22,7 @@ extension QueryInterfaceRequest { } } -extension TableMapping { +extension TableRecord { // MARK: Full Text Search @@ -35,8 +35,8 @@ extension TableMapping { /// database row. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { return all().matching(pattern) } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index bb0191eae..b7423d5da 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -14,8 +14,8 @@ /// database row. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { switch query.source { case .table(let name, let alias)?: @@ -31,7 +31,7 @@ } } - extension TableMapping { + extension TableRecord { // MARK: Full Text Search diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 420d10c57..02b7bf0b5 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -246,7 +246,7 @@ extension QueryInterfaceRequest { } } -extension QueryInterfaceRequest where T: TableMapping { +extension QueryInterfaceRequest where T: TableRecord { /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. /// @@ -255,8 +255,8 @@ extension QueryInterfaceRequest where T: TableMapping { /// request = request.filter(key: 1) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { guard let key = key else { return T.none() @@ -272,8 +272,8 @@ extension QueryInterfaceRequest where T: TableMapping { /// request = request.filter(keys: [1, 2, 3]) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { let keys = Array(keys) let makePredicate: (Column) -> SQLExpression @@ -308,8 +308,8 @@ extension QueryInterfaceRequest where T: TableMapping { /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { guard let key = key else { return T.none() @@ -327,8 +327,8 @@ extension QueryInterfaceRequest where T: TableMapping { /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { guard !keys.isEmpty else { return T.none() @@ -381,7 +381,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistable { } } -extension TableMapping { +extension TableRecord { // MARK: Request Derivation @@ -391,8 +391,8 @@ extension TableMapping { /// let request = Player.all() /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { let query = QueryInterfaceQuery( select: databaseSelection, @@ -435,8 +435,8 @@ extension TableMapping { /// let request = Player.filter(Column("email") == "arthur@example.com") /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { return all().filter(predicate) } @@ -447,8 +447,8 @@ extension TableMapping { /// let request = Player.filter(key: 1) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { return all().filter(key: key) } @@ -459,8 +459,8 @@ extension TableMapping { /// let request = Player.filter(keys: [1, 2, 3]) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { return all().filter(keys: keys) } @@ -474,8 +474,8 @@ extension TableMapping { /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { return all().filter(key: key) } @@ -489,8 +489,8 @@ extension TableMapping { /// index on the key columns. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { return all().filter(keys: keys) } @@ -501,8 +501,8 @@ extension TableMapping { /// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"]) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().filter(sql: sql, arguments: arguments) } @@ -514,8 +514,8 @@ extension TableMapping { /// let request = Player.order(Column("name")) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { return all().order(orderings) } @@ -527,8 +527,8 @@ extension TableMapping { /// let request = Player.order([Column("name")]) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { return all().order(orderings) } @@ -539,8 +539,8 @@ extension TableMapping { /// let request = Player.order(sql: "name") /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().order(sql: sql, arguments: arguments) } @@ -552,8 +552,8 @@ extension TableMapping { /// let request = Player.limit(1) /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { return all().limit(limit, offset: offset) } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 78d2da736..8791b3edc 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -3,11 +3,11 @@ /// AllColumns is the `*` in `SELECT *`. /// /// You use AllColumns in your custom implementation of -/// TableMapping.databaseSelection. +/// TableRecord.databaseSelection. /// /// For example: /// -/// struct Player : TableMapping { +/// struct Player : TableRecord { /// static var databaseTableName = "players" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } diff --git a/GRDB/Record/DecodableRecord+TableMapping.swift b/GRDB/Record/DecodableRecord+TableRecord.swift similarity index 91% rename from GRDB/Record/DecodableRecord+TableMapping.swift rename to GRDB/Record/DecodableRecord+TableRecord.swift index 38872aeb7..f5a529ab9 100644 --- a/GRDB/Record/DecodableRecord+TableMapping.swift +++ b/GRDB/Record/DecodableRecord+TableRecord.swift @@ -1,4 +1,4 @@ -extension DecodableRecord where Self: TableMapping { +extension DecodableRecord where Self: TableRecord { // MARK: Fetching All @@ -18,8 +18,8 @@ extension DecodableRecord where Self: TableMapping { /// The cursor must be iterated in a protected dispath queue. /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - returns: A cursor over fetched records. @@ -34,8 +34,8 @@ extension DecodableRecord where Self: TableMapping { /// let players = try Player.fetchAll(db) // [Player] /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -49,8 +49,8 @@ extension DecodableRecord where Self: TableMapping { /// let player = try Player.fetchOne(db) // Player? /// /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableMapping.databaseSelection` property, or - /// for individual requests with the `TableMapping.select` method. + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. /// /// - parameter db: A database connection. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. @@ -59,7 +59,7 @@ extension DecodableRecord where Self: TableMapping { } } -extension DecodableRecord where Self: TableMapping { +extension DecodableRecord where Self: TableRecord { // MARK: Fetching by Single-Column Primary Key @@ -119,7 +119,7 @@ extension DecodableRecord where Self: TableMapping { } } -extension DecodableRecord where Self: TableMapping { +extension DecodableRecord where Self: TableRecord { // MARK: Fetching by Key diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 280db9460..e1cd2af1a 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -393,7 +393,7 @@ public final class FetchedRecordsController { fileprivate var errorHandler: ((FetchedRecordsController, Error) -> ())? } -extension FetchedRecordsController where Record: TableMapping { +extension FetchedRecordsController where Record: TableRecord { // MARK: - Initialization diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/Persistable.swift index 824617966..a6c241e39 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/Persistable.swift @@ -169,7 +169,7 @@ public struct PersistenceConflictPolicy { } /// Types that adopt MutablePersistable can be inserted, updated, and deleted. -public protocol MutablePersistable : TableMapping { +public protocol MutablePersistable : TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index cbaf30d13..f07b4eb5a 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : DecodableRecord, TableMapping, Persistable { +open class Record : DecodableRecord, TableRecord, Persistable { // MARK: - Initializers diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift index 8a368fcbe..f898e6241 100644 --- a/GRDB/Record/RecordBox.swift +++ b/GRDB/Record/RecordBox.swift @@ -40,7 +40,7 @@ public final class RecordBox: Record { super.init(row: row) } - // MARK: - TableMapping + // MARK: - TableRecord /// :nodoc: override public class var databaseTableName: String { diff --git a/GRDB/Record/TableMapping.swift b/GRDB/Record/TableRecord.swift similarity index 87% rename from GRDB/Record/TableMapping.swift rename to GRDB/Record/TableRecord.swift index 1029fd30a..4ea8692bf 100644 --- a/GRDB/Record/TableMapping.swift +++ b/GRDB/Record/TableRecord.swift @@ -1,17 +1,17 @@ -/// Types that adopt TableMapping declare a particular relationship with +/// Types that adopt TableRecord declare a particular relationship with /// a database table. /// -/// Types that adopt both TableMapping and DecodableRecord are granted with +/// Types that adopt both TableRecord and DecodableRecord are granted with /// built-in methods that allow to fetch instances identified by key: /// /// try Player.fetchOne(db, key: 123) // Player? /// try Citizenship.fetchOne(db, key: ["citizenId": 12, "countryId": 45]) // Citizenship? /// -/// TableMapping is adopted by Record. -public protocol TableMapping { +/// TableRecord is adopted by Record. +public protocol TableRecord { /// The name of the database table used to build requests. /// - /// struct Player : TableMapping { + /// struct Player : TableRecord { /// static var databaseTableName = "players" /// } /// @@ -29,7 +29,7 @@ public protocol TableMapping { /// You can provide a custom implementation and provide an explicit list /// of columns: /// - /// struct RestrictedPlayer : TableMapping { + /// struct RestrictedPlayer : TableRecord { /// static var databaseTableName = "players" /// static var databaseSelection = [Column("id"), Column("name")] /// } @@ -39,7 +39,7 @@ public protocol TableMapping { /// /// You can also add extra columns such as the `rowid` column: /// - /// struct ExtendedPlayer : TableMapping { + /// struct ExtendedPlayer : TableRecord { /// static var databaseTableName = "players" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } @@ -49,14 +49,14 @@ public protocol TableMapping { static var databaseSelection: [SQLSelectable] { get } } -extension TableMapping { +extension TableRecord { /// Default value: `[AllColumns()]`. public static var databaseSelection: [SQLSelectable] { return [AllColumns()] } } -extension TableMapping { +extension TableRecord { // MARK: - Counting All @@ -68,7 +68,7 @@ extension TableMapping { } } -extension TableMapping { +extension TableRecord { // MARK: - SQL Generation @@ -76,7 +76,7 @@ extension TableMapping { /// /// For example: /// - /// struct Player: TableMapping { + /// struct Player: TableRecord { /// static let databaseTableName = "players" /// } /// @@ -98,7 +98,7 @@ extension TableMapping { /// /// For example: /// - /// struct Player: TableMapping { + /// struct Player: TableRecord { /// static let databaseTableName = "players" /// } /// diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 52531e732..0ebaec7b5 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -22,7 +22,7 @@ 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; 560FC52E1CB003810014AA8E /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 560FC5331CB003810014AA8E /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; @@ -79,7 +79,7 @@ 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 560FC59B1CB00B880014AA8E /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 560FC59F1CB00B880014AA8E /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 560FC5A01CB00B880014AA8E /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -326,7 +326,7 @@ 567156571CB16729007DC145 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 567156591CB16729007DC145 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 5671565D1CB16729007DC145 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 5671565E1CB16729007DC145 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -523,7 +523,7 @@ 56AFC9FD1CB1A8BB00F48B96 /* NSString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1521C672E4000235C62 /* NSString.swift */; }; 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; 56AFCA071CB1A8BB00F48B96 /* DatabasePool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37A31C8F625000949E71 /* DatabasePool.swift */; }; 56AFCA081CB1A8BB00F48B96 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; @@ -595,7 +595,7 @@ 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 56AFCA6D1CB1AA9900F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -655,7 +655,7 @@ 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */; }; 56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; - 56AFCAC61CB1ABC800F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238131B9C74A90082EB20 /* DatabaseTests.swift */; }; 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; @@ -736,8 +736,8 @@ 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D011EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; - 56D51D041EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D011EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D041EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -755,10 +755,10 @@ 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FF45411D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56FF45421D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56FF45451D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; @@ -846,7 +846,7 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; 560FC5B01CB00B880014AA8E /* GRDBCipherOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -865,7 +865,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; @@ -1056,7 +1056,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1073,7 +1073,7 @@ 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; @@ -1255,12 +1255,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -1319,7 +1319,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1534,7 +1534,7 @@ 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680521C2013296800E87861 /* RecordBoxTests.swift */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1587,13 +1587,13 @@ children = ( 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 5680520A2013209300E87861 /* RecordBox.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -2033,14 +2033,14 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 56D51D011EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D011EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 560FC52E1CB003810014AA8E /* Record.swift in Sources */, 56CEB5461EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB101D10899D006283EF /* URL.swift in Sources */, - 560FC5311CB003810014AA8E /* TableMapping.swift in Sources */, + 560FC5311CB003810014AA8E /* TableRecord.swift in Sources */, 56DAA2DC1DE9C827006E10C8 /* Cursor.swift in Sources */, 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 560FC5321CB003810014AA8E /* DatabasePool.swift in Sources */, @@ -2165,7 +2165,7 @@ 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, - 56FEE7FC1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */, @@ -2198,7 +2198,7 @@ 5623936A1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 560FC59C1CB00B880014AA8E /* StatementArguments+FoundationTests.swift in Sources */, 5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 560FC59D1CB00B880014AA8E /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, 566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, 562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, @@ -2312,7 +2312,7 @@ 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, - 56FEE7FD1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5671564B1CB16729007DC145 /* Row+FoundationTests.swift in Sources */, 56A8C2431D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, @@ -2349,7 +2349,7 @@ 562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, 566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, 562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 5671565B1CB16729007DC145 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 5671565C1CB16729007DC145 /* FoundationNSDateTests.swift in Sources */, 5671565D1CB16729007DC145 /* DatabaseTests.swift in Sources */, @@ -2427,11 +2427,11 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 56D51D041EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D041EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56AFCA031CB1A8BB00F48B96 /* TableMapping.swift in Sources */, + 56AFCA031CB1A8BB00F48B96 /* TableRecord.swift in Sources */, 56CEB5491EAA359A00BFAF62 /* Column.swift in Sources */, 5657AB131D10899D006283EF /* URL.swift in Sources */, 56AFCA061CB1A8BB00F48B96 /* Configuration.swift in Sources */, @@ -2560,7 +2560,7 @@ 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 56FEE8001F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 5690C33C1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56AFCA581CB1AA9900F48B96 /* Row+FoundationTests.swift in Sources */, @@ -2601,7 +2601,7 @@ 56AFCA6C1CB1AA9900F48B96 /* StatementArguments+FoundationTests.swift in Sources */, 562393651DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5B1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, - 56AFCA6D1CB1AA9900F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, @@ -2707,7 +2707,7 @@ 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, - 56FEE8011F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCAB01CB1ABC800F48B96 /* TransactionObserverTests.swift in Sources */, @@ -2747,7 +2747,7 @@ 568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56AFCAC51CB1ABC800F48B96 /* StatementArguments+FoundationTests.swift in Sources */, 562393661DEE06D300A6B01F /* CursorTests.swift in Sources */, - 56AFCAC61CB1ABC800F48B96 /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, 5674A71E1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index bd0f1dcba..63d371093 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -262,8 +262,8 @@ 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D021EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; - 56D51D051EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */; }; + 56D51D021EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D051EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -278,8 +278,8 @@ 56F3E7681E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; 56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; - 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */; }; + 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; + 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56FF45471D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; @@ -319,7 +319,7 @@ F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80381CFB2932003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80391CFB2936003DC1BA /* GRDBCustomSQLite-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF21CFB23DA003DC1BA /* GRDBCustomSQLite-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -363,7 +363,7 @@ F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableMapping.swift */; }; + F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80931CFB2F13003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80941CFB2F15003DC1BA /* GRDBCustomSQLite-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF21CFB23DA003DC1BA /* GRDBCustomSQLite-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -459,12 +459,12 @@ F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; F3BA811B1CFB305F003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; - F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */; }; + F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; F3BA81201CFB3063003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -550,7 +550,7 @@ 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; - 560D92461C672C4B00F4F92B /* TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableMapping.swift; sourceTree = ""; }; + 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; @@ -566,7 +566,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableMapping+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; @@ -748,7 +748,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableMapping.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -765,7 +765,7 @@ 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableMappingTests.swift; sourceTree = ""; }; + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; @@ -929,12 +929,12 @@ path = GRDBTests; sourceTree = ""; }; - 56176C9C1EACEA8C000F3F2B /* TableMapping */ = { + 56176C9C1EACEA8C000F3F2B /* TableRecord */ = { isa = PBXGroup; children = ( - 56FEE7FA1F47253700D930EA /* TableMappingTests.swift */, + 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */, ); - name = TableMapping; + name = TableRecord; sourceTree = ""; }; 56176C9E1EACEDF9000F3F2B /* Record */ = { @@ -993,7 +993,7 @@ 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, - 56300B6A1C53D3E8005A543B /* TableMapping+QueryInterfaceRequestTests.swift */, + 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, ); name = QueryInterface; @@ -1208,7 +1208,7 @@ 560B3FA41C19DFF800C58EC7 /* Persistable */, 56176C9E1EACEDF9000F3F2B /* Record */, 568052182013295100E87861 /* RecordBoxTests.swift */, - 56176C9C1EACEA8C000F3F2B /* TableMapping */, + 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; sourceTree = ""; @@ -1261,13 +1261,13 @@ children = ( 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableMapping.swift */, + 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, 560D92441C672C4B00F4F92B /* Persistable.swift */, 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 568052072013206F00E87861 /* RecordBox.swift */, - 560D92461C672C4B00F4F92B /* TableMapping.swift */, + 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; sourceTree = ""; @@ -1737,7 +1737,7 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D051EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D051EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -1771,7 +1771,7 @@ F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, - F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */, + F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5680520E201320A200E87861 /* RecordBox.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -1804,7 +1804,7 @@ F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */, F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, - F3BA81181CFB305E003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */, 5657AB4D1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, @@ -1868,7 +1868,7 @@ 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 56FEE8021F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -1984,7 +1984,7 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D021EA789FA0074638A /* DecodableRecord+TableMapping.swift in Sources */, + 56D51D021EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -2018,7 +2018,7 @@ F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, - F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */, + F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 568052092013207000E87861 /* RecordBox.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -2062,7 +2062,7 @@ F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, - F3BA811D1CFB305F003DC1BA /* TableMapping+QueryInterfaceRequestTests.swift in Sources */, + F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, @@ -2115,7 +2115,7 @@ 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 56FEE7FE1F47253700D930EA /* TableMappingTests.swift in Sources */, + 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, 5690C33A1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Playgrounds/Issue156.playground/Contents.swift index e34392e90..75e88bbaa 100644 --- a/Playgrounds/Issue156.playground/Contents.swift +++ b/Playgrounds/Issue156.playground/Contents.swift @@ -76,7 +76,7 @@ class TestDeleteAll: NSObject { } -struct MyRecord: DecodableRecord, TableMapping, Persistable { +struct MyRecord: DecodableRecord, TableRecord, Persistable { static let MyColumn = Column("MyColumn") static var databaseTableName: String { return String(describing: self) } diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index 3da4dc315..d500e5827 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -76,8 +76,8 @@ extension PointOfInterest : DecodableRecord { } } -// Adopt TableMapping -extension PointOfInterest : TableMapping { +// Adopt TableRecord +extension PointOfInterest : TableRecord { static let databaseTableName = "pointOfInterests" } diff --git a/README.md b/README.md index c60d193bb..be69c6671 100644 --- a/README.md +++ b/README.md @@ -1858,7 +1858,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Record Protocols Overview](#record-protocols-overview) - [DecodableRecord Protocol](#decodablerecord-protocol) -- [TableMapping Protocol](#tablemapping-protocol) +- [TableRecord Protocol](#tablerecord-protocol) - [Persistable Protocol](#persistable-protocol) - [Persistence Methods](#persistence-methods) - [Customizing the Persistence Methods](#customizing-the-persistence-methods) @@ -1891,7 +1891,7 @@ class Player : Record { ... } let players = try Player.fetchAll(db, "SELECT ...", arguments: ...) // [Player] ``` -Add the [TableMapping](#tablemapping-protocol) protocol and you can stop writing SQL: +Add the [TableRecord] protocol and you can stop writing SQL: ```swift let spain = try Country.fetchOne(db, key: "ES") // Country? @@ -1957,7 +1957,7 @@ try Player.filter(emailColumn == nil).deleteAll(db) ### Counting Records -[Record](#record-class) subclasses and types that adopt the [TableMapping](#tablemapping-protocol) protocol can be counted: +[Record](#record-class) subclasses and types that adopt the [TableRecord] protocol can be counted: ```swift let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db) // Int @@ -1968,7 +1968,7 @@ Details follow: - [Record Protocols Overview](#record-protocols-overview) - [DecodableRecord Protocol](#decodablerecord-protocol) -- [TableMapping Protocol](#tablemapping-protocol) +- [TableRecord Protocol](#tablerecord-protocol) - [Persistable Protocol](#persistable-protocol) - [Codable Records](#codable-records) - [Record Class](#record-class) @@ -2051,20 +2051,20 @@ Details follow: } ``` - DecodableRecord is not able to build SQL requests, though. For that, you also need TableMapping: + DecodableRecord is not able to build SQL requests, though. For that, you also need TableRecord: -- [TableMapping](#tablemapping-protocol) is able to **build requests without SQL**: +- [TableRecord] is able to **build requests without SQL**: ```swift - struct Place : TableMapping { ... } + struct Place : TableRecord { ... } // SELECT * FROM places ORDER BY title let request = Place.order(Column("title")) ``` - When a type adopts both TableMapping and DecodableRecord, it can load from those requests: + When a type adopts both TableRecord and DecodableRecord, it can load from those requests: ```swift - struct Place : TableMapping, DecodableRecord { ... } + struct Place : TableRecord, DecodableRecord { ... } try dbQueue.inDatabase { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) @@ -2151,12 +2151,12 @@ try Place.fetchOne(db, "SELECT ...", arguments:...) // Place? See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.9/Structs/StatementArguments.html) for more information about the query arguments. -## TableMapping Protocol +## TableRecord Protocol -**Adopt the TableMapping protocol** on top of [DecodableRecord], and you are granted with the full [query interface](#the-query-interface). +**Adopt the TableRecord protocol** on top of [DecodableRecord], and you are granted with the full [query interface](#the-query-interface). ```swift -protocol TableMapping { +protocol TableRecord { static var databaseTableName: String { get } static var databaseSelection: [SQLSelectable] { get } } @@ -2164,10 +2164,10 @@ protocol TableMapping { The `databaseTableName` type property is the name of a database table. `databaseSelection` is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. -**To use TableMapping**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: +**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: ```swift -extension Place : TableMapping { +extension Place : TableRecord { static let databaseTableName = "places" } ``` @@ -2179,7 +2179,7 @@ Adopting types can be fetched without SQL, using the [query interface](#the-quer let paris = try Place.filter(nameColumn == "Paris").fetchOne(db) ``` -TableMapping can also fetch records by primary key: +TableRecord can also fetch records by primary key: ```swift try Player.fetchOne(db, key: 1) // Player? @@ -2209,8 +2209,8 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci **GRDB provides two protocols that let adopting types create, update, and delete rows in the database:** ```swift -protocol MutablePersistable : TableMapping { - /// The name of the database table (from TableMapping) +protocol MutablePersistable : TableRecord { + /// The name of the database table (from TableRecord) static var databaseTableName: String { get } /// Defines the values persisted in the database @@ -2479,7 +2479,7 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableMapping, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableRecord, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). Record subclasses define their custom database relationship by overriding database methods: @@ -2710,10 +2710,10 @@ Without primary key, records don't have any identity, and the [persistence metho When SQLite won't let you provide an explicit primary key (as in [full-text](#full-text-search) tables, for example), you may want to make your record type fully aware of the hidden rowid column: -1. Have the `databaseSelection` static property (from the [TableMapping](#tablemapping-protocol) protocol) return the hidden rowid column: +1. Have the `databaseSelection` static property (from the [TableRecord] protocol) return the hidden rowid column: ```swift - struct Event : TableMapping { + struct Event : TableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } @@ -2803,8 +2803,8 @@ This is the list of record methods, along with their required protocols. The [Re | ------ | --------- | :---: | | **Core Methods** | | | | `init(row:)` | [DecodableRecord] | | -| `Type.databaseTableName` | [TableMapping](#tablemapping-protocol) | | -| `Type.databaseSelection` | [TableMapping](#tablemapping-protocol) | [*](#columns-selected-by-a-request) | +| `Type.databaseTableName` | [TableRecord] | | +| `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | | `Type.persistenceConflictPolicy` | [Persistable](#persistable-protocol) | [*](#conflict-resolution) | | `record.encode(to:)` | [Persistable](#persistable-protocol) | | | `record.didInsert(with:for:)` | [Persistable](#persistable-protocol) | | @@ -2826,26 +2826,26 @@ This is the list of record methods, along with their required protocols. The [Re | **Convert Record to Dictionary** | | | | `record.databaseDictionary` | [Persistable](#persistable-protocol) | | | **Count Records** | | | -| `Type.fetchCount(db)` | [TableMapping](#tablemapping-protocol) | | -| `Type.filter(...).fetchCount(db)` | [TableMapping](#tablemapping-protocol) | ² | +| `Type.fetchCount(db)` | [TableRecord] | | +| `Type.filter(...).fetchCount(db)` | [TableRecord] | ² | | **Fetch Record [Cursors](#cursors)** | | | -| `Type.fetchCursor(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchCursor(db, keys:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchCursor(db)` | [DecodableRecord] & [TableRecord] | | +| `Type.fetchCursor(db, keys:...)` | [DecodableRecord] & [TableRecord] | ¹ | | `Type.fetchCursor(db, sql)` | [DecodableRecord] | ³ | | `Type.fetchCursor(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchCursor(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | +| `Type.filter(...).fetchCursor(db)` | [DecodableRecord] & [TableRecord] | ² | | **Fetch Record Arrays** | | | -| `Type.fetchAll(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchAll(db, keys:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchAll(db)` | [DecodableRecord] & [TableRecord] | | +| `Type.fetchAll(db, keys:...)` | [DecodableRecord] & [TableRecord] | ¹ | | `Type.fetchAll(db, sql)` | [DecodableRecord] | ³ | | `Type.fetchAll(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchAll(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | +| `Type.filter(...).fetchAll(db)` | [DecodableRecord] & [TableRecord] | ² | | **Fetch Individual Records** | | | -| `Type.fetchOne(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | | -| `Type.fetchOne(db, key:...)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ¹ | +| `Type.fetchOne(db)` | [DecodableRecord] & [TableRecord] | | +| `Type.fetchOne(db, key:...)` | [DecodableRecord] & [TableRecord] | ¹ | | `Type.fetchOne(db, sql)` | [DecodableRecord] | ³ | | `Type.fetchOne(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchOne(db)` | [DecodableRecord] & [TableMapping](#tablemapping-protocol) | ² | +| `Type.filter(...).fetchOne(db)` | [DecodableRecord] & [TableRecord] | ² | | **[Changes Tracking](#changes-tracking)** | | | | `record.databaseEqual(...)` | [Persistable](#persistable-protocol) | | | `record.databaseChanges(from:...)` | [Persistable](#persistable-protocol) | | @@ -3117,7 +3117,7 @@ let players = try request.fetchAll(db) // [Player] let count = try request.fetchCount(db) // Int ``` -All requests start from **a type** that adopts the `TableMapping` protocol, such as a `Record` subclass (see [Records](#records)): +All requests start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): ```swift class Player : Record { ... } @@ -3309,12 +3309,12 @@ let request = Player.select(AllColumns(), Column.rowID) To specify the default selection for all requests built from a type, define the `databaseSelection` property: ```swift -struct RestrictedPlayer : TableMapping { +struct RestrictedPlayer : TableRecord { static let databaseTableName = "players" static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] } -struct ExtendedPlayer : TableMapping { +struct ExtendedPlayer : TableRecord { static let databaseTableName = "players" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } @@ -3701,7 +3701,7 @@ Player.deleteOne(db, key: ["email": "arthur@example.com"]) ## Custom Requests -Until now, we have seen [requests](#requests) created from any type that adopts the [TableMapping](#tablemapping-protocol) protocol: +Until now, we have seen [requests](#requests) created from any type that adopts the [TableRecord] protocol: ```swift let request = Player.all() // QueryInterfaceRequest @@ -4712,7 +4712,7 @@ Our introduction above has introduced important techniques. It uses [row adapter But we may want to make it more usable and robust: 1. It's generally easier to consume records than raw rows. -2. Joined records not always need all columns from a table (see `TableMapping.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). +2. Joined records not always need all columns from a table (see `TableRecord.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). 3. Building row adapters is long and error prone. To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [DecodableRecord] protocol: @@ -4893,12 +4893,12 @@ Item.all() You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code: ```swift -struct Player: Decodable, DecodableRecord, TableMapping { +struct Player: Decodable, DecodableRecord, TableRecord { static let databaseTableName = "players" var id: Int64 var name: String } -struct Team: Decodable, DecodableRecord, TableMapping { +struct Team: Decodable, DecodableRecord, TableRecord { static let databaseTableName = "teams" var id: Int64 var name: String @@ -5489,10 +5489,10 @@ try controller.performFetch() FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content. -For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableMapping](#tablemapping-protocol) protocol, they are automatically compared according to their primary key: +For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key: ```swift -class Player : TableMapping { ... } +class Player : TableRecord { ... } let controller = FetchedRecordsController( dbQueue, request: Player.all()) @@ -6916,8 +6916,13 @@ Sample Code Legacy ====== -## RowConvertible Protocol +#### RowConvertible Protocol This protocol has been renamed [DecodableRecord] in GRDB 3.0. +#### TableMapping Protocol + +This protocol has been renamed [TableRecord] in GRDB 3.0. + [DecodableRecord]: #decodablerecord-protocol +[TableRecord]: #tablerecord-protocol diff --git a/TODO.md b/TODO.md index 5fc8da458..3223fc981 100644 --- a/TODO.md +++ b/TODO.md @@ -30,7 +30,7 @@ GRDB 3.0 - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename RowConvertible, TableMapping, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? +- [ ] Rename RowConvertible, TableRecord, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. - [X] Drop IteratorCursor, use AnyCursor instead - [X] Rename TypedRequest to FetchRequest, drop Request diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index f140b34d3..7a7f9c1e8 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -162,14 +162,14 @@ private class UserStatementColumnConvertible2 : StatementColumnConvertible { required init(sqliteStatement: SQLiteStatement, index: Int32) { } } -// MARK: - TableMapping +// MARK: - TableRecord -private struct UserTableMapping1 : TableMapping { - static let databaseTableName = "UserTableMapping1" +private struct UserTableRecord1 : TableRecord { + static let databaseTableName = "UserTableRecord1" } -private class UserTableMapping2 : TableMapping { - static let databaseTableName = "UserTableMapping2" +private class UserTableRecord2 : TableRecord { + static let databaseTableName = "UserTableRecord2" } // MARK: - TransactionObserver diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 55406b398..bf56708d7 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -287,7 +287,7 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "foo" } @@ -414,7 +414,7 @@ class DatabaseRegionTests : GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "foo" } diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index b4c171fa5..bb638889e 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -41,33 +41,33 @@ let testedSQL = """ ORDER BY t1.id """ -private struct T1: Codable, DecodableRecord, TableMapping { +private struct T1: Codable, DecodableRecord, TableRecord { static let databaseTableName = "t1" var id: Int64 var name: String } -private struct T2: Codable, DecodableRecord, TableMapping { +private struct T2: Codable, DecodableRecord, TableRecord { static let databaseTableName = "t2" var id: Int64 var t1id: Int64 var name: String } -private struct T3: Codable, DecodableRecord, TableMapping { +private struct T3: Codable, DecodableRecord, TableRecord { static let databaseTableName = "t3" static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] var t1id: Int64 var name: String } -private struct T4: Codable, DecodableRecord, TableMapping { +private struct T4: Codable, DecodableRecord, TableRecord { static let databaseTableName = "t4" var t1id: Int64 var name: String } -private struct T5: Codable, DecodableRecord, TableMapping { +private struct T5: Codable, DecodableRecord, TableRecord { static let databaseTableName = "t5" var id: Int64 var t3id: Int64? diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 2dbdfa946..988918f8d 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -14,7 +14,7 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } private let tableRequest = Reader.all() diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 235f64585..269d89fe0 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -60,7 +60,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.create(table: "records") { t in t.column("date", .datetime) } - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } @@ -78,7 +78,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE VIRTUAL TABLE records USING fts3(content TEXT)") - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } @@ -98,7 +98,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.create(table: "records") { t in t.column("text", .text) } - struct Record : TableMapping { + struct Record : TableRecord { static let databaseTableName = "records" } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index f32069f12..00fdf0f94 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -14,7 +14,7 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } private let tableRequest = Reader.all() diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index 9224d3ef6..2ffd67fe4 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -7,7 +7,7 @@ import XCTest @testable import GRDB #endif -private struct Person : DecodableRecord, TableMapping { +private struct Person : DecodableRecord, TableRecord { static let databaseTableName = "persons" init(row: Row) { } diff --git a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift similarity index 99% rename from Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift rename to Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 88799416b..6448b5ad6 100644 --- a/Tests/GRDBTests/TableMapping+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -14,12 +14,12 @@ private struct Col { static let readerId = Column("readerId") } -private struct Reader : TableMapping { +private struct Reader : TableRecord { static let databaseTableName = "readers" } -class TableMappingQueryInterfaceRequestTests: GRDBTestCase { +class TableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() diff --git a/Tests/GRDBTests/TableMappingTests.swift b/Tests/GRDBTests/TableRecordTests.swift similarity index 90% rename from Tests/GRDBTests/TableMappingTests.swift rename to Tests/GRDBTests/TableRecordTests.swift index c310cf690..54ce6be41 100644 --- a/Tests/GRDBTests/TableMappingTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -7,10 +7,10 @@ import XCTest import GRDB #endif -class TableMappingTests: GRDBTestCase { +class TableRecordTests: GRDBTestCase { func testDefaultDatabaseSelection() throws { - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "t1" } let dbQueue = try makeDatabaseQueue() @@ -22,7 +22,7 @@ class TableMappingTests: GRDBTestCase { } func testExtendedDatabaseSelection() throws { - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "t1" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } @@ -35,7 +35,7 @@ class TableMappingTests: GRDBTestCase { } func testRestrictedDatabaseSelection() throws { - struct Record: TableMapping { + struct Record: TableRecord { static let databaseTableName = "t1" static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")] } diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index 84de5e2ff..d44ba94fb 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -103,7 +103,7 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift#rowconvertible-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift#decodablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift)) From 08a08cd74f7077a8165d8d4efaf61cca32a9c192 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 18:46:32 +0100 Subject: [PATCH 021/348] Rename MutablePersistable to EncodableRecord --- Documentation/WhyAdoptGRDB.md | 6 +- GRDB.xcodeproj/project.pbxproj | 110 ++++++------ .../QueryInterfaceRequest.swift | 2 +- ....swift => EncodableRecord+Encodable.swift} | 14 +- ...ersistable.swift => EncodableRecord.swift} | 94 +++++------ GRDB/Record/FetchedRecordsController.swift | 2 +- GRDB/Record/Record.swift | 4 +- GRDB/Record/RecordBox.swift | 8 +- GRDBCipher.xcodeproj/project.pbxproj | 157 +++++++++--------- GRDBCustom.xcodeproj/project.pbxproj | 107 ++++++------ .../Issue156.playground/Contents.swift | 2 +- Playgrounds/Tour.playground/Contents.swift | 4 +- README.md | 107 ++++++------ TODO.md | 10 +- .../GRDBTests/CompilationProtocolTests.swift | 20 +-- ...bleRecord+QueryInterfaceRequestTests.swift | 2 +- ...Tests.swift => EncodableRecordTests.swift} | 128 +++++++------- Tests/GRDBTests/FTS3RecordTests.swift | 2 +- Tests/GRDBTests/FTS4RecordTests.swift | 2 +- Tests/GRDBTests/FTS5RecordTests.swift | 2 +- Tests/GRDBTests/GRDBTestCase.swift | 2 +- ... MutableEncodableRecordChangesTests.swift} | 8 +- ...> MutableEncodableRecordDeleteTests.swift} | 8 +- ...utableEncodableRecordEncodableTests.swift} | 40 ++--- ...ecordPersistenceConflictPolicyTests.swift} | 16 +- ...wift => MutableEncodableRecordTests.swift} | 104 ++++++------ Tests/GRDBTests/RecordBoxTests.swift | 2 +- .../RecordPersistenceConflictPolicy.swift | 4 +- .../GRDBTests/TransactionObserverTests.swift | 4 +- Tests/Performance/PerformanceTests.swift | 2 +- Tests/generatePerformanceReport.rb | 10 +- 31 files changed, 488 insertions(+), 495 deletions(-) rename GRDB/Record/{Persistable+Encodable.swift => EncodableRecord+Encodable.swift} (95%) rename GRDB/Record/{Persistable.swift => EncodableRecord.swift} (94%) rename Tests/GRDBTests/{PersistableTests.swift => EncodableRecordTests.swift} (85%) rename Tests/GRDBTests/{MutablePersistableChangesTests.swift => MutableEncodableRecordChangesTests.swift} (97%) rename Tests/GRDBTests/{MutablePersistableDeleteTests.swift => MutableEncodableRecordDeleteTests.swift} (97%) rename Tests/GRDBTests/{MutablePersistableEncodableTests.swift => MutableEncodableRecordEncodableTests.swift} (92%) rename Tests/GRDBTests/{MutablePersistablePersistenceConflictPolicyTests.swift => MutableEncodableRecordPersistenceConflictPolicyTests.swift} (95%) rename Tests/GRDBTests/{MutablePersistableTests.swift => MutableEncodableRecordTests.swift} (86%) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 29ecf731a..12119bcc2 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -79,10 +79,10 @@ extension Place: TableRecord { ... } let place = try Place.fetchOne(db, key: 1) // Place? ``` -Add the [Persistable] protocol, and places know how to insert, update and delete themselves: +Add the [EncodableRecord] protocol, and places know how to insert, update and delete themselves: ```swift -extension Place: Persistable { ... } +extension Place: EncodableRecord { ... } try place.delete(db) ``` @@ -263,7 +263,7 @@ Happy GRDB! :gift: [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift [GRDBObjc]: http://github.com/groue/GRDBObjc -[Persistable]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[EncodableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [Realm]: http://realm.io [DecodableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 18b21cf1d..74b5c52eb 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -45,8 +45,8 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; - 560D92471C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; - 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 560D92471C672C4B00F4F92B /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + 560D92481C672C4B00F4F92B /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; @@ -101,8 +101,8 @@ 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 563363B21C933FF8000BE133 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 563363B01C933FF8000BE133 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; + 563363B21C933FF8000BE133 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; @@ -183,7 +183,7 @@ 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - 565490E11D5AE252005622CB /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 565490E11D5AE252005622CB /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; @@ -237,8 +237,8 @@ 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; 566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84402041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84412041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */; }; 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -273,9 +273,9 @@ 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F41F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F81F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F91F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; + 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; + 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; + 5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; 5674A6FB1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A6FF1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7001F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; @@ -286,8 +286,8 @@ 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A7201F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; + 5674A7201F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; + 5674A7231F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; @@ -420,8 +420,8 @@ 56A8C2471D1918F00096E9D4 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; }; 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746F1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021C91D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CD1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021C91D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CD1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; @@ -516,7 +516,7 @@ 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; - 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56D4966B1D81309E008276D7 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -552,8 +552,8 @@ 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56D496931D81316E008276D7 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - 56D496951D81317B008276D7 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56D496951D81317B008276D7 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; + 56D496961D81317B008276D7 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; @@ -622,7 +622,7 @@ 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45441D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56FF45441D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -767,7 +767,7 @@ 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; @@ -788,8 +788,8 @@ 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -832,7 +832,7 @@ 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -850,11 +850,11 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; @@ -941,7 +941,7 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; @@ -1026,7 +1026,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1173,17 +1173,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { isa = PBXGroup; children = ( - 566A843F2041914000E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, + 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, ); - name = Persistable; + name = EncodableRecord; sourceTree = ""; }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { @@ -1494,7 +1494,7 @@ 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680520F201320E600E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1551,9 +1551,9 @@ 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 567517C720131B220094BF41 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -2212,7 +2212,7 @@ 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, - 5674A6F81F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, @@ -2243,7 +2243,7 @@ 565490D41D5AE252005622CB /* (null) in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, - 565490E11D5AE252005622CB /* Persistable.swift in Sources */, + 565490E11D5AE252005622CB /* EncodableRecord.swift in Sources */, 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2293,7 +2293,7 @@ 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6F91F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2366,7 +2366,7 @@ 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, - 560D92481C672C4B00F4F92B /* Persistable.swift in Sources */, + 560D92481C672C4B00F4F92B /* EncodableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, @@ -2391,7 +2391,7 @@ 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, - 56FF45441D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, 56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */, 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2419,7 +2419,7 @@ 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, - 56B021CD1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CD1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2434,7 +2434,7 @@ 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */, - 563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */, + 563363B01C933FF8000BE133 /* MutableEncodableRecordTests.swift in Sources */, 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, @@ -2451,7 +2451,7 @@ 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */, - 563363B21C933FF8000BE133 /* PersistableTests.swift in Sources */, + 563363B21C933FF8000BE133 /* EncodableRecordTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */, 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2466,7 +2466,7 @@ 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 566A84412041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84412041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, @@ -2511,7 +2511,7 @@ 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, - 5674A7231F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7231F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, @@ -2560,7 +2560,7 @@ 56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, - 56D4966B1D81309E008276D7 /* MutablePersistableDeleteTests.swift in Sources */, + 56D4966B1D81309E008276D7 /* MutableEncodableRecordDeleteTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, @@ -2611,10 +2611,10 @@ 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, - 56D496961D81317B008276D7 /* PersistableTests.swift in Sources */, + 56D496961D81317B008276D7 /* EncodableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 566A84402041914000E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84402041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, @@ -2642,7 +2642,7 @@ 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, - 56B021C91D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021C91D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */, 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */, @@ -2654,11 +2654,11 @@ 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, - 56D496951D81317B008276D7 /* MutablePersistableTests.swift in Sources */, + 56D496951D81317B008276D7 /* MutableEncodableRecordTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, - 5674A7201F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7201F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, @@ -2711,7 +2711,7 @@ 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, - 5674A6F41F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2767,7 +2767,7 @@ 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 567517C820131B220094BF41 /* RecordBox.swift in Sources */, - 560D92471C672C4B00F4F92B /* Persistable.swift in Sources */, + 560D92471C672C4B00F4F92B /* EncodableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 02b7bf0b5..1242bfca7 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -365,7 +365,7 @@ extension QueryInterfaceRequest where T: TableRecord { } } -extension QueryInterfaceRequest where RowDecoder: MutablePersistable { +extension QueryInterfaceRequest where RowDecoder: MutableEncodableRecord { // MARK: Deleting diff --git a/GRDB/Record/Persistable+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift similarity index 95% rename from GRDB/Record/Persistable+Encodable.swift rename to GRDB/Record/EncodableRecord+Encodable.swift index 4fa8d7779..61e49a241 100644 --- a/GRDB/Record/Persistable+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -1,4 +1,4 @@ -private struct PersistableKeyedEncodingContainer : KeyedEncodingContainerProtocol { +private struct EncodableRecordKeyedEncodingContainer : KeyedEncodingContainerProtocol { let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { @@ -40,7 +40,7 @@ private struct PersistableKeyedEncodingContainer : KeyedEncoding // This allows us to encode Date as String, for example. encode((value as! DatabaseValueConvertible), key.stringValue) } else { - try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode)) + try value.encode(to: EncodableRecordEncoder(codingPath: [key], encode: encode)) } } @@ -140,12 +140,12 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue, key.stringValue) } else { - try value.encode(to: PersistableEncoder(codingPath: [key], encode: encode)) + try value.encode(to: EncodableRecordEncoder(codingPath: [key], encode: encode)) } } } -private struct PersistableEncoder : Encoder { +private struct EncodableRecordEncoder : Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] @@ -171,7 +171,7 @@ private struct PersistableEncoder : Encoder { guard codingPath.isEmpty else { fatalError("unkeyed encoding is not supported") } - return KeyedEncodingContainer(PersistableKeyedEncodingContainer(encode: encode)) + return KeyedEncodingContainer(EncodableRecordKeyedEncodingContainer(encode: encode)) } /// Returns an encoding container appropriate for holding multiple unkeyed values. @@ -194,7 +194,7 @@ private struct PersistableEncoder : Encoder { } } -extension MutablePersistable where Self: Encodable { +extension MutableEncodableRecord where Self: Encodable { public func encode(to container: inout PersistenceContainer) { // The inout container parameter won't enter an escaping closure since // SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md @@ -202,7 +202,7 @@ extension MutablePersistable where Self: Encodable { // So let's use it in a non-escaping closure: func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { withoutActuallyEscaping(encode) { escapableEncode in - let encoder = PersistableEncoder(codingPath: [], encode: escapableEncode) + let encoder = EncodableRecordEncoder(codingPath: [], encode: escapableEncode) try! self.encode(to: encoder) } } diff --git a/GRDB/Record/Persistable.swift b/GRDB/Record/EncodableRecord.swift similarity index 94% rename from GRDB/Record/Persistable.swift rename to GRDB/Record/EncodableRecord.swift index a6c241e39..107b1caa2 100644 --- a/GRDB/Record/Persistable.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -12,12 +12,12 @@ extension Database.ConflictResolution { // MARK: - PersistenceError -/// An error thrown by a type that adopts Persistable. +/// An error thrown by a type that adopts EncodableRecord. public enum PersistenceError: Error, CustomStringConvertible { - /// Thrown by MutablePersistable.update() when no matching row could be + /// Thrown by MutableEncodableRecord.update() when no matching row could be /// found in the database. - case recordNotFound(MutablePersistable) + case recordNotFound(MutableEncodableRecord) } // CustomStringConvertible @@ -25,8 +25,8 @@ extension PersistenceError { /// :nodoc: public var description: String { switch self { - case .recordNotFound(let persistable): - return "Not found: \(persistable)" + case .recordNotFound(let record): + return "Not found: \(record)" } } } @@ -34,9 +34,9 @@ extension PersistenceError { // MARK: - PersistenceContainer /// Use persistence containers in the `encode(to:)` method of your -/// persistable records: +/// encodable records: /// -/// struct Player : MutablePersistable { +/// struct Player : MutableEncodableRecord { /// var id: Int64? /// var name: String? /// @@ -81,7 +81,7 @@ public struct PersistenceContainer { /// // Meh /// var container = PersistenceContainer() /// record.encode(to: container) - init(_ record: MutablePersistable) { + init(_ record: MutableEncodableRecord) { storage = [:] record.encode(to: &self) } @@ -137,7 +137,7 @@ public struct PersistenceContainer { } extension Row { - convenience init(_ record: MutablePersistable) { + convenience init(_ record: MutableEncodableRecord) { self.init(PersistenceContainer(record)) } @@ -146,12 +146,12 @@ extension Row { } } -// MARK: - MutablePersistable +// MARK: - MutableEncodableRecord -/// The MutablePersistable protocol uses this type in order to handle SQLite +/// The MutableEncodableRecord protocol uses this type in order to handle SQLite /// conflicts when records are inserted or updated. /// -/// See `MutablePersistable.persistenceConflictPolicy`. +/// See `MutableEncodableRecord.persistenceConflictPolicy`. /// /// See https://www.sqlite.org/lang_conflict.html public struct PersistenceConflictPolicy { @@ -168,8 +168,8 @@ public struct PersistenceConflictPolicy { } } -/// Types that adopt MutablePersistable can be inserted, updated, and deleted. -public protocol MutablePersistable : TableRecord { +/// Types that adopt MutableEncodableRecord can be inserted, updated, and deleted. +public protocol MutableEncodableRecord : TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -191,7 +191,7 @@ public protocol MutablePersistable : TableRecord { /// /// Primary key columns, if any, must be included. /// - /// struct Player : MutablePersistable { + /// struct Player : MutableEncodableRecord { /// var id: Int64? /// var name: String? /// @@ -214,7 +214,7 @@ public protocol MutablePersistable : TableRecord { /// /// This method is optional: the default implementation does nothing. /// - /// struct Player : MutablePersistable { + /// struct Player : MutableEncodableRecord { /// var id: Int64? /// var name: String? /// @@ -313,14 +313,14 @@ public protocol MutablePersistable : TableRecord { func exists(_ db: Database) throws -> Bool } -extension MutablePersistable { +extension MutableEncodableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null } } } -extension MutablePersistable { +extension MutableEncodableRecord { /// Describes the conflict policy for insertions and updates. /// /// The default value specifies ABORT policy for both insertions and @@ -403,7 +403,7 @@ extension MutablePersistable { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - public func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool { + public func updateChanges(_ db: Database, from record: MutableEncodableRecord) throws -> Bool { let changedColumns = Set(databaseChanges(from: record).keys) if changedColumns.isEmpty { return false @@ -453,11 +453,11 @@ extension MutablePersistable { /// but also in terms of columns. When the two records don't define the /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. - public func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue] { + public func databaseChanges(from record: MutableEncodableRecord) -> [String: DatabaseValue] { return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record)) } - fileprivate func databaseChangesIterator(from record: MutablePersistable) -> AnyIterator<(String, DatabaseValue)> { + fileprivate func databaseChangesIterator(from record: MutableEncodableRecord) -> AnyIterator<(String, DatabaseValue)> { let oldContainer = PersistenceContainer(record) var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { @@ -490,10 +490,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutableEncodableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt MutablePersistable can invoke performInsert() in their + /// that adopt MutableEncodableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public mutating func performInsert(_ db: Database) throws { @@ -507,10 +507,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutableEncodableRecord. /// /// performUpdate() provides the default implementation for update(). Types - /// that adopt MutablePersistable can invoke performUpdate() in their + /// that adopt MutableEncodableRecord can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). /// @@ -531,10 +531,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutableEncodableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt MutablePersistable can invoke performSave() in their + /// that adopt MutableEncodableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -560,10 +560,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutableEncodableRecord. /// /// performDelete() provides the default implementation for deelte(). Types - /// that adopt MutablePersistable can invoke performDelete() in + /// that adopt MutableEncodableRecord can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). public func performDelete(_ db: Database) throws -> Bool { @@ -576,10 +576,10 @@ extension MutablePersistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutablePersistable. + /// that adopt MutableEncodableRecord. /// /// performExists() provides the default implementation for exists(). Types - /// that adopt MutablePersistable can invoke performExists() in + /// that adopt MutableEncodableRecord can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). public func performExists(_ db: Database) throws -> Bool { @@ -592,7 +592,7 @@ extension MutablePersistable { } -extension MutablePersistable { +extension MutableEncodableRecord { // MARK: - Deleting All @@ -607,7 +607,7 @@ extension MutablePersistable { } } -extension MutablePersistable { +extension MutableEncodableRecord { // MARK: - Deleting by Single-Column Primary Key @@ -669,7 +669,7 @@ extension MutablePersistable { } } -extension MutablePersistable { +extension MutableEncodableRecord { // MARK: - Deleting by Key @@ -706,15 +706,15 @@ extension MutablePersistable { } } -// MARK: - Persistable +// MARK: - EncodableRecord -/// Types that adopt Persistable can be inserted, updated, and deleted. +/// Types that adopt EncodableRecord can be inserted, updated, and deleted. /// /// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. /// -/// Unlike MutablePersistable, the insert() and save() methods are not +/// Unlike MutableEncodableRecord, the insert() and save() methods are not /// mutating methods. -public protocol Persistable : MutablePersistable { +public protocol EncodableRecord : MutableEncodableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -725,7 +725,7 @@ public protocol Persistable : MutablePersistable { /// This method is optional: the default implementation does nothing. /// /// If you need a mutating variant of this method, adopt the - /// MutablePersistable protocol instead. + /// MutableEncodableRecord protocol instead. /// /// - parameters: /// - rowID: The inserted rowID. @@ -772,7 +772,7 @@ public protocol Persistable : MutablePersistable { func save(_ db: Database) throws } -extension Persistable { +extension EncodableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -801,10 +801,10 @@ extension Persistable { // MARK: - Immutable CRUD Internals /// Don't invoke this method directly: it is an internal method for types - /// that adopt Persistable. + /// that adopt EncodableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt Persistable can invoke performInsert() in their + /// that adopt EncodableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public func performInsert(_ db: Database) throws { @@ -818,10 +818,10 @@ extension Persistable { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt Persistable. + /// that adopt EncodableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt Persistable can invoke performSave() in their + /// that adopt EncodableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -849,14 +849,14 @@ extension Persistable { // MARK: - DAO -/// DAO takes care of Persistable CRUD +/// DAO takes care of EncodableRecord CRUD final class DAO { /// The database let db: Database /// The record - let record: MutablePersistable + let record: MutableEncodableRecord /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is @@ -869,7 +869,7 @@ final class DAO { /// The table primary key let primaryKey: PrimaryKeyInfo - init(_ db: Database, _ record: MutablePersistable) throws { + init(_ db: Database, _ record: MutableEncodableRecord) throws { let databaseTableName = type(of: record).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) let persistenceContainer = PersistenceContainer(record) diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index e1cd2af1a..515ad2d8d 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -900,7 +900,7 @@ extension FetchedRecordsController { } } -extension FetchedRecordsController where Record: MutablePersistable { +extension FetchedRecordsController where Record: MutableEncodableRecord { /// Returns the indexPath of a given record. /// diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index f07b4eb5a..907b9eb49 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : DecodableRecord, TableRecord, Persistable { +open class Record : DecodableRecord, TableRecord, EncodableRecord { // MARK: - Initializers @@ -155,7 +155,7 @@ open class Record : DecodableRecord, TableRecord, Persistable { row = Row(self) #else // workaround weird Swift 3.0 glitch - row = Row(self as! MutablePersistable) + row = Row(self as! MutableEncodableRecord) #endif let copy = type(of: self).init(row: row) copy.referenceRow = referenceRow diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift index f898e6241..2c4e356e8 100644 --- a/GRDB/Record/RecordBox.swift +++ b/GRDB/Record/RecordBox.swift @@ -2,7 +2,7 @@ /// changes tracking provided by the Record class. /// /// // A Regular record struct -/// struct Player: DecodableRecord, MutablePersistable, Codable { +/// struct Player: DecodableRecord, MutableEncodableRecord, Codable { /// static let databaseTableName = "players" /// var id: Int64? /// var name: String @@ -21,8 +21,8 @@ /// playerRecord.hasPersistentChangedValues // true /// playerRecord.persistentChangedValues["score"] // 100 (the old value) /// } -@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") -public final class RecordBox: Record { +@available(*, deprecated, message: "Prefer changes methods defined on the MutableEncodableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") +public final class RecordBox: Record { /// The boxed record public var value: T @@ -52,7 +52,7 @@ public final class RecordBox: Record { return T.databaseSelection } - // MARK: - MutablePersistable + // MARK: - MutableEncodableRecord /// :nodoc: override public class var persistenceConflictPolicy: PersistenceConflictPolicy { diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 0ebaec7b5..ad6fa6daa 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -37,7 +37,7 @@ 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 560FC53F1CB003810014AA8E /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 560FC5411CB003810014AA8E /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 560FC5411CB003810014AA8E /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; @@ -59,11 +59,11 @@ 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; + 560FC57E1CB00B880014AA8E /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 560FC5841CB00B880014AA8E /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -260,10 +260,10 @@ 566A843120413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843220413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843320413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84462041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84472041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84482041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84492041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -304,11 +304,11 @@ 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; + 5671563C1CB16729007DC145 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 567156411CB16729007DC145 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 567156411CB16729007DC145 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -354,8 +354,8 @@ 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F71F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6FA1F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; + 5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; + 5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; 5674A6FE1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7011F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; @@ -368,10 +368,10 @@ 5674A7181F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71E1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7221F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A7241F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; + 5674A71E1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; + 5674A7211F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; + 5674A7221F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; + 5674A7241F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; @@ -538,7 +538,7 @@ 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + 56AFCA151CB1A8BB00F48B96 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; @@ -567,12 +567,12 @@ 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; + 56AFCA4B1CB1AA9900F48B96 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56AFCA521CB1AA9900F48B96 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCA551CB1AA9900F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -627,12 +627,12 @@ 56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; + 56AFCAA41CB1ABC800F48B96 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + 56AFCAAB1CB1ABC800F48B96 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; 56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -666,10 +666,10 @@ 56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; }; - 56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CB1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CE1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021CF1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021CA1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CB1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CE1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CF1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; @@ -759,10 +759,10 @@ 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45411D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45421D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45451D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45461D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56FF45411D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45421D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45451D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45461D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF45581D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; @@ -845,7 +845,7 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; @@ -868,8 +868,8 @@ 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -908,7 +908,7 @@ 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -927,11 +927,11 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; @@ -1020,7 +1020,7 @@ 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCA7F1CB1AA9900F48B96 /* GRDBCipheriOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCAD71CB1ABC800F48B96 /* GRDBCipheriOSEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -1074,7 +1074,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1203,17 +1203,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { isa = PBXGroup; children = ( - 566A84452041AB3900E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, + 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, ); - name = Persistable; + name = EncodableRecord; sourceTree = ""; }; 560FC54F1CB0047D0014AA8E /* GRDBCipher */ = { @@ -1531,7 +1531,7 @@ 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73EB203DA29B000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680521C2013296800E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1588,9 +1588,9 @@ 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 5680520A2013209300E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -2016,7 +2016,7 @@ 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6FA1F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2071,7 +2071,7 @@ 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, 5680520C2013209300E87861 /* RecordBox.swift in Sources */, - 560FC5411CB003810014AA8E /* Persistable.swift in Sources */, + 560FC5411CB003810014AA8E /* EncodableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, @@ -2087,7 +2087,7 @@ files = ( 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */, 560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */, - 56FF45411D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45411D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */, 5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */, 56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, @@ -2116,7 +2116,7 @@ 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021CA1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CA1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, 560FC5761CB00B880014AA8E /* RowCopiedFromStatementTests.swift in Sources */, @@ -2145,7 +2145,7 @@ 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 560FC57E1CB00B880014AA8E /* MutablePersistableTests.swift in Sources */, + 560FC57E1CB00B880014AA8E /* MutableEncodableRecordTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, @@ -2160,7 +2160,7 @@ 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 560FC5841CB00B880014AA8E /* PersistableTests.swift in Sources */, + 560FC5841CB00B880014AA8E /* EncodableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, @@ -2200,7 +2200,7 @@ 5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */, 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84462041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84462041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */, 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2209,7 +2209,7 @@ 5698ACCF1DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */, 560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */, - 5674A7221F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7221F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */, 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2234,7 +2234,7 @@ files = ( 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */, 5671561E1CB16729007DC145 /* DataMemoryTests.swift in Sources */, - 56FF45421D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45421D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, 5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */, 5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2261,7 +2261,7 @@ 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, - 56B021CB1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CB1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, @@ -2291,7 +2291,7 @@ 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 5671563C1CB16729007DC145 /* MutablePersistableTests.swift in Sources */, + 5671563C1CB16729007DC145 /* MutableEncodableRecordTests.swift in Sources */, 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, @@ -2300,7 +2300,7 @@ 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, - 567156411CB16729007DC145 /* PersistableTests.swift in Sources */, + 567156411CB16729007DC145 /* EncodableRecordTests.swift in Sources */, 5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */, 5657AB501D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */, @@ -2347,7 +2347,7 @@ 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB581D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84472041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84472041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2356,7 +2356,7 @@ 5671565E1CB16729007DC145 /* QueryInterfaceRequestTests.swift in Sources */, 5698ACD01DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, - 5674A7241F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7241F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */, 567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -2410,7 +2410,7 @@ 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6F71F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2462,7 +2462,7 @@ 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, - 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */, + 56AFCA151CB1A8BB00F48B96 /* EncodableRecord.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, 5680520D2013209900E87861 /* RecordBox.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -2481,7 +2481,7 @@ files = ( 56AFCA301CB1AA9900F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 562393771DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CE1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CE1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */, 56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2525,7 +2525,7 @@ 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, 566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */, + 56AFCA4B1CB1AA9900F48B96 /* MutableEncodableRecordTests.swift in Sources */, 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -2540,8 +2540,8 @@ 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, - 56FF45451D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, - 56AFCA521CB1AA9900F48B96 /* PersistableTests.swift in Sources */, + 56FF45451D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56AFCA521CB1AA9900F48B96 /* EncodableRecordTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, @@ -2594,7 +2594,7 @@ 565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 56AFCA671CB1AA9900F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84482041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84482041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2603,7 +2603,7 @@ 5657AB5B1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, - 5674A7211F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A7211F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, @@ -2628,7 +2628,7 @@ files = ( 56C3F7581CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393781DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CF1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CF1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2680,7 +2680,7 @@ 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */, 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCAA41CB1ABC800F48B96 /* MutablePersistableTests.swift in Sources */, + 56AFCAA41CB1ABC800F48B96 /* MutableEncodableRecordTests.swift in Sources */, 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -2689,8 +2689,8 @@ 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */, 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, - 56AFCAAB1CB1ABC800F48B96 /* PersistableTests.swift in Sources */, - 56FF45461D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56AFCAAB1CB1ABC800F48B96 /* EncodableRecordTests.swift in Sources */, + 56FF45461D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, @@ -2741,7 +2741,7 @@ 56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56AFCAC01CB1ABC800F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84492041AB3900E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84492041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2750,7 +2750,7 @@ 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, - 5674A71E1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71E1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5691784B1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 56AFCACB1CB1ABC800F48B96 /* DatabaseFunctionTests.swift in Sources */, @@ -2843,7 +2843,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2880,7 +2879,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2917,7 +2915,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2968,7 +2965,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -3006,7 +3002,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3043,7 +3038,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSEncryptedTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3143,7 +3137,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 63d371093..9c9e85f4f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -93,8 +93,8 @@ 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843620413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; }; - 566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */; }; + 566A84432041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84442041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */; }; 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -117,8 +117,8 @@ 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F51F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; - 5674A6F61F307F600095F066 /* Persistable+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */; }; + 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; + 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; 5674A6FC1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A6FD1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; @@ -127,8 +127,8 @@ 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; - 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */; }; + 5674A71D1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; + 5674A71F1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; @@ -205,8 +205,8 @@ 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; - 56B021D01D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */; }; + 56B021CC1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021D01D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; @@ -280,8 +280,8 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; - 56FF45471D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */; }; + 56FF45431D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -317,7 +317,7 @@ F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + F3BA80331CFB28A4003DC1BA /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80381CFB2932003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -361,7 +361,7 @@ F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* Persistable.swift */; }; + F3BA808F1CFB2E7A003DC1BA /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80931CFB2F13003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -399,10 +399,10 @@ F3BA80CE1CFB2FDE003DC1BA /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - F3BA80D21CFB2FF3003DC1BA /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; - F3BA80D31CFB2FF4003DC1BA /* MutablePersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */; }; - F3BA80D41CFB2FF4003DC1BA /* PersistableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableTests.swift */; }; + F3BA80D11CFB2FF3003DC1BA /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; + F3BA80D21CFB2FF3003DC1BA /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + F3BA80D31CFB2FF4003DC1BA /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; + F3BA80D41CFB2FF4003DC1BA /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -549,7 +549,7 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* Persistable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistable.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -569,8 +569,8 @@ 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* PersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -609,7 +609,7 @@ 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableChangesTests.swift; sourceTree = ""; }; + 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -627,11 +627,11 @@ 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Persistable+Encodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableEncodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; @@ -712,7 +712,7 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistablePersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -766,7 +766,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -892,17 +892,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* Persistable */ = { + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { isa = PBXGroup; children = ( - 566A84422041AB2D00E50BFD /* MutablePersistableChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutablePersistableTests.swift */, - 563363AA1C933FF8000BE133 /* PersistableTests.swift */, + 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, + 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, ); - name = Persistable; + name = EncodableRecord; sourceTree = ""; }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { @@ -1205,7 +1205,7 @@ 5674A7251F30A8EF0095F066 /* DecodableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73E7203DA278000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* Persistable */, + 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 568052182013295100E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1262,9 +1262,9 @@ 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, + 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, + 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, - 560D92441C672C4B00F4F92B /* Persistable.swift */, - 5674A6F31F307F600095F066 /* Persistable+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 568052072013206F00E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -1719,7 +1719,7 @@ 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F61F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -1758,7 +1758,7 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, - F3BA80331CFB28A4003DC1BA /* Persistable.swift in Sources */, + F3BA80331CFB28A4003DC1BA /* EncodableRecord.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, @@ -1790,7 +1790,7 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - 56FF45471D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -1818,18 +1818,18 @@ F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021D01D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021D01D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, 5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, - F3BA80D11CFB2FF3003DC1BA /* MutablePersistableTests.swift in Sources */, + F3BA80D11CFB2FF3003DC1BA /* MutableEncodableRecordTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */, 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - F3BA80D21CFB2FF3003DC1BA /* PersistableTests.swift in Sources */, + F3BA80D21CFB2FF3003DC1BA /* EncodableRecordTests.swift in Sources */, 5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -1903,7 +1903,7 @@ F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 566A84442041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84442041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */, 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, @@ -1912,7 +1912,7 @@ 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, - 5674A71F1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71F1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */, 562393671DEE06D300A6B01F /* CursorTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -1966,7 +1966,7 @@ 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F51F307F600095F066 /* Persistable+Encodable.swift in Sources */, + 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -2005,7 +2005,7 @@ 56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, - F3BA808F1CFB2E7A003DC1BA /* Persistable.swift in Sources */, + F3BA808F1CFB2E7A003DC1BA /* EncodableRecord.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, @@ -2050,7 +2050,7 @@ 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */, 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, - 56B021CC1D8C0D3900B239BB /* MutablePersistablePersistenceConflictPolicyTests.swift in Sources */, + 56B021CC1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2071,11 +2071,11 @@ 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, - F3BA80D31CFB2FF4003DC1BA /* MutablePersistableTests.swift in Sources */, + F3BA80D31CFB2FF4003DC1BA /* MutableEncodableRecordTests.swift in Sources */, 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */, F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, - F3BA80D41CFB2FF4003DC1BA /* PersistableTests.swift in Sources */, + F3BA80D41CFB2FF4003DC1BA /* EncodableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, 5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, @@ -2106,7 +2106,7 @@ 5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, - 56FF45431D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, F3BA80F01CFB3017003DC1BA /* DecodableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, @@ -2150,7 +2150,7 @@ 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, - 566A84432041AB2D00E50BFD /* MutablePersistableChangesTests.swift in Sources */, + 566A84432041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */, F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */, @@ -2159,7 +2159,7 @@ 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, - 5674A71D1F30A8DF0095F066 /* MutablePersistableEncodableTests.swift in Sources */, + 5674A71D1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, @@ -2299,7 +2299,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; @@ -2356,7 +2355,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -2394,7 +2392,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2443,7 +2440,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2482,7 +2478,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Playgrounds/Issue156.playground/Contents.swift index 75e88bbaa..f01c64c18 100644 --- a/Playgrounds/Issue156.playground/Contents.swift +++ b/Playgrounds/Issue156.playground/Contents.swift @@ -76,7 +76,7 @@ class TestDeleteAll: NSObject { } -struct MyRecord: DecodableRecord, TableRecord, Persistable { +struct MyRecord: DecodableRecord, TableRecord, EncodableRecord { static let MyColumn = Column("MyColumn") static var databaseTableName: String { return String(describing: self) } diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index d500e5827..0c7ec316e 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -81,8 +81,8 @@ extension PointOfInterest : TableRecord { static let databaseTableName = "pointOfInterests" } -// Adopt MutablePersistable -extension PointOfInterest : MutablePersistable { +// Adopt MutableEncodableRecord +extension PointOfInterest : MutableEncodableRecord { func encode(to container: inout PersistenceContainer) { container["id"] = id container["title"] = title diff --git a/README.md b/README.md index be69c6671..b681a9b18 100644 --- a/README.md +++ b/README.md @@ -1859,7 +1859,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Record Protocols Overview](#record-protocols-overview) - [DecodableRecord Protocol](#decodablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) -- [Persistable Protocol](#persistable-protocol) +- [EncodableRecord Protocol](#encodablerecord-protocol) - [Persistence Methods](#persistence-methods) - [Customizing the Persistence Methods](#customizing-the-persistence-methods) - [Codable Records](#codable-records) @@ -1872,7 +1872,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in ### Inserting Records -To insert a record in the database, subclass the [Record](#record-class) class or adopt the [Persistable](#persistable-protocol) protocol, and call the `insert` method: +To insert a record in the database, subclass the [Record](#record-class) class or adopt the [EncodableRecord] protocol, and call the `insert` method: ```swift class Player : Record { ... } @@ -1906,7 +1906,7 @@ See [fetching methods](#fetching-methods), and the [query interface](#the-query- ### Updating Records -[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be updated in the database: +[Record](#record-class) subclasses and types that adopt the [EncodableRecord] protocol can be updated in the database: ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1933,7 +1933,7 @@ try db.execute("UPDATE players SET synchronized = 1") ### Deleting Records -[Record](#record-class) subclasses and types that adopt the [Persistable](#persistable-protocol) protocol can be deleted from the database: +[Record](#record-class) subclasses and types that adopt the [EncodableRecord] protocol can be deleted from the database: ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1969,7 +1969,7 @@ Details follow: - [Record Protocols Overview](#record-protocols-overview) - [DecodableRecord Protocol](#decodablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) -- [Persistable Protocol](#persistable-protocol) +- [EncodableRecord Protocol](#encodablerecord-protocol) - [Codable Records](#codable-records) - [Record Class](#record-class) - [Changes Tracking](#changes-tracking) @@ -2071,10 +2071,10 @@ Details follow: } ``` -- [Persistable](#persistable-protocol) is able to **write**: it can create, update, and delete rows in the database: +- [EncodableRecord] is able to **write**: it can create, update, and delete rows in the database: ```swift - struct Place : Persistable { ... } + struct Place : EncodableRecord { ... } try dbQueue.inDatabase { db in try Place.delete(db, key: 1) try Place(...).insert(db) @@ -2204,12 +2204,12 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci ``` -## Persistable Protocol +## EncodableRecord Protocol **GRDB provides two protocols that let adopting types create, update, and delete rows in the database:** ```swift -protocol MutablePersistable : TableRecord { +protocol MutableEncodableRecord : TableRecord { /// The name of the database table (from TableRecord) static var databaseTableName: String { get } @@ -2223,7 +2223,7 @@ protocol MutablePersistable : TableRecord { ``` ```swift -protocol Persistable : MutablePersistable { +protocol EncodableRecord : MutableEncodableRecord { /// Non-mutating version of the optional didInsert(with:for:) func didInsert(with rowID: Int64, for column: String?) } @@ -2231,11 +2231,11 @@ protocol Persistable : MutablePersistable { Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other: -- *If your type is a struct that mutates on insertion*, choose `MutablePersistable`. +- *If your type is a struct that mutates on insertion*, choose `MutableEncodableRecord`. For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion. -- Otherwise, stick with `Persistable`. Particularly if your type is a class. +- Otherwise, stick with `EncodableRecord`. Particularly if your type is a class. The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns. @@ -2246,7 +2246,7 @@ The optional `didInsert` method lets the adopting type store its rowID after suc **To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitely. For example: ```swift -extension Place : MutablePersistable { +extension Place : MutableEncodableRecord { /// The values persisted in the database func encode(to container: inout PersistenceContainer) { @@ -2274,7 +2274,7 @@ paris.id // some value Persistence containers also accept keys of type `Column`: ```swift -extension Place : MutablePersistable { +extension Place : MutableEncodableRecord { enum Columns { static let id = Column("id") static let title = Column("title") @@ -2294,7 +2294,7 @@ extension Place : MutablePersistable { ### Persistence Methods -[Record](#record-class) subclasses and types that adopt [Persistable](#persistable-protocol) are given default implementations for methods that insert, update, and delete: +[Record](#record-class) subclasses and types that adopt [EncodableRecord] are given default implementations for methods that insert, update, and delete: ```swift // Instance methods @@ -2351,10 +2351,10 @@ class Player : Record { } ``` -If you use the raw [Persistable](#persistable-protocol) protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: +If you use the raw [EncodableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: ```swift -struct Link : Persistable { +struct Link : EncodableRecord { var url: URL func insert(_ db: Database) throws { @@ -2384,7 +2384,7 @@ struct Link : Persistable { [Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4. -GRDB provides default implementations for [`DecodableRecord.init(row:)`](#decodablerecord-protocol) and [`Persistable.encode(to:)`](#persistable-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: +GRDB provides default implementations for [`DecodableRecord.init(row:)`](#decodablerecord-protocol) and [`EncodableRecord.encode(to:)`](#encodablerecord-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: ```swift // Declare a plain Codable struct or class... @@ -2394,7 +2394,7 @@ struct Player: Codable { } // Adopt Record protocols... -extension Player: DecodableRecord, Persistable { +extension Player: DecodableRecord, EncodableRecord { static let databaseTableName = "players" } @@ -2409,7 +2409,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: -struct Place: DecodableRecord, Persistable, Codable { +struct Place: DecodableRecord, EncodableRecord, Codable { static let databaseTableName = "places" var title: String @@ -2441,14 +2441,14 @@ struct Place: Codable { } // Free database support! -extension Place: DecodableRecord, Persistable { +extension Place: DecodableRecord, EncodableRecord { static let databaseTableName = "places" } ``` GRDB ships with support for nested codable records, but this is a more complex topic. See [Joined Queries Support](#joined-queries-support) for more information. -As documented with the [Persistable](#persistable-protocol) protocol, have your struct records use MutablePersistable instead of Persistable when they store their automatically incremented row id: +As documented with the [EncodableRecord] protocol, have your struct records use MutableEncodableRecord instead of EncodableRecord when they store their automatically incremented row id: ```swift struct Place: Codable { @@ -2459,7 +2459,7 @@ struct Place: Codable { var coordinate: CLLocationCoordinate2D { ... } } -extension Place: DecodableRecord, MutablePersistable { +extension Place: DecodableRecord, MutableEncodableRecord { static let databaseTableName = "places" mutating func didInsert(with rowID: Int64, for column: String?) { @@ -2479,7 +2479,7 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableRecord, and Persistable](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableRecord, and EncodableRecord](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). Record subclasses define their custom database relationship by overriding database methods: @@ -2526,7 +2526,7 @@ class Place : Record { The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless. -You can use instead the `updateChanges` method, available on the [Persistable](#persistable-protocol) protocol, which performs an update of the changed columns only (and does nothing if record has no change): +You can use instead the `updateChanges` method, available on the [EncodableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): ```swift let oldPlayer = try Player.fetchOne(db, ...) @@ -2539,7 +2539,7 @@ if try newPlayer.updateChanges(db, from: oldPlayer) { } ``` -> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a Persistable protocol, you don't need to care about Equatable. +> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a EncodableRecord protocol, you don't need to care about Equatable. The [Record](#record-class) class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: @@ -2639,10 +2639,10 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` -When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutablePersistable or Persistable protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): +When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutableEncodableRecord or EncodableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): ```swift -protocol MutablePersistable { +protocol MutableEncodableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -2652,7 +2652,7 @@ protocol MutablePersistable { static var persistenceConflictPolicy: PersistenceConflictPolicy { get } } -struct Player : MutablePersistable { +struct Player : MutableEncodableRecord { static let persistenceConflictPolicy = PersistenceConflictPolicy( insert: .replace, update: .replace) @@ -2759,10 +2759,10 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu event.id // some value ``` -3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [Persistable and MutablePersistable](#persistable-protocol) protocols): +3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [EncodableRecord and MutableEncodableRecord](#encodablerecord-protocol) protocols): ```swift - struct Event : MutablePersistable { + struct Event : MutableEncodableRecord { var id: Int64? func encode(to container: inout PersistenceContainer) { @@ -2805,26 +2805,26 @@ This is the list of record methods, along with their required protocols. The [Re | `init(row:)` | [DecodableRecord] | | | `Type.databaseTableName` | [TableRecord] | | | `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | -| `Type.persistenceConflictPolicy` | [Persistable](#persistable-protocol) | [*](#conflict-resolution) | -| `record.encode(to:)` | [Persistable](#persistable-protocol) | | -| `record.didInsert(with:for:)` | [Persistable](#persistable-protocol) | | +| `Type.persistenceConflictPolicy` | [EncodableRecord] | [*](#conflict-resolution) | +| `record.encode(to:)` | [EncodableRecord] | | +| `record.didInsert(with:for:)` | [EncodableRecord] | | | **Insert and Update Records** | | | -| `record.insert(db)` | [Persistable](#persistable-protocol) | | -| `record.save(db)` | [Persistable](#persistable-protocol) | | -| `record.update(db)` | [Persistable](#persistable-protocol) | | -| `record.update(db, columns:...)` | [Persistable](#persistable-protocol) | | -| `record.updateChanges(db, from:...)` | [Persistable](#persistable-protocol) | | +| `record.insert(db)` | [EncodableRecord] | | +| `record.save(db)` | [EncodableRecord] | | +| `record.update(db)` | [EncodableRecord] | | +| `record.update(db, columns:...)` | [EncodableRecord] | | +| `record.updateChanges(db, from:...)` | [EncodableRecord] | | | `record.updateChanges(db)` | [Record](#record-class) | | | **Delete Records** | | | -| `record.delete(db)` | [Persistable](#persistable-protocol) | | -| `Type.deleteOne(db, key:...)` | [Persistable](#persistable-protocol) | ¹ | -| `Type.deleteAll(db)` | [Persistable](#persistable-protocol) | | -| `Type.deleteAll(db, keys:...)` | [Persistable](#persistable-protocol) | ¹ | -| `Type.filter(...).deleteAll(db)` | [Persistable](#persistable-protocol) | ² | +| `record.delete(db)` | [EncodableRecord] | | +| `Type.deleteOne(db, key:...)` | [EncodableRecord] | ¹ | +| `Type.deleteAll(db)` | [EncodableRecord] | | +| `Type.deleteAll(db, keys:...)` | [EncodableRecord] | ¹ | +| `Type.filter(...).deleteAll(db)` | [EncodableRecord] | ² | | **Check Record Existence** | | | -| `record.exists(db)` | [Persistable](#persistable-protocol) | | +| `record.exists(db)` | [EncodableRecord] | | | **Convert Record to Dictionary** | | | -| `record.databaseDictionary` | [Persistable](#persistable-protocol) | | +| `record.databaseDictionary` | [EncodableRecord] | | | **Count Records** | | | | `Type.fetchCount(db)` | [TableRecord] | | | `Type.filter(...).fetchCount(db)` | [TableRecord] | ² | @@ -2847,9 +2847,9 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.fetchOne(statement)` | [DecodableRecord] | ⁴ | | `Type.filter(...).fetchOne(db)` | [DecodableRecord] & [TableRecord] | ² | | **[Changes Tracking](#changes-tracking)** | | | -| `record.databaseEqual(...)` | [Persistable](#persistable-protocol) | | -| `record.databaseChanges(from:...)` | [Persistable](#persistable-protocol) | | -| `record.updateChanges(db, from:...)` | [Persistable](#persistable-protocol) | | +| `record.databaseEqual(...)` | [EncodableRecord] | | +| `record.databaseChanges(from:...)` | [EncodableRecord] | | +| `record.updateChanges(db, from:...)` | [EncodableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | @@ -3663,7 +3663,7 @@ let request = Player.filter(emailColumn == nil) try request.deleteAll(db) ``` -> :point_up: **Note** Deletion methods are only available for records that adopts the [Persistable](#persistable-protocol) protocol. +> :point_up: **Note** Deletion methods are only available for records that adopts the [EncodableRecord] protocol. **Deleting records according to their primary key** is also quite common. It has a shortcut which accepts any single-column primary key: @@ -5849,7 +5849,7 @@ do { ### PersistenceError -**PersistenceError** is thrown by the [Persistable](#persistable-protocol) protocol, in a single case: when the `update` method could not find any row to update: +**PersistenceError** is thrown by the [EncodableRecord] protocol, in a single case: when the `update` method could not find any row to update: ```swift do { @@ -6916,6 +6916,10 @@ Sample Code Legacy ====== +#### Persistable Protocol + +This protocol has been renamed [EncodableRecord] in GRDB 3.0. + #### RowConvertible Protocol This protocol has been renamed [DecodableRecord] in GRDB 3.0. @@ -6925,4 +6929,5 @@ This protocol has been renamed [DecodableRecord] in GRDB 3.0. This protocol has been renamed [TableRecord] in GRDB 3.0. [DecodableRecord]: #decodablerecord-protocol +[EncodableRecord]: #encodablerecord-protocol [TableRecord]: #tablerecord-protocol diff --git a/TODO.md b/TODO.md index 3223fc981..c1c598c8b 100644 --- a/TODO.md +++ b/TODO.md @@ -24,18 +24,18 @@ GRDB 3.0 - [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: - 1. Make save() impossible to customize: remove it from Persistable protocol, and remove performSave() from tne public API. + 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. 2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type. -- [ ] Not sure: Make the MutablePersistable.update(_:columns:) method mutating (as support for an updatedDate column). If so, allow type to change the set of changed columns. +- [ ] Not sure: Make the MutableEncodableRecord.update(_:columns:) method mutating (as support for an updatedDate column). If so, allow type to change the set of changed columns. - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename RowConvertible, TableRecord, MutablePersistable and Persistable so that their names contain Record: FetchableRecord, TableRecord, MutablePersistableRecord, PersistableRecord? -- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutablePersistableRecord. This would allow keeping fetching and persistence methods private in some files. +- [ ] Rename RowConvertible, TableRecord, MutableEncodableRecord and EncodableRecord so that their names contain Record: FetchableRecord, TableRecord, MutableEncodableRecordRecord, EncodableRecordRecord? +- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutableEncodableRecordRecord. This would allow keeping fetching and persistence methods private in some files. - [X] Drop IteratorCursor, use AnyCursor instead - [X] Rename TypedRequest to FetchRequest, drop Request - [ ] Rename columnCount -> numberOfColumns -- [ ] Try to remove double Persistable/MutablePersistable protocols: Would non-mutating Record methods help? +- [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? Not sure diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 7a7f9c1e8..fe2a4e959 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -110,27 +110,27 @@ private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer { } #endif -// MARK: - MutablePersistable +// MARK: - MutableEncodableRecord -private struct UserMutablePersistable1 : MutablePersistable { - static let databaseTableName = "UserMutablePersistable1" +private struct UserMutableEncodableRecord1 : MutableEncodableRecord { + static let databaseTableName = "UserMutableEncodableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserMutablePersistable2 : MutablePersistable { - static let databaseTableName = "UserMutablePersistable2" +private class UserMutableEncodableRecord2 : MutableEncodableRecord { + static let databaseTableName = "UserMutableEncodableRecord2" func encode(to container: inout PersistenceContainer) { } } -// MARK: - Persistable +// MARK: - EncodableRecord -private struct UserPersistable1 : Persistable { - static let databaseTableName = "UserPersistable1" +private struct UserEncodableRecord1 : EncodableRecord { + static let databaseTableName = "UserEncodableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserPersistable2 : Persistable { - static let databaseTableName = "UserPersistable2" +private class UserEncodableRecord2 : EncodableRecord { + static let databaseTableName = "UserEncodableRecord2" func encode(to container: inout PersistenceContainer) { } } diff --git a/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift index 61bd7f54d..657ac2e45 100644 --- a/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift @@ -21,7 +21,7 @@ extension Reader : DecodableRecord { } } -extension Reader : MutablePersistable { +extension Reader : MutableEncodableRecord { static let databaseTableName = "readers" func encode(to container: inout PersistenceContainer) { diff --git a/Tests/GRDBTests/PersistableTests.swift b/Tests/GRDBTests/EncodableRecordTests.swift similarity index 85% rename from Tests/GRDBTests/PersistableTests.swift rename to Tests/GRDBTests/EncodableRecordTests.swift index e615cdae6..86ccb3c8d 100644 --- a/Tests/GRDBTests/PersistableTests.swift +++ b/Tests/GRDBTests/EncodableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct PersistablePerson : Persistable { +private struct EncodableRecordPerson : EncodableRecord { var name: String? var age: Int? @@ -19,7 +19,7 @@ private struct PersistablePerson : Persistable { } } -private class PersistablePersonClass : Persistable { +private class EncodableRecordPersonClass : EncodableRecord { var id: Int64? var name: String? var age: Int? @@ -44,7 +44,7 @@ private class PersistablePersonClass : Persistable { } } -private struct PersistableCountry : Persistable { +private struct EncodableRecordCountry : EncodableRecord { var isoCode: String var name: String @@ -56,7 +56,7 @@ private struct PersistableCountry : Persistable { } } -private struct PersistableCustomizedCountry : Persistable { +private struct EncodableRecordCustomizedCountry : EncodableRecord { var isoCode: String var name: String let willInsert: () -> Void @@ -98,7 +98,7 @@ private struct PersistableCustomizedCountry : Persistable { } } -private struct Citizenship : Persistable { +private struct Citizenship : EncodableRecord { let personID: Int64 let countryIsoCode: String @@ -110,7 +110,7 @@ private struct Citizenship : Persistable { } } -class PersistableTests: GRDBTestCase { +class EncodableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -132,12 +132,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistablePerson + // MARK: - EncodableRecordPerson - func testInsertPersistablePerson() throws { + func testInsertEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePerson(name: "Arthur", age: 42) + let person = EncodableRecordPerson(name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -146,10 +146,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistablePerson() throws { + func testSaveEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePerson(name: "Arthur", age: 42) + let person = EncodableRecordPerson(name: "Arthur", age: 42) try person.save(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -159,12 +159,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistablePersonClass + // MARK: - EncodableRecordPersonClass - func testInsertPersistablePersonClass() throws { + func testInsertEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -174,12 +174,12 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistablePersonClass() throws { + func testUpdateEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) person1.name = "Craig" @@ -198,12 +198,12 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistablePersonClass() throws { + func testPartialUpdateEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 24) + let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 24) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 36) + let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -254,10 +254,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistablePersonClass() throws { + func testSaveEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -265,7 +265,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.save(db) person1.name = "Craig" @@ -290,12 +290,12 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistablePersonClass() throws { + func testDeleteEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = PersistablePersonClass(id: nil, name: "Barbara", age: 39) + let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) var deleted = try person1.delete(db) @@ -310,10 +310,10 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistablePersonClass() throws { + func testExistsEncodableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 42) + let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -323,12 +323,12 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistableCountry + // MARK: - EncodableRecordCountry - func testInsertPersistableCountry() throws { + func testInsertEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = PersistableCountry(isoCode: "FR", name: "France") + let country = EncodableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -338,12 +338,12 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistableCountry() throws { + func testUpdateEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -359,12 +359,12 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistableCountry() throws { + func testPartialUpdateEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) do { @@ -395,10 +395,10 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistableCountry() throws { + func testSaveEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = PersistableCountry(isoCode: "FR", name: "France") + var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -406,7 +406,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -431,12 +431,12 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistableCountry() throws { + func testDeleteEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country1 = PersistableCountry(isoCode: "FR", name: "France") + let country1 = EncodableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = PersistableCountry(isoCode: "US", name: "United States") + let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -451,10 +451,10 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistableCountry() throws { + func testExistsEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = PersistableCountry(isoCode: "FR", name: "France") + let country = EncodableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -464,9 +464,9 @@ class PersistableTests: GRDBTestCase { } - // MARK: - PersistableCustomizedCountry + // MARK: - EncodableRecordCustomizedCountry - func testInsertPersistableCustomizedCountry() throws { + func testInsertEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -474,7 +474,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = PersistableCustomizedCountry( + let country = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -497,7 +497,7 @@ class PersistableTests: GRDBTestCase { } } - func testUpdatePersistableCustomizedCountry() throws { + func testUpdateEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -505,7 +505,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -514,7 +514,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = EncodableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -543,7 +543,7 @@ class PersistableTests: GRDBTestCase { } } - func testPartialUpdatePersistableCustomizedCountry() throws { + func testPartialUpdateEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -551,7 +551,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -560,7 +560,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = EncodableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -589,7 +589,7 @@ class PersistableTests: GRDBTestCase { } } - func testSavePersistableCustomizedCountry() throws { + func testSaveEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -597,7 +597,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = PersistableCustomizedCountry( + var country1 = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -618,7 +618,7 @@ class PersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = PersistableCustomizedCountry( + let country2 = EncodableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -662,7 +662,7 @@ class PersistableTests: GRDBTestCase { } } - func testDeletePersistableCustomizedCountry() throws { + func testDeleteEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -670,7 +670,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country1 = PersistableCustomizedCountry( + let country1 = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -679,7 +679,7 @@ class PersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = PersistableCustomizedCountry( + let country2 = EncodableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -707,7 +707,7 @@ class PersistableTests: GRDBTestCase { } } - func testExistsPersistableCustomizedCountry() throws { + func testExistsEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -715,7 +715,7 @@ class PersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = PersistableCustomizedCountry( + let country = EncodableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -749,9 +749,9 @@ class PersistableTests: GRDBTestCase { func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = PersistablePersonClass(id: nil, name: "Arthur", age: 12) + let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 12) try person.insert(db) - try PersistableCountry(isoCode: "FR", name: "France").insert(db) + try EncodableRecordCountry(isoCode: "FR", name: "France").insert(db) do { try Citizenship(personID: person.id!, countryIsoCode: "US").insert(db) } catch let error as DatabaseError { diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index 22dc0c7ac..fd799dbe7 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -23,7 +23,7 @@ extension Book : DecodableRecord { } } -extension Book : MutablePersistable { +extension Book : MutableEncodableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 61cbee6fc..c590d09ce 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -23,7 +23,7 @@ extension Book : DecodableRecord { } } -extension Book : MutablePersistable { +extension Book : MutableEncodableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 985cbd642..4984b62a8 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -24,7 +24,7 @@ extension Book : DecodableRecord { } } -extension Book : MutablePersistable { +extension Book : MutableEncodableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index e505717f3..c9c0fac79 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -131,7 +131,7 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)") } - func assert(_ record: MutablePersistable, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { + func assert(_ record: MutableEncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) diff --git a/Tests/GRDBTests/MutablePersistableChangesTests.swift b/Tests/GRDBTests/MutableEncodableRecordChangesTests.swift similarity index 97% rename from Tests/GRDBTests/MutablePersistableChangesTests.swift rename to Tests/GRDBTests/MutableEncodableRecordChangesTests.swift index c5f015d5c..04d918c7d 100644 --- a/Tests/GRDBTests/MutablePersistableChangesTests.swift +++ b/Tests/GRDBTests/MutableEncodableRecordChangesTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct Player: DecodableRecord, MutablePersistable, Codable { +private struct Player: DecodableRecord, MutableEncodableRecord, Codable { static let databaseTableName = "players" var id: Int64? @@ -34,7 +34,7 @@ private struct Player: DecodableRecord, MutablePersistable, Codable { } } -class MutablePersistableChangesTests: GRDBTestCase { +class MutableEncodableRecordChangesTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in @@ -47,7 +47,7 @@ class MutablePersistableChangesTests: GRDBTestCase { } func testDegenerateDatabaseEqualWithSelf() throws { - struct DegenerateRecord: MutablePersistable { + struct DegenerateRecord: MutableEncodableRecord { static let databaseTableName = "ignored" func encode(to container: inout PersistenceContainer) { } @@ -174,7 +174,7 @@ class MutablePersistableChangesTests: GRDBTestCase { func testDatabaseEqualWithDifferentTypesAndDifferentWidth() throws { // Mangle column case as well, for fun ;-) - struct NarrowPlayer: MutablePersistable, Codable { + struct NarrowPlayer: MutableEncodableRecord, Codable { static let databaseTableName = "players" var ID: Int64? var NAME: String? diff --git a/Tests/GRDBTests/MutablePersistableDeleteTests.swift b/Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift similarity index 97% rename from Tests/GRDBTests/MutablePersistableDeleteTests.swift rename to Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift index db1b2d276..d0455f179 100644 --- a/Tests/GRDBTests/MutablePersistableDeleteTests.swift +++ b/Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift @@ -7,23 +7,23 @@ import XCTest import GRDB #endif -private struct Hacker : MutablePersistable { +private struct Hacker : MutableEncodableRecord { static let databaseTableName = "hackers" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Person : MutablePersistable { +private struct Person : MutableEncodableRecord { static let databaseTableName = "persons" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Citizenship : MutablePersistable { +private struct Citizenship : MutableEncodableRecord { static let databaseTableName = "citizenships" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -class MutablePersistableDeleteTests: GRDBTestCase { +class MutableEncodableRecordDeleteTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in diff --git a/Tests/GRDBTests/MutablePersistableEncodableTests.swift b/Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift similarity index 92% rename from Tests/GRDBTests/MutablePersistableEncodableTests.swift rename to Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift index 0f128339d..7d270ebf7 100644 --- a/Tests/GRDBTests/MutablePersistableEncodableTests.swift +++ b/Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift @@ -8,14 +8,14 @@ import Foundation import GRDB #endif -class MutablePersistableEncodableTests: GRDBTestCase { } +class MutableEncodableRecordEncodableTests: GRDBTestCase { } -// MARK: - MutablePersistable conformance derived from Encodable +// MARK: - MutableEncodableRecord conformance derived from Encodable -extension MutablePersistableEncodableTests { +extension MutableEncodableRecordEncodableTests { func testTrivialEncodable() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: String } @@ -36,7 +36,7 @@ extension MutablePersistableEncodableTests { } func testCustomEncodable() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: String @@ -65,13 +65,13 @@ extension MutablePersistableEncodableTests { } } - func testCustomMutablePersistable() throws { - struct Struct : MutablePersistable, Encodable { + func testCustomMutableEncodableRecord() throws { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: String func encode(to container: inout PersistenceContainer) { - container["value"] = value + " (MutablePersistable)" + container["value"] = value + " (MutableEncodableRecord)" } } @@ -82,21 +82,21 @@ extension MutablePersistableEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["value": "foo (MutablePersistable)"]) + assert(value, isEncodedIn: ["value": "foo (MutableEncodableRecord)"]) try value.insert(db) let string = try String.fetchOne(db, "SELECT value FROM t1")! - XCTAssertEqual(string, "foo (MutablePersistable)") + XCTAssertEqual(string, "foo (MutableEncodableRecord)") } } } // MARK: - Different kinds of single-value properties -extension MutablePersistableEncodableTests { +extension MutableEncodableRecordEncodableTests { func testTrivialProperty() throws { - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let int64: Int64 let optionalInt64: Int64? @@ -141,7 +141,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -195,7 +195,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -240,7 +240,7 @@ extension MutablePersistableEncodableTests { case foo, bar } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -303,7 +303,7 @@ extension MutablePersistableEncodableTests { } } - struct Struct : MutablePersistable, Encodable { + struct Struct : MutableEncodableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -341,10 +341,10 @@ extension MutablePersistableEncodableTests { // MARK: - Foundation Codable Types -extension MutablePersistableEncodableTests { +extension MutableEncodableRecordEncodableTests { func testStructWithDate() throws { - struct StructWithDate : Persistable, Encodable { + struct StructWithDate : EncodableRecord, Encodable { static let databaseTableName = "t1" let date: Date } @@ -371,7 +371,7 @@ extension MutablePersistableEncodableTests { } func testStructWithURL() throws { - struct StructWithURL : Persistable, Encodable { + struct StructWithURL : EncodableRecord, Encodable { static let databaseTableName = "t1" let url: URL } @@ -394,7 +394,7 @@ extension MutablePersistableEncodableTests { } func testStructWithUUID() throws { - struct StructWithUUID : Persistable, Encodable { + struct StructWithUUID : EncodableRecord, Encodable { static let databaseTableName = "t1" let uuid: UUID } diff --git a/Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift similarity index 95% rename from Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift rename to Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift index a076d0f49..ca7a75ee4 100644 --- a/Tests/GRDBTests/MutablePersistablePersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct DefaultPolicy: MutablePersistable { +private struct DefaultPolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -21,7 +21,7 @@ private struct DefaultPolicy: MutablePersistable { } } -private struct MixedPolicy: MutablePersistable { +private struct MixedPolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -36,7 +36,7 @@ private struct MixedPolicy: MutablePersistable { } } -private struct ReplacePolicy: MutablePersistable { +private struct ReplacePolicy: MutableEncodableRecord { var id: Int64? var email: String @@ -53,7 +53,7 @@ private struct ReplacePolicy: MutablePersistable { } } -private struct IgnorePolicy: MutablePersistable { +private struct IgnorePolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -68,7 +68,7 @@ private struct IgnorePolicy: MutablePersistable { } } -private struct FailPolicy: MutablePersistable { +private struct FailPolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -83,7 +83,7 @@ private struct FailPolicy: MutablePersistable { } } -private struct AbortPolicy: MutablePersistable { +private struct AbortPolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -98,7 +98,7 @@ private struct AbortPolicy: MutablePersistable { } } -private struct RollbackPolicy: MutablePersistable { +private struct RollbackPolicy: MutableEncodableRecord { var id: Int64? static let databaseTableName = "records" @@ -113,7 +113,7 @@ private struct RollbackPolicy: MutablePersistable { } } -class MutablePersistablePersistenceConflictPolicyTests: GRDBTestCase { +class MutableEncodableRecordPersistenceConflictPolicyTests: GRDBTestCase { func testPolicyDefaultArguments() { let policy = PersistenceConflictPolicy() diff --git a/Tests/GRDBTests/MutablePersistableTests.swift b/Tests/GRDBTests/MutableEncodableRecordTests.swift similarity index 86% rename from Tests/GRDBTests/MutablePersistableTests.swift rename to Tests/GRDBTests/MutableEncodableRecordTests.swift index 5638f3d0d..f9f860fc9 100644 --- a/Tests/GRDBTests/MutablePersistableTests.swift +++ b/Tests/GRDBTests/MutableEncodableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct MutablePersistablePerson : MutablePersistable { +private struct MutableEncodableRecordPerson : MutableEncodableRecord { var id: Int64? var name: String? var age: Int? @@ -26,7 +26,7 @@ private struct MutablePersistablePerson : MutablePersistable { } } -private struct MutablePersistableCountry : MutablePersistable { +private struct MutableEncodableRecordCountry : MutableEncodableRecord { var rowID: Int64? var isoCode: String var name: String @@ -43,7 +43,7 @@ private struct MutablePersistableCountry : MutablePersistable { } } -private struct MutablePersistableCustomizedCountry : MutablePersistable { +private struct MutableEncodableRecordCustomizedCountry : MutableEncodableRecord { var rowID: Int64? var isoCode: String var name: String @@ -90,7 +90,7 @@ private struct MutablePersistableCustomizedCountry : MutablePersistable { } } -class MutablePersistableTests: GRDBTestCase { +class MutableEncodableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -109,12 +109,12 @@ class MutablePersistableTests: GRDBTestCase { } - // MARK: - MutablePersistablePerson + // MARK: - MutableEncodableRecordPerson - func testInsertMutablePersistablePerson() throws { + func testInsertMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -124,12 +124,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistablePerson() throws { + func testUpdateMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) person1.name = "Craig" @@ -148,12 +148,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testPartialUpdateMutablePersistablePerson() throws { + func testPartialUpdateMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 36) + var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -204,10 +204,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistablePerson() throws { + func testSaveMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -215,7 +215,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.save(db) person1.name = "Craig" @@ -240,12 +240,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistablePerson() throws { + func testDeleteMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutablePersistablePerson(id: nil, name: "Barbara", age: 24) + var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) var deleted = try person1.delete(db) @@ -260,10 +260,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistablePerson() throws { + func testExistsMutableEncodableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + var person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -272,18 +272,18 @@ class MutablePersistableTests: GRDBTestCase { } } - func testMutablePersistablePersonDatabaseDictionary() { - let person = MutablePersistablePerson(id: nil, name: "Arthur", age: 24) + func testMutableEncodableRecordPersonDatabaseDictionary() { + let person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) let dict = person.databaseDictionary XCTAssertEqual(dict, ["iD": DatabaseValue.null, "NAme": "Arthur".databaseValue, "aGe": 24.databaseValue]) } - // MARK: - MutablePersistableCountry + // MARK: - MutableEncodableRecordCountry - func testInsertMutablePersistableCountry() throws { + func testInsertMutableEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -293,12 +293,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistableCountry() throws { + func testUpdateMutableEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -314,10 +314,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistableCountry() throws { + func testSaveMutableEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -325,7 +325,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -350,12 +350,12 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistableCountry() throws { + func testDeleteMutableEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutablePersistableCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -370,10 +370,10 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistableCountry() throws { + func testExistsMutableEncodableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutablePersistableCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -383,9 +383,9 @@ class MutablePersistableTests: GRDBTestCase { } - // MARK: - MutablePersistableCustomizedCountry + // MARK: - MutableEncodableRecordCustomizedCountry - func testInsertMutablePersistableCustomizedCountry() throws { + func testInsertMutableEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -393,7 +393,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutablePersistableCustomizedCountry( + var country = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -417,7 +417,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testUpdateMutablePersistableCustomizedCountry() throws { + func testUpdateMutableEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -425,7 +425,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -435,7 +435,7 @@ class MutablePersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -465,7 +465,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testSaveMutablePersistableCustomizedCountry() throws { + func testSaveMutableEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -473,7 +473,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -495,7 +495,7 @@ class MutablePersistableTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -540,7 +540,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testDeleteMutablePersistableCustomizedCountry() throws { + func testDeleteMutableEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -548,7 +548,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutablePersistableCustomizedCountry( + var country1 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -558,7 +558,7 @@ class MutablePersistableTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutablePersistableCustomizedCountry( + var country2 = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -587,7 +587,7 @@ class MutablePersistableTests: GRDBTestCase { } } - func testExistsMutablePersistableCustomizedCountry() throws { + func testExistsMutableEncodableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -595,7 +595,7 @@ class MutablePersistableTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutablePersistableCustomizedCountry( + var country = MutableEncodableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -627,7 +627,7 @@ class MutablePersistableTests: GRDBTestCase { // MARK: - Misc func testPartiallyEncodedRecord() throws { - struct PartialRecord : MutablePersistable { + struct PartialRecord : MutableEncodableRecord { var id: Int64? var a: String diff --git a/Tests/GRDBTests/RecordBoxTests.swift b/Tests/GRDBTests/RecordBoxTests.swift index 81e800dfb..481590e47 100644 --- a/Tests/GRDBTests/RecordBoxTests.swift +++ b/Tests/GRDBTests/RecordBoxTests.swift @@ -10,7 +10,7 @@ import XCTest typealias RecordBox = GRDB.RecordBox // Single deprecation warning #endif -private struct Player: DecodableRecord, MutablePersistable, Codable { +private struct Player: DecodableRecord, MutableEncodableRecord, Codable { static let databaseTableName = "players" var id: Int64? diff --git a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift index 619322d4c..c6611fd02 100644 --- a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift +++ b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift @@ -20,14 +20,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase { func testDefaultPersistenceConflictPolicy() { let record = RecordWithoutPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistable).persistenceConflictPolicy + let policy = type(of: record as MutableEncodableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .abort) XCTAssertEqual(policy.conflictResolutionForUpdate, .abort) } func testConfigurablePersistenceConflictPolicy() { let record = RecordWithPersistenceConflictPolicy() - let policy = type(of: record as MutablePersistable).persistenceConflictPolicy + let policy = type(of: record as MutableEncodableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .fail) XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore) } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index d0c3dd945..3f9bf8730 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -100,7 +100,7 @@ private final class Artist: Codable { } } -extension Artist : DecodableRecord, Persistable { +extension Artist : DecodableRecord, EncodableRecord { static let databaseTableName = "artists" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID @@ -119,7 +119,7 @@ private final class Artwork : Codable { } } -extension Artwork : DecodableRecord, Persistable { +extension Artwork : DecodableRecord, EncodableRecord { static let databaseTableName = "artworks" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID diff --git a/Tests/Performance/PerformanceTests.swift b/Tests/Performance/PerformanceTests.swift index dfb0407a3..0e319e24f 100644 --- a/Tests/Performance/PerformanceTests.swift +++ b/Tests/Performance/PerformanceTests.swift @@ -7,7 +7,7 @@ import RealmSwift // MARK:- GRDB -struct ItemStruct : DecodableRecord, Persistable { +struct ItemStruct : DecodableRecord, EncodableRecord { var i0: Int var i1: Int var i2: Int diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index d44ba94fb..c3ce2678b 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -48,7 +48,7 @@ All tests use the default settings of each library. For each library, we: - Build and consume database rows with raw SQL and column indexes (aiming at the best performance) - Build and consume database rows with column names (sacrificing performance for maintainability) - Build and consume records values to and from database rows (aiming at the shortest code from database to records) -- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift#changes-tracking) (records know if they have unsaved changes) +- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) (records know if they have unsaved changes) As a bottom line, the raw SQLite C API is used as efficiently as possible, without any error checking. @@ -103,11 +103,11 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift#decodablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#decodablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [Persistable](https://github.com/groue/GRDB.swift#persistable-protocol) protocol. + This tests inserts 20000 records with the persistence method provided by GRDB's [EncodableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#encodablerecord-protocol) protocol. - **Records with change tracking**: @@ -115,9 +115,9 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift#record-class) class. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordClassTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift#record-class) class. + This tests inserts 20000 records with the persistence method provided by GRDB's [Record](https://github.com/groue/GRDB.swift/blob/master/README.md#record-class) class. REPORT From 1a91020a8406b031141a17883a47293a2ca62528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 19:25:49 +0100 Subject: [PATCH 022/348] After all, FetchableRecord and PersistableRecord --- Documentation/WhyAdoptGRDB.md | 12 +- GRDB.xcodeproj/project.pbxproj | 200 +++++++------- GRDB/Core/Database+Schema.swift | 2 +- GRDB/Core/FetchRequest.swift | 2 +- GRDB/Core/Row.swift | 4 +- GRDB/Legacy/Fixits-0-90-1.swift | 4 +- .../QueryInterfaceRequest.swift | 2 +- ....swift => FetchableRecord+Decodable.swift} | 2 +- ...wift => FetchableRecord+TableRecord.swift} | 6 +- ...ableRecord.swift => FetchableRecord.swift} | 18 +- GRDB/Record/FetchedRecordsController.swift | 16 +- ...wift => PersistableRecord+Encodable.swift} | 14 +- ...leRecord.swift => PersistableRecord.swift} | 88 +++--- GRDB/Record/Record.swift | 4 +- GRDB/Record/RecordBox.swift | 10 +- GRDB/Record/TableRecord.swift | 2 +- GRDBCipher.xcodeproj/project.pbxproj | 252 +++++++++--------- GRDBCustom.xcodeproj/project.pbxproj | 180 ++++++------- .../Issue156.playground/Contents.swift | 2 +- Playgrounds/Tour.playground/Contents.swift | 8 +- README.md | 202 +++++++------- .../GRDBTests/CompilationProtocolTests.swift | 26 +- Tests/GRDBTests/FTS3RecordTests.swift | 4 +- Tests/GRDBTests/FTS4RecordTests.swift | 4 +- Tests/GRDBTests/FTS5RecordTests.swift | 4 +- Tests/GRDBTests/FetchRequestTests.swift | 2 +- ...leRecord+QueryInterfaceRequestTests.swift} | 10 +- ...ft => FetchableRecordDecodableTests.swift} | 38 +-- ...Tests.swift => FetchableRecordTests.swift} | 4 +- .../FetchedRecordsControllerTests.swift | 4 +- Tests/GRDBTests/GRDBTestCase.swift | 2 +- Tests/GRDBTests/JoinSupportTests.swift | 16 +- ...utablePersistableRecordChangesTests.swift} | 8 +- ...MutablePersistableRecordDeleteTests.swift} | 8 +- ...ablePersistableRecordEncodableTests.swift} | 40 +-- ...ecordPersistenceConflictPolicyTests.swift} | 16 +- ...ft => MutablePersistableRecordTests.swift} | 104 ++++---- ...sts.swift => PersistableRecordTests.swift} | 128 ++++----- Tests/GRDBTests/RecordBoxTests.swift | 2 +- .../RecordPersistenceConflictPolicy.swift | 4 +- Tests/GRDBTests/RecordUniqueIndexTests.swift | 2 +- .../GRDBTests/TransactionObserverTests.swift | 4 +- Tests/Performance/PerformanceTests.swift | 2 +- Tests/generatePerformanceReport.rb | 4 +- 44 files changed, 733 insertions(+), 733 deletions(-) rename GRDB/Record/{DecodableRecord+Decodable.swift => FetchableRecord+Decodable.swift} (99%) rename GRDB/Record/{DecodableRecord+TableRecord.swift => FetchableRecord+TableRecord.swift} (97%) rename GRDB/Record/{DecodableRecord.swift => FetchableRecord.swift} (95%) rename GRDB/Record/{EncodableRecord+Encodable.swift => PersistableRecord+Encodable.swift} (95%) rename GRDB/Record/{EncodableRecord.swift => PersistableRecord.swift} (94%) rename Tests/GRDBTests/{DecodableRecord+QueryInterfaceRequestTests.swift => FetchableRecord+QueryInterfaceRequestTests.swift} (96%) rename Tests/GRDBTests/{DecodableRecordDecodableTests.swift => FetchableRecordDecodableTests.swift} (89%) rename Tests/GRDBTests/{DecodableRecordTests.swift => FetchableRecordTests.swift} (99%) rename Tests/GRDBTests/{MutableEncodableRecordChangesTests.swift => MutablePersistableRecordChangesTests.swift} (97%) rename Tests/GRDBTests/{MutableEncodableRecordDeleteTests.swift => MutablePersistableRecordDeleteTests.swift} (97%) rename Tests/GRDBTests/{MutableEncodableRecordEncodableTests.swift => MutablePersistableRecordEncodableTests.swift} (91%) rename Tests/GRDBTests/{MutableEncodableRecordPersistenceConflictPolicyTests.swift => MutablePersistableRecordPersistenceConflictPolicyTests.swift} (95%) rename Tests/GRDBTests/{MutableEncodableRecordTests.swift => MutablePersistableRecordTests.swift} (86%) rename Tests/GRDBTests/{EncodableRecordTests.swift => PersistableRecordTests.swift} (85%) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 12119bcc2..db582af51 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -65,10 +65,10 @@ struct Place { } ``` -By adopting the [DecodableRecord] protocol, places can be loaded from SQL requests: +By adopting the [FetchableRecord] protocol, places can be loaded from SQL requests: ```swift -extension Place: DecodableRecord { ... } +extension Place: FetchableRecord { ... } let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] ``` @@ -79,10 +79,10 @@ extension Place: TableRecord { ... } let place = try Place.fetchOne(db, key: 1) // Place? ``` -Add the [EncodableRecord] protocol, and places know how to insert, update and delete themselves: +Add the [PersistableRecord] protocol, and places know how to insert, update and delete themselves: ```swift -extension Place: EncodableRecord { ... } +extension Place: PersistableRecord { ... } try place.delete(db) ``` @@ -263,9 +263,9 @@ Happy GRDB! :gift: [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift [GRDBObjc]: http://github.com/groue/GRDBObjc -[EncodableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[PersistableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [Realm]: http://realm.io -[DecodableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [RxSwift]: https://github.com/ReactiveX/RxSwift [SQLite.swift]: http://github.com/stephencelis/SQLite.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 74b5c52eb..1d9908b7a 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -45,8 +45,8 @@ 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; }; 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; - 560D92471C672C4B00F4F92B /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; - 560D92481C672C4B00F4F92B /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; + 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; @@ -95,14 +95,14 @@ 562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; }; 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; - 56300B621C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56300B691C53D25E005A543B /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; }; 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 563363B01C933FF8000BE133 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 563363B21C933FF8000BE133 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; @@ -183,7 +183,7 @@ 565490DE1D5AE252005622CB /* QueryInterfaceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */; }; 565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - 565490E11D5AE252005622CB /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; @@ -211,7 +211,7 @@ 5659F4A01EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A31EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; 5659F4A61EA8D997004A4992 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F49F1EA8D997004A4992 /* Result.swift */; }; - 565B0FF01BBC7D980098DE03 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */; }; 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */; }; 565EFAF21D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; @@ -237,8 +237,8 @@ 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84192041146100E50BFD /* DatabaseSnapshot.swift */; }; 566A8425204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; 566A8426204120B700E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84402041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */; }; - 566A84412041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -273,12 +273,12 @@ 5674A6EB1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F01F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6FB1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; - 5674A6FF1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; - 5674A7001F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7031F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; @@ -286,10 +286,10 @@ 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A7201F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7231F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; - 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; 567517C920131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; 567517CA20131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; @@ -420,8 +420,8 @@ 56A8C2471D1918F00096E9D4 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; }; 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746F1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021C91D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; - 56B021CD1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; @@ -459,9 +459,9 @@ 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F11EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; - 56CEB4F41EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; - 56CEB4F71EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F71EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; @@ -513,10 +513,10 @@ 56D496651D813076008276D7 /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; - 56D4966B1D81309E008276D7 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; 56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; }; 56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; @@ -550,10 +550,10 @@ 56D496901D81316E008276D7 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56D496921D81316E008276D7 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; - 56D496931D81316E008276D7 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 56D496931D81316E008276D7 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - 56D496951D81317B008276D7 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 56D496961D81317B008276D7 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */; }; @@ -577,9 +577,9 @@ 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; 56D507841F6D7B2F00AE1C5B /* InsertRecordStructTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */; }; - 56D51D001EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; - 56D51D031EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; - 56D51D061EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -622,7 +622,7 @@ 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45441D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -767,7 +767,7 @@ 560C981A1C0E22D300BF8471 /* GRDBOSXPerformanceTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXPerformanceTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; @@ -783,13 +783,13 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -819,7 +819,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -832,7 +832,7 @@ 5665F85C203EE6030084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A84192041146100E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; + 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -849,13 +849,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; @@ -941,7 +941,7 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; @@ -983,7 +983,7 @@ 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -997,7 +997,7 @@ 56D3BE701F4EB1900034C6D2 /* FetchRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchRecordStructTests.swift; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; 56D507821F6D7A4500AE1C5B /* InsertRecordStructTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InsertRecordStructTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1026,7 +1026,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1173,17 +1173,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, - 566A843F2041914000E50BFD /* MutableEncodableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, + 566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = EncodableRecord; + name = PersistableRecord; sourceTree = ""; }; 56176C581EACC2D8000F3F2B /* GRDBTests */ = { @@ -1261,7 +1261,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, @@ -1330,13 +1330,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = DecodableRecord; + name = FetchableRecord; sourceTree = ""; }; 569530FA1C9067CC00CF1A2B /* Crash */ = { @@ -1491,10 +1491,10 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( - 5674A7251F30A8EF0095F066 /* DecodableRecord */, + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680520F201320E600E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1548,12 +1548,12 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 567517C720131B220094BF41 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -2170,7 +2170,7 @@ files = ( 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, - 56D51D061EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, 565490E41D5AE252005622CB /* TableRecord.swift in Sources */, 565490CF1D5AE252005622CB /* NSNumber.swift in Sources */, @@ -2206,13 +2206,13 @@ 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6FF1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A6FF1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 56E06F181E85906E008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56B964A31DA51B4C0002DA19 /* FTS5.swift in Sources */, 566475A01D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 565490BB1D5AE236005622CB /* DatabaseReader.swift in Sources */, 5659F4A61EA8D997004A4992 /* Result.swift in Sources */, - 5674A6F81F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F81F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, @@ -2238,12 +2238,12 @@ 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, 56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */, - 56CEB4F71EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F71EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56F5ABD91D814330001F60CB /* Data.swift in Sources */, 565490D41D5AE252005622CB /* (null) in Sources */, 566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 565490B61D5AE236005622CB /* Configuration.swift in Sources */, - 565490E11D5AE252005622CB /* EncodableRecord.swift in Sources */, + 565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */, 56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 565490E01D5AE252005622CB /* FetchedRecordsController.swift in Sources */, 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2293,7 +2293,7 @@ 56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */, - 5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F91F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2328,7 +2328,7 @@ 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, - 56D51D031EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 567517C920131B220094BF41 /* RecordBox.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, @@ -2343,12 +2343,12 @@ 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, - 5674A7001F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5674A6E91F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 566B91161FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56A238881B9C75030082EB20 /* Row.swift in Sources */, - 56CEB4F41EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, @@ -2366,7 +2366,7 @@ 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, - 560D92481C672C4B00F4F92B /* EncodableRecord.swift in Sources */, + 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, @@ -2391,7 +2391,7 @@ 56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */, 56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */, 56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, - 56FF45441D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */, 562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, 563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2419,7 +2419,7 @@ 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, - 56B021CD1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 569531271C9087B700CF1A2B /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2434,12 +2434,12 @@ 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */, - 563363B01C933FF8000BE133 /* MutableEncodableRecordTests.swift in Sources */, + 563363B01C933FF8000BE133 /* MutablePersistableRecordTests.swift in Sources */, 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, - 56300B621C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, @@ -2451,7 +2451,7 @@ 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */, 56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */, - 563363B21C933FF8000BE133 /* EncodableRecordTests.swift in Sources */, + 563363B21C933FF8000BE133 /* PersistableRecordTests.swift in Sources */, 56A238421B9C74A90082EB20 /* DatabaseValueConversionTests.swift in Sources */, 564E73E0203D50B9000C443C /* JoinSupportTests.swift in Sources */, 5674A7121F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2465,8 +2465,8 @@ 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5623935B1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, - 5674A72D1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 566A84412041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 566A84412041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */, 56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */, @@ -2477,7 +2477,7 @@ 5698AC441DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5698ACBA1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56176C6F1EACCCC9000F3F2B /* FTS5TokenizerTests.swift in Sources */, - 565B0FF01BBC7D980098DE03 /* DecodableRecordTests.swift in Sources */, + 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */, 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2511,7 +2511,7 @@ 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, - 5674A7231F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, @@ -2560,7 +2560,7 @@ 56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */, - 56D4966B1D81309E008276D7 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, @@ -2575,7 +2575,7 @@ 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 56D496AE1D813345008276D7 /* DatabasePoolCollationTests.swift in Sources */, 5698AC491DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, - 56D496931D81316E008276D7 /* DecodableRecordTests.swift in Sources */, + 56D496931D81316E008276D7 /* FetchableRecordTests.swift in Sources */, 56D496881D81316E008276D7 /* DatabaseValueConversionTests.swift in Sources */, 56D496BA1D813482008276D7 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */, @@ -2611,10 +2611,10 @@ 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, - 56D496961D81317B008276D7 /* EncodableRecordTests.swift in Sources */, + 56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */, 5698AC9E1DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, - 5674A72A1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, - 566A84402041914000E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, + 566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */, 56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */, @@ -2642,7 +2642,7 @@ 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, - 56B021C91D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */, 562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */, 56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */, @@ -2650,15 +2650,15 @@ 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56E5D8041B4D424400430942 /* GRDBTestCase.swift in Sources */, 567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 56D496681D813086008276D7 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, - 56D496951D81317B008276D7 /* MutableEncodableRecordTests.swift in Sources */, + 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, - 5674A7201F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, @@ -2691,7 +2691,7 @@ 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, - 56CEB4F11EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */, 5605F18D1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2711,7 +2711,7 @@ 5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */, 5659F4981EA8D989004A4992 /* Pool.swift in Sources */, - 5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F41F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54C1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2728,7 +2728,7 @@ 56CEB55A1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D2F1DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, - 56D51D001EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2756,7 +2756,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FB1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2767,7 +2767,7 @@ 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 567517C820131B220094BF41 /* RecordBox.swift in Sources */, - 560D92471C672C4B00F4F92B /* EncodableRecord.swift in Sources */, + 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 602be97d6..af1a5f6e4 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -325,7 +325,7 @@ extension Database { /// 2 score INTEGER 0 NULL 0 /// /// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info -public struct ColumnInfo : DecodableRecord { +public struct ColumnInfo : FetchableRecord { let cid: Int /// The column name diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index e8db16821..052bd312a 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,6 +1,6 @@ /// The protocol for all types that define a way to fetch database content. /// -/// struct Player: DecodableRecord { ... } +/// struct Player: FetchableRecord { ... } /// let request: ... // Some FetchRequest that fetches Player /// try request.fetchCursor(db) // Cursor of Player /// try request.fetchAll(db) // [Player] diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 8e222fb08..4c9678165 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -482,7 +482,7 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record { + public subscript(_ scope: String) -> Record { guard let scopedRow = scoped(on: scope) else { // Programmer error fatalError("no such scope: \(scope)") @@ -498,7 +498,7 @@ extension Row { /// /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. - public subscript(_ scope: String) -> Record? { + public subscript(_ scope: String) -> Record? { guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else { return nil } diff --git a/GRDB/Legacy/Fixits-0-90-1.swift b/GRDB/Legacy/Fixits-0-90-1.swift index 9dcb57781..cb886e4de 100644 --- a/GRDB/Legacy/Fixits-0-90-1.swift +++ b/GRDB/Legacy/Fixits-0-90-1.swift @@ -30,7 +30,7 @@ extension QueryInterfaceRequest { public func fetch(_ db: Database) -> Any { preconditionFailure() } } -extension DecodableRecord { +extension FetchableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") @@ -39,7 +39,7 @@ extension DecodableRecord { public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() } } -extension DecodableRecord where Self: TableRecord { +extension FetchableRecord where Self: TableRecord { @available(*, unavailable, renamed:"fetchCursor") public static func fetch(_ db: Database) -> Any { preconditionFailure() } @available(*, unavailable, renamed:"fetchCursor") diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 1242bfca7..c3b9d655e 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -365,7 +365,7 @@ extension QueryInterfaceRequest where T: TableRecord { } } -extension QueryInterfaceRequest where RowDecoder: MutableEncodableRecord { +extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { // MARK: Deleting diff --git a/GRDB/Record/DecodableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift similarity index 99% rename from GRDB/Record/DecodableRecord+Decodable.swift rename to GRDB/Record/FetchableRecord+Decodable.swift index 5871de4a6..65b973c06 100644 --- a/GRDB/Record/DecodableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -249,7 +249,7 @@ private struct RowDecoder: Decoder { } } -extension DecodableRecord where Self: Decodable { +extension FetchableRecord where Self: Decodable { /// Initializes a record from `row`. public init(row: Row) { try! self.init(from: RowDecoder(row: row, codingPath: [])) diff --git a/GRDB/Record/DecodableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift similarity index 97% rename from GRDB/Record/DecodableRecord+TableRecord.swift rename to GRDB/Record/FetchableRecord+TableRecord.swift index f5a529ab9..9cda45372 100644 --- a/GRDB/Record/DecodableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -1,4 +1,4 @@ -extension DecodableRecord where Self: TableRecord { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching All @@ -59,7 +59,7 @@ extension DecodableRecord where Self: TableRecord { } } -extension DecodableRecord where Self: TableRecord { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Single-Column Primary Key @@ -119,7 +119,7 @@ extension DecodableRecord where Self: TableRecord { } } -extension DecodableRecord where Self: TableRecord { +extension FetchableRecord where Self: TableRecord { // MARK: Fetching by Key diff --git a/GRDB/Record/DecodableRecord.swift b/GRDB/Record/FetchableRecord.swift similarity index 95% rename from GRDB/Record/DecodableRecord.swift rename to GRDB/Record/FetchableRecord.swift index cb3e4b1b0..aaf103b20 100644 --- a/GRDB/Record/DecodableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -4,7 +4,7 @@ import SQLite3 #endif -/// Types that adopt DecodableRecord can be initialized from a database Row. +/// Types that adopt FetchableRecord can be initialized from a database Row. /// /// let row = try Row.fetchOne(db, "SELECT ...")! /// let player = Player(row) @@ -21,8 +21,8 @@ /// try Player.fetchAll(statement, arguments:...) // [Player] /// try Player.fetchOne(statement, arguments:...) // Player? /// -/// DecodableRecord is adopted by Record. -public protocol DecodableRecord { +/// FetchableRecord is adopted by Record. +public protocol FetchableRecord { /// Creates a record from `row`. /// @@ -34,11 +34,11 @@ public protocol DecodableRecord { /// A cursor of records. For example: /// -/// struct Player : DecodableRecord { ... } +/// struct Player : FetchableRecord { ... } /// try dbQueue.inDatabase { db in /// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") /// } -public final class RecordCursor : Cursor { +public final class RecordCursor : Cursor { private let statement: SelectStatement private let row: Row // Reused for performance private let sqliteStatement: SQLiteStatement @@ -67,7 +67,7 @@ public final class RecordCursor : Cursor { } } -extension DecodableRecord { +extension FetchableRecord { // MARK: Fetching From SelectStatement @@ -125,7 +125,7 @@ extension DecodableRecord { } } -extension DecodableRecord { +extension FetchableRecord { // MARK: Fetching From SQL @@ -183,9 +183,9 @@ extension DecodableRecord { } } -extension FetchRequest where RowDecoder: DecodableRecord { +extension FetchRequest where RowDecoder: FetchableRecord { - // MARK: Fetching Record and DecodableRecord + // MARK: Fetching Record and FetchableRecord /// A cursor over fetched records. /// diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 515ad2d8d..0ab45362d 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -9,7 +9,7 @@ import Foundation /// /// See https://github.com/groue/GRDB.swift#fetchedrecordscontroller for /// more information. -public final class FetchedRecordsController { +public final class FetchedRecordsController { // MARK: - Initialization @@ -510,7 +510,7 @@ extension FetchedRecordsController where Record: TableRecord { /// FetchedRecordsController adopts TransactionObserverType so that it can /// monitor changes to its fetched records. -private final class FetchedRecordsObserver : TransactionObserver { +private final class FetchedRecordsObserver : TransactionObserver { var isValid: Bool var needsComputeChanges: Bool var items: [Item]! // ought to be not nil when observer has started tracking transactions @@ -861,8 +861,8 @@ private func identicalItemArrays(_ lhs: [Item], _ rhs: [Item = (Item, Item) -> Bool -private typealias ItemComparatorFactory = (Database) throws -> ItemComparator +private typealias ItemComparator = (Item, Item) -> Bool +private typealias ItemComparatorFactory = (Database) throws -> ItemComparator extension FetchedRecordsController { @@ -900,7 +900,7 @@ extension FetchedRecordsController { } } -extension FetchedRecordsController where Record: MutableEncodableRecord { +extension FetchedRecordsController where Record: MutablePersistableRecord { /// Returns the indexPath of a given record. /// @@ -915,7 +915,7 @@ extension FetchedRecordsController where Record: MutableEncodableRecord { } } -private enum ItemChange { +private enum ItemChange { case insertion(item: Item, indexPath: IndexPath) case deletion(item: Item, indexPath: IndexPath) case move(item: Item, indexPath: IndexPath, newIndexPath: IndexPath, changes: [String: DatabaseValue]) @@ -1010,7 +1010,7 @@ extension FetchedRecordChange: CustomStringConvertible { } /// A section given by a FetchedRecordsController. -public struct FetchedRecordsSectionInfo { +public struct FetchedRecordsSectionInfo { fileprivate let controller: FetchedRecordsController /// The number of records (rows) in the section. @@ -1035,7 +1035,7 @@ public struct FetchedRecordsSectionInfo { // MARK: - Item -private final class Item : DecodableRecord, Equatable { +private final class Item : FetchableRecord, Equatable { let row: Row // Records are lazily loaded diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/PersistableRecord+Encodable.swift similarity index 95% rename from GRDB/Record/EncodableRecord+Encodable.swift rename to GRDB/Record/PersistableRecord+Encodable.swift index 61e49a241..135e8a149 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/PersistableRecord+Encodable.swift @@ -1,4 +1,4 @@ -private struct EncodableRecordKeyedEncodingContainer : KeyedEncodingContainerProtocol { +private struct PersistableRecordKeyedEncodingContainer : KeyedEncodingContainerProtocol { let encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void init(encode: @escaping (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { @@ -40,7 +40,7 @@ private struct EncodableRecordKeyedEncodingContainer : KeyedEnco // This allows us to encode Date as String, for example. encode((value as! DatabaseValueConvertible), key.stringValue) } else { - try value.encode(to: EncodableRecordEncoder(codingPath: [key], encode: encode)) + try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode)) } } @@ -140,12 +140,12 @@ private struct DatabaseValueEncodingContainer : SingleValueEncodingContainer { // This allows us to encode Date as String, for example. encode(dbValueConvertible.databaseValue, key.stringValue) } else { - try value.encode(to: EncodableRecordEncoder(codingPath: [key], encode: encode)) + try value.encode(to: PersistableRecordEncoder(codingPath: [key], encode: encode)) } } } -private struct EncodableRecordEncoder : Encoder { +private struct PersistableRecordEncoder : Encoder { /// The path of coding keys taken to get to this point in encoding. /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] @@ -171,7 +171,7 @@ private struct EncodableRecordEncoder : Encoder { guard codingPath.isEmpty else { fatalError("unkeyed encoding is not supported") } - return KeyedEncodingContainer(EncodableRecordKeyedEncodingContainer(encode: encode)) + return KeyedEncodingContainer(PersistableRecordKeyedEncodingContainer(encode: encode)) } /// Returns an encoding container appropriate for holding multiple unkeyed values. @@ -194,7 +194,7 @@ private struct EncodableRecordEncoder : Encoder { } } -extension MutableEncodableRecord where Self: Encodable { +extension MutablePersistableRecord where Self: Encodable { public func encode(to container: inout PersistenceContainer) { // The inout container parameter won't enter an escaping closure since // SE-0035: https://github.com/apple/swift-evolution/blob/master/proposals/0035-limit-inout-capture.md @@ -202,7 +202,7 @@ extension MutableEncodableRecord where Self: Encodable { // So let's use it in a non-escaping closure: func encode(_ encode: (_ value: DatabaseValueConvertible?, _ key: String) -> Void) { withoutActuallyEscaping(encode) { escapableEncode in - let encoder = EncodableRecordEncoder(codingPath: [], encode: escapableEncode) + let encoder = PersistableRecordEncoder(codingPath: [], encode: escapableEncode) try! self.encode(to: encoder) } } diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/PersistableRecord.swift similarity index 94% rename from GRDB/Record/EncodableRecord.swift rename to GRDB/Record/PersistableRecord.swift index 107b1caa2..f3bcdfd6d 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -12,12 +12,12 @@ extension Database.ConflictResolution { // MARK: - PersistenceError -/// An error thrown by a type that adopts EncodableRecord. +/// An error thrown by a type that adopts PersistableRecord. public enum PersistenceError: Error, CustomStringConvertible { - /// Thrown by MutableEncodableRecord.update() when no matching row could be + /// Thrown by MutablePersistableRecord.update() when no matching row could be /// found in the database. - case recordNotFound(MutableEncodableRecord) + case recordNotFound(MutablePersistableRecord) } // CustomStringConvertible @@ -36,7 +36,7 @@ extension PersistenceError { /// Use persistence containers in the `encode(to:)` method of your /// encodable records: /// -/// struct Player : MutableEncodableRecord { +/// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -81,7 +81,7 @@ public struct PersistenceContainer { /// // Meh /// var container = PersistenceContainer() /// record.encode(to: container) - init(_ record: MutableEncodableRecord) { + init(_ record: MutablePersistableRecord) { storage = [:] record.encode(to: &self) } @@ -137,7 +137,7 @@ public struct PersistenceContainer { } extension Row { - convenience init(_ record: MutableEncodableRecord) { + convenience init(_ record: MutablePersistableRecord) { self.init(PersistenceContainer(record)) } @@ -146,12 +146,12 @@ extension Row { } } -// MARK: - MutableEncodableRecord +// MARK: - MutablePersistableRecord -/// The MutableEncodableRecord protocol uses this type in order to handle SQLite +/// The MutablePersistableRecord protocol uses this type in order to handle SQLite /// conflicts when records are inserted or updated. /// -/// See `MutableEncodableRecord.persistenceConflictPolicy`. +/// See `MutablePersistableRecord.persistenceConflictPolicy`. /// /// See https://www.sqlite.org/lang_conflict.html public struct PersistenceConflictPolicy { @@ -168,8 +168,8 @@ public struct PersistenceConflictPolicy { } } -/// Types that adopt MutableEncodableRecord can be inserted, updated, and deleted. -public protocol MutableEncodableRecord : TableRecord { +/// Types that adopt MutablePersistableRecord can be inserted, updated, and deleted. +public protocol MutablePersistableRecord : TableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -191,7 +191,7 @@ public protocol MutableEncodableRecord : TableRecord { /// /// Primary key columns, if any, must be included. /// - /// struct Player : MutableEncodableRecord { + /// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -214,7 +214,7 @@ public protocol MutableEncodableRecord : TableRecord { /// /// This method is optional: the default implementation does nothing. /// - /// struct Player : MutableEncodableRecord { + /// struct Player : MutablePersistableRecord { /// var id: Int64? /// var name: String? /// @@ -313,14 +313,14 @@ public protocol MutableEncodableRecord : TableRecord { func exists(_ db: Database) throws -> Bool } -extension MutableEncodableRecord { +extension MutablePersistableRecord { /// A dictionary whose keys are the columns encoded in the `encode(to:)` method. public var databaseDictionary: [String: DatabaseValue] { return PersistenceContainer(self).storage.mapValues { $0?.databaseValue ?? .null } } } -extension MutableEncodableRecord { +extension MutablePersistableRecord { /// Describes the conflict policy for insertions and updates. /// /// The default value specifies ABORT policy for both insertions and @@ -403,7 +403,7 @@ extension MutableEncodableRecord { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database and record could not be updated. @discardableResult - public func updateChanges(_ db: Database, from record: MutableEncodableRecord) throws -> Bool { + public func updateChanges(_ db: Database, from record: MutablePersistableRecord) throws -> Bool { let changedColumns = Set(databaseChanges(from: record).keys) if changedColumns.isEmpty { return false @@ -453,11 +453,11 @@ extension MutableEncodableRecord { /// but also in terms of columns. When the two records don't define the /// same set of columns in their `encode(to:)` method, only the columns /// defined by the receiver record are considered. - public func databaseChanges(from record: MutableEncodableRecord) -> [String: DatabaseValue] { + public func databaseChanges(from record: MutablePersistableRecord) -> [String: DatabaseValue] { return Dictionary(uniqueKeysWithValues: databaseChangesIterator(from: record)) } - fileprivate func databaseChangesIterator(from record: MutableEncodableRecord) -> AnyIterator<(String, DatabaseValue)> { + fileprivate func databaseChangesIterator(from record: MutablePersistableRecord) -> AnyIterator<(String, DatabaseValue)> { let oldContainer = PersistenceContainer(record) var newValueIterator = PersistenceContainer(self).makeIterator() return AnyIterator { @@ -490,10 +490,10 @@ extension MutableEncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutableEncodableRecord. + /// that adopt MutablePersistableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt MutableEncodableRecord can invoke performInsert() in their + /// that adopt MutablePersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public mutating func performInsert(_ db: Database) throws { @@ -507,10 +507,10 @@ extension MutableEncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutableEncodableRecord. + /// that adopt MutablePersistableRecord. /// /// performUpdate() provides the default implementation for update(). Types - /// that adopt MutableEncodableRecord can invoke performUpdate() in their + /// that adopt MutablePersistableRecord can invoke performUpdate() in their /// implementation of update(). They should not provide their own /// implementation of performUpdate(). /// @@ -531,10 +531,10 @@ extension MutableEncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutableEncodableRecord. + /// that adopt MutablePersistableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt MutableEncodableRecord can invoke performSave() in their + /// that adopt MutablePersistableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -560,10 +560,10 @@ extension MutableEncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutableEncodableRecord. + /// that adopt MutablePersistableRecord. /// /// performDelete() provides the default implementation for deelte(). Types - /// that adopt MutableEncodableRecord can invoke performDelete() in + /// that adopt MutablePersistableRecord can invoke performDelete() in /// their implementation of delete(). They should not provide their own /// implementation of performDelete(). public func performDelete(_ db: Database) throws -> Bool { @@ -576,10 +576,10 @@ extension MutableEncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt MutableEncodableRecord. + /// that adopt MutablePersistableRecord. /// /// performExists() provides the default implementation for exists(). Types - /// that adopt MutableEncodableRecord can invoke performExists() in + /// that adopt MutablePersistableRecord can invoke performExists() in /// their implementation of exists(). They should not provide their own /// implementation of performExists(). public func performExists(_ db: Database) throws -> Bool { @@ -592,7 +592,7 @@ extension MutableEncodableRecord { } -extension MutableEncodableRecord { +extension MutablePersistableRecord { // MARK: - Deleting All @@ -607,7 +607,7 @@ extension MutableEncodableRecord { } } -extension MutableEncodableRecord { +extension MutablePersistableRecord { // MARK: - Deleting by Single-Column Primary Key @@ -669,7 +669,7 @@ extension MutableEncodableRecord { } } -extension MutableEncodableRecord { +extension MutablePersistableRecord { // MARK: - Deleting by Key @@ -706,15 +706,15 @@ extension MutableEncodableRecord { } } -// MARK: - EncodableRecord +// MARK: - PersistableRecord -/// Types that adopt EncodableRecord can be inserted, updated, and deleted. +/// Types that adopt PersistableRecord can be inserted, updated, and deleted. /// /// This protocol is intented for types that don't have an INTEGER PRIMARY KEY. /// -/// Unlike MutableEncodableRecord, the insert() and save() methods are not +/// Unlike MutablePersistableRecord, the insert() and save() methods are not /// mutating methods. -public protocol EncodableRecord : MutableEncodableRecord { +public protocol PersistableRecord : MutablePersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -725,7 +725,7 @@ public protocol EncodableRecord : MutableEncodableRecord { /// This method is optional: the default implementation does nothing. /// /// If you need a mutating variant of this method, adopt the - /// MutableEncodableRecord protocol instead. + /// MutablePersistableRecord protocol instead. /// /// - parameters: /// - rowID: The inserted rowID. @@ -772,7 +772,7 @@ public protocol EncodableRecord : MutableEncodableRecord { func save(_ db: Database) throws } -extension EncodableRecord { +extension PersistableRecord { /// Notifies the record that it was succesfully inserted. /// @@ -801,10 +801,10 @@ extension EncodableRecord { // MARK: - Immutable CRUD Internals /// Don't invoke this method directly: it is an internal method for types - /// that adopt EncodableRecord. + /// that adopt PersistableRecord. /// /// performInsert() provides the default implementation for insert(). Types - /// that adopt EncodableRecord can invoke performInsert() in their + /// that adopt PersistableRecord can invoke performInsert() in their /// implementation of insert(). They should not provide their own /// implementation of performInsert(). public func performInsert(_ db: Database) throws { @@ -818,10 +818,10 @@ extension EncodableRecord { } /// Don't invoke this method directly: it is an internal method for types - /// that adopt EncodableRecord. + /// that adopt PersistableRecord. /// /// performSave() provides the default implementation for save(). Types - /// that adopt EncodableRecord can invoke performSave() in their + /// that adopt PersistableRecord can invoke performSave() in their /// implementation of save(). They should not provide their own /// implementation of performSave(). /// @@ -849,14 +849,14 @@ extension EncodableRecord { // MARK: - DAO -/// DAO takes care of EncodableRecord CRUD +/// DAO takes care of PersistableRecord CRUD final class DAO { /// The database let db: Database /// The record - let record: MutableEncodableRecord + let record: MutablePersistableRecord /// DAO keeps a copy the record's persistenceContainer, so that this /// dictionary is built once whatever the database operation. It is @@ -869,7 +869,7 @@ final class DAO { /// The table primary key let primaryKey: PrimaryKeyInfo - init(_ db: Database, _ record: MutableEncodableRecord) throws { + init(_ db: Database, _ record: MutablePersistableRecord) throws { let databaseTableName = type(of: record).databaseTableName let primaryKey = try db.primaryKey(databaseTableName) let persistenceContainer = PersistenceContainer(record) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 907b9eb49..a526703f3 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,7 +2,7 @@ /// Record is a class that wraps a table row, or the result of any query. It is /// designed to be subclassed. -open class Record : DecodableRecord, TableRecord, EncodableRecord { +open class Record : FetchableRecord, TableRecord, PersistableRecord { // MARK: - Initializers @@ -155,7 +155,7 @@ open class Record : DecodableRecord, TableRecord, EncodableRecord { row = Row(self) #else // workaround weird Swift 3.0 glitch - row = Row(self as! MutableEncodableRecord) + row = Row(self as! MutablePersistableRecord) #endif let copy = type(of: self).init(row: row) copy.referenceRow = referenceRow diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift index 2c4e356e8..523c00544 100644 --- a/GRDB/Record/RecordBox.swift +++ b/GRDB/Record/RecordBox.swift @@ -2,7 +2,7 @@ /// changes tracking provided by the Record class. /// /// // A Regular record struct -/// struct Player: DecodableRecord, MutableEncodableRecord, Codable { +/// struct Player: FetchableRecord, MutablePersistableRecord, Codable { /// static let databaseTableName = "players" /// var id: Int64? /// var name: String @@ -21,8 +21,8 @@ /// playerRecord.hasPersistentChangedValues // true /// playerRecord.persistentChangedValues["score"] // 100 (the old value) /// } -@available(*, deprecated, message: "Prefer changes methods defined on the MutableEncodableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") -public final class RecordBox: Record { +@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") +public final class RecordBox: Record { /// The boxed record public var value: T @@ -32,7 +32,7 @@ public final class RecordBox: Recor super.init() } - // MARK: - DecodableRecord + // MARK: - FetchableRecord /// Initializes a record from `row`. public required init(row: Row) { @@ -52,7 +52,7 @@ public final class RecordBox: Recor return T.databaseSelection } - // MARK: - MutableEncodableRecord + // MARK: - MutablePersistableRecord /// :nodoc: override public class var persistenceConflictPolicy: PersistenceConflictPolicy { diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 4ea8692bf..c45dd7f5e 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -1,7 +1,7 @@ /// Types that adopt TableRecord declare a particular relationship with /// a database table. /// -/// Types that adopt both TableRecord and DecodableRecord are granted with +/// Types that adopt both TableRecord and FetchableRecord are granted with /// built-in methods that allow to fetch instances identified by key: /// /// try Player.fetchOne(db, key: 123) // Player? diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index ad6fa6daa..bd66efde7 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -37,7 +37,7 @@ 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 560FC53F1CB003810014AA8E /* Row.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238761B9C75030082EB20 /* Row.swift */; }; 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 560FC5411CB003810014AA8E /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; @@ -59,11 +59,11 @@ 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 560FC57C1CB00B880014AA8E /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 560FC57E1CB00B880014AA8E /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 560FC5811CB00B880014AA8E /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 560FC5821CB00B880014AA8E /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 560FC5841CB00B880014AA8E /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 560FC58B1CB00B880014AA8E /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -72,7 +72,7 @@ 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 560FC5921CB00B880014AA8E /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; @@ -260,10 +260,10 @@ 566A843120413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843220413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843320413DD000E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84462041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; - 566A84472041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; - 566A84482041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; - 566A84492041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C71D531BEA002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -304,11 +304,11 @@ 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; }; 5671563A1CB16729007DC145 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 5671563C1CB16729007DC145 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; - 567156411CB16729007DC145 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 567156411CB16729007DC145 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; }; 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; }; 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -319,7 +319,7 @@ 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; }; - 567156511CB16729007DC145 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381A1B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift */; }; 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238161B9C74A90082EB20 /* DatabaseErrorTests.swift */; }; @@ -354,10 +354,10 @@ 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EE1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6F11F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6FE1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; - 5674A7011F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70D1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; @@ -368,14 +368,14 @@ 5674A7181F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71E1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7211F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7221F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7241F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; - 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; - 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; - 5674A72E1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567A80541D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; @@ -538,7 +538,7 @@ 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; }; 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1511C672E4000235C62 /* NSNumber.swift */; }; 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; }; - 56AFCA151CB1A8BB00F48B96 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; }; 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238751B9C75030082EB20 /* DatabaseValue.swift */; }; @@ -567,12 +567,12 @@ 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCA4B1CB1AA9900F48B96 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56AFCA4C1CB1AA9900F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCA521CB1AA9900F48B96 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCA551CB1AA9900F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -582,7 +582,7 @@ 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCA5E1CB1AA9900F48B96 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -627,12 +627,12 @@ 56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */; }; 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; }; - 56AFCAA41CB1ABC800F48B96 /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + 56AFCAA41CB1ABC800F48B96 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; }; - 56AFCAAB1CB1ABC800F48B96 /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; 56AFCAAC1CB1ABC800F48B96 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381C1B9C74A90082EB20 /* RawRepresentable+DatabaseValueConvertibleTests.swift */; }; 56AFCAAF1CB1ABC800F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; @@ -642,7 +642,7 @@ 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; - 56AFCAB71CB1ABC800F48B96 /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; }; 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; }; @@ -666,10 +666,10 @@ 56AFCACF1CB1ABC800F48B96 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1861C69111300235C62 /* DatabaseRegionTests.swift */; }; 56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; }; - 56B021CA1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; - 56B021CB1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; - 56B021CE1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; - 56B021CF1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CE1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CF1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; @@ -710,8 +710,8 @@ 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F21EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; - 56CEB4F51EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5021EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -736,8 +736,8 @@ 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D011EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; - 56D51D041EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D31DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D41DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; @@ -759,10 +759,10 @@ 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45411D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; - 56FF45421D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; - 56FF45451D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; - 56FF45461D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45411D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45421D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF45581D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; @@ -845,7 +845,7 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC54D1CB003810014AA8E /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; @@ -863,13 +863,13 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -895,7 +895,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -908,7 +908,7 @@ 5665F86A203EF47C0084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842720413D6E00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A842F20413DCF00E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; + 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -926,13 +926,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -1020,7 +1020,7 @@ 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCA7F1CB1AA9900F48B96 /* GRDBCipheriOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56AFCAD71CB1ABC800F48B96 /* GRDBCipheriOSEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipheriOSEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -1044,7 +1044,7 @@ 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -1056,7 +1056,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -1074,7 +1074,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -1203,17 +1203,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, - 566A84452041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, + 566A84452041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = EncodableRecord; + name = PersistableRecord; sourceTree = ""; }; 560FC54F1CB0047D0014AA8E /* GRDBCipher */ = { @@ -1313,7 +1313,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, @@ -1382,13 +1382,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = DecodableRecord; + name = FetchableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1528,10 +1528,10 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( - 5674A7251F30A8EF0095F066 /* DecodableRecord */, + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73EB203DA29B000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 5680521C2013296800E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1585,12 +1585,12 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 5680520A2013209300E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -1994,7 +1994,7 @@ 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F21EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2016,7 +2016,7 @@ 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6FA1F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2033,7 +2033,7 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, - 56D51D011EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, 5671FC211DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2060,7 +2060,7 @@ 560FC5391CB003810014AA8E /* DatabaseReader.swift in Sources */, 560FC53A1CB003810014AA8E /* NSNull.swift in Sources */, 56CEB51A1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A7011F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A7011F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC791DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 560FC53B1CB003810014AA8E /* Database.swift in Sources */, 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2071,7 +2071,7 @@ 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, 5680520C2013209300E87861 /* RecordBox.swift in Sources */, - 560FC5411CB003810014AA8E /* EncodableRecord.swift in Sources */, + 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, @@ -2087,7 +2087,7 @@ files = ( 560FC5611CB00B880014AA8E /* DatabaseValueConversionTests.swift in Sources */, 560FC5B31CB031EA0014AA8E /* DataMemoryTests.swift in Sources */, - 56FF45411D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56FF45411D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 560FC5621CB00B880014AA8E /* Record+QueryInterfaceRequestTests.swift in Sources */, 5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */, 56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, @@ -2116,7 +2116,7 @@ 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, 5674A7191F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021CA1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, 560FC5761CB00B880014AA8E /* RowCopiedFromStatementTests.swift in Sources */, @@ -2145,9 +2145,9 @@ 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 560FC57E1CB00B880014AA8E /* MutableEncodableRecordTests.swift in Sources */, + 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, - 560FC57F1CB00B880014AA8E /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, @@ -2160,10 +2160,10 @@ 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, - 560FC5841CB00B880014AA8E /* EncodableRecordTests.swift in Sources */, + 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, - 5674A72C1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2180,7 +2180,7 @@ 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393311DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, - 560FC5921CB00B880014AA8E /* DecodableRecordTests.swift in Sources */, + 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5657AB371D108BA9006283EF /* FoundationDataTests.swift in Sources */, 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */, @@ -2200,7 +2200,7 @@ 5657AB671D108BA9006283EF /* FoundationURLTests.swift in Sources */, 560FC59D1CB00B880014AA8E /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 562205F51E420E48005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84462041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84462041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393581DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 560FC59E1CB00B880014AA8E /* FoundationNSDateTests.swift in Sources */, 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2209,7 +2209,7 @@ 5698ACCF1DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 560FC5A21CB00B880014AA8E /* DatabaseFunctionTests.swift in Sources */, 560FC5A41CB00B880014AA8E /* RecordWithColumnNameManglingTests.swift in Sources */, - 5674A7221F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A7221F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 5690C3271D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 560FC5A51CB00B880014AA8E /* CGFloatTests.swift in Sources */, 56FF45571D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2234,7 +2234,7 @@ files = ( 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */, 5671561E1CB16729007DC145 /* DataMemoryTests.swift in Sources */, - 56FF45421D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56FF45421D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 5671561F1CB16729007DC145 /* Record+QueryInterfaceRequestTests.swift in Sources */, 5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2261,7 +2261,7 @@ 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, - 56B021CB1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5674A71B1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, @@ -2291,8 +2291,8 @@ 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 5671563C1CB16729007DC145 /* MutableEncodableRecordTests.swift in Sources */, - 5671563D1CB16729007DC145 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */, + 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, 5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, @@ -2300,7 +2300,7 @@ 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, - 567156411CB16729007DC145 /* EncodableRecordTests.swift in Sources */, + 567156411CB16729007DC145 /* PersistableRecordTests.swift in Sources */, 5665F86D203EF47D0084C6C0 /* ColumnInfoTests.swift in Sources */, 5657AB501D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 567156441CB16729007DC145 /* RecordSubClassTests.swift in Sources */, @@ -2310,7 +2310,7 @@ 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, - 5674A72E1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2323,7 +2323,7 @@ 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, - 567156511CB16729007DC145 /* DecodableRecordTests.swift in Sources */, + 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -2347,7 +2347,7 @@ 5671565A1CB16729007DC145 /* StatementArguments+FoundationTests.swift in Sources */, 5657AB581D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 562205F81E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, - 566A84472041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84472041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 562393591DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5671565B1CB16729007DC145 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2356,7 +2356,7 @@ 5671565E1CB16729007DC145 /* QueryInterfaceRequestTests.swift in Sources */, 5698ACD01DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 569178481CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, - 5674A7241F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A7241F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 5634B1091CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 567156601CB16729007DC145 /* DatabaseFunctionTests.swift in Sources */, 567156611CB16729007DC145 /* RecordWithColumnNameManglingTests.swift in Sources */, @@ -2388,7 +2388,7 @@ 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F51EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -2410,7 +2410,7 @@ 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, - 5674A6F71F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, @@ -2427,7 +2427,7 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, - 56D51D041EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, 5671FC241DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, @@ -2454,7 +2454,7 @@ 56AFCA0F1CB1A8BB00F48B96 /* NSNull.swift in Sources */, 56AFCA101CB1A8BB00F48B96 /* DatabaseQueue.swift in Sources */, 56CEB51D1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FE1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A6FE1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, 5698AC7C1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56AFCA111CB1A8BB00F48B96 /* DatabaseError.swift in Sources */, 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2462,7 +2462,7 @@ 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, - 56AFCA151CB1A8BB00F48B96 /* EncodableRecord.swift in Sources */, + 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, 5680520D2013209900E87861 /* RecordBox.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, @@ -2481,7 +2481,7 @@ files = ( 56AFCA301CB1AA9900F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 562393771DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CE1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CE1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */, 56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2525,10 +2525,10 @@ 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, 566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCA4B1CB1AA9900F48B96 /* MutableEncodableRecordTests.swift in Sources */, + 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableRecordTests.swift in Sources */, 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, - 56AFCA4C1CB1AA9900F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 56AFCA4C1CB1AA9900F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */, @@ -2540,8 +2540,8 @@ 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, - 56FF45451D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, - 56AFCA521CB1AA9900F48B96 /* EncodableRecordTests.swift in Sources */, + 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, @@ -2558,7 +2558,7 @@ 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, - 5674A72B1F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56AF74701D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74E1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2570,7 +2570,7 @@ 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, - 56AFCA5E1CB1AA9900F48B96 /* DecodableRecordTests.swift in Sources */, + 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2594,7 +2594,7 @@ 565EFAF31D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 56AFCA671CB1AA9900F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCA681CB1AA9900F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84482041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84482041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E841D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCA6B1CB1AA9900F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2603,7 +2603,7 @@ 5657AB5B1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA6D1CB1AA9900F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCA6E1CB1AA9900F48B96 /* FoundationNSDateTests.swift in Sources */, - 5674A7211F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A7211F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56AFCA6F1CB1AA9900F48B96 /* DatabaseTests.swift in Sources */, 56AFCA701CB1AA9900F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5634B10B1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, @@ -2628,7 +2628,7 @@ files = ( 56C3F7581CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393781DEE104400A6B01F /* MapCursorTests.swift in Sources */, - 56B021CF1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CF1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 56AFCA891CB1ABC800F48B96 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -2680,17 +2680,17 @@ 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */, 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, - 56AFCAA41CB1ABC800F48B96 /* MutableEncodableRecordTests.swift in Sources */, + 56AFCAA41CB1ABC800F48B96 /* MutablePersistableRecordTests.swift in Sources */, 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, - 56AFCAA51CB1ABC800F48B96 /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */, 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, - 56AFCAAB1CB1ABC800F48B96 /* EncodableRecordTests.swift in Sources */, - 56FF45461D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */, + 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, @@ -2705,7 +2705,7 @@ 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - 5674A7281F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56AFCAAE1CB1ABC800F48B96 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, 56FEE8011F47253700D930EA /* TableRecordTests.swift in Sources */, 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, @@ -2721,7 +2721,7 @@ 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, 56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */, - 56AFCAB71CB1ABC800F48B96 /* DecodableRecordTests.swift in Sources */, + 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5623931E1DECC02000A6B01F /* RowFetchTests.swift in Sources */, @@ -2741,7 +2741,7 @@ 56AFCABF1CB1ABC800F48B96 /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 56AFCAC01CB1ABC800F48B96 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56AFCAC11CB1ABC800F48B96 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, - 566A84492041AB3900E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84492041AB3900E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 56AFCAC41CB1ABC800F48B96 /* DatabaseTimestampTests.swift in Sources */, 568068371EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, @@ -2750,7 +2750,7 @@ 56AFCAC61CB1ABC800F48B96 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAC71CB1ABC800F48B96 /* FoundationNSDateTests.swift in Sources */, 56AFCAC81CB1ABC800F48B96 /* DatabaseTests.swift in Sources */, - 5674A71E1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A71E1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56AFCAC91CB1ABC800F48B96 /* QueryInterfaceRequestTests.swift in Sources */, 5691784B1CED9B6000E179EA /* DatabaseQueueTests.swift in Sources */, 56AFCACB1CB1ABC800F48B96 /* DatabaseFunctionTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 9c9e85f4f..15f7843c5 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -93,8 +93,8 @@ 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */; }; 566A843520413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; 566A843620413DE400E50BFD /* DatabaseSnapshotTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */; }; - 566A84432041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */; }; - 566A84442041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */; }; + 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */; }; + 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */; }; 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; }; 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */; }; @@ -117,20 +117,20 @@ 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */; }; 5674A6EC1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; 5674A6ED1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */; }; - 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */; }; - 5674A6FC1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; - 5674A6FD1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */; }; + 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */; }; + 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; + 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; }; 5674A7041F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A7051F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */; }; 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */; }; 5674A7141F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */; }; - 5674A71D1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A71F1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */; }; - 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; - 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */; }; + 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; + 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; + 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -205,8 +205,8 @@ 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; }; 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; }; - 56B021CC1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; - 56B021D01D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; + 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; @@ -238,8 +238,8 @@ 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; }; 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; 56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; - 56CEB4F31EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; - 56CEB4F61EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */; }; + 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; + 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */; }; 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; 56CEB5031EAA2F4D00BFAF62 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; }; @@ -262,8 +262,8 @@ 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */; }; 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */; }; - 56D51D021EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; - 56D51D051EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */; }; + 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; + 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */; }; 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2D91DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; }; 56DAA2DD1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; @@ -280,8 +280,8 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; - 56FF45431D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; - 56FF45471D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */; }; + 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; + 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; }; 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; @@ -317,7 +317,7 @@ F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA80311CFB289F003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA80331CFB28A4003DC1BA /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80341CFB28A4003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80381CFB2932003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -361,7 +361,7 @@ F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; F3BA808D1CFB2E75003DC1BA /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */; }; - F3BA808F1CFB2E7A003DC1BA /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* EncodableRecord.swift */; }; + F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; }; F3BA80901CFB2E7A003DC1BA /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; F3BA80931CFB2F13003DC1BA /* GRDBCustomSQLite.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDBCustomSQLite.h */; settings = {ATTRIBUTES = (Public, ); }; }; @@ -399,10 +399,10 @@ F3BA80CE1CFB2FDE003DC1BA /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; - F3BA80D11CFB2FF3003DC1BA /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - F3BA80D21CFB2FF3003DC1BA /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; - F3BA80D31CFB2FF4003DC1BA /* MutableEncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */; }; - F3BA80D41CFB2FF4003DC1BA /* EncodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */; }; + F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; + F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */; }; + F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; }; F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238181B9C74A90082EB20 /* DatabaseValueTests.swift */; }; @@ -423,12 +423,12 @@ F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80EB1CFB3016003DC1BA /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381F1B9C74A90082EB20 /* RowCopiedFromStatementTests.swift */; }; F3BA80ED1CFB3017003DC1BA /* RowFromDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381E1B9C74A90082EB20 /* RowFromDictionaryTests.swift */; }; F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; }; - F3BA80F01CFB3017003DC1BA /* DecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */; }; + F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */; }; F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EE573C1BB317B7007A6A95 /* StatementColumnConvertibleTests.swift */; }; @@ -457,12 +457,12 @@ F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238241B9C74A90082EB20 /* DatabaseMigratorTests.swift */; }; F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + F3BA81161CFB305E003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */; }; F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; }; - F3BA811B1CFB305F003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */; }; + F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; }; F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; }; F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; }; @@ -549,7 +549,7 @@ 560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = ""; }; 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = ""; }; 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = ""; }; - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = ""; }; + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; @@ -564,13 +564,13 @@ 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = ""; }; 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = ""; }; 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequestTests.swift; sourceTree = ""; }; - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExpressionsTests.swift; sourceTree = ""; }; 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "TableRecord+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceRequest.swift; sourceTree = ""; }; 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = ""; }; - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordTests.swift; sourceTree = ""; }; - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecordTests.swift; sourceTree = ""; }; + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = ""; }; + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecordTests.swift; sourceTree = ""; }; 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueConcurrencyTests.swift; sourceTree = ""; }; 563363BF1C942C04000BE133 /* DatabaseReader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReader.swift; sourceTree = ""; }; 563363C31C942C37000BE133 /* DatabaseWriter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriter.swift; sourceTree = ""; }; @@ -596,7 +596,7 @@ 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 5659F49F1EA8D997004A4992 /* Result.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecordTests.swift; sourceTree = ""; }; + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; 565D5D731BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "StatementArguments+FoundationTests.swift"; sourceTree = ""; }; 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = ""; }; @@ -609,7 +609,7 @@ 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnInfoTests.swift; sourceTree = ""; }; 566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshot.swift; sourceTree = ""; }; 566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotTests.swift; sourceTree = ""; }; - 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordChangesTests.swift; sourceTree = ""; }; + 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordChangesTests.swift; sourceTree = ""; }; 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinition.swift; sourceTree = ""; }; 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableDefinitionTests.swift; sourceTree = ""; }; 566B91081FA4C3960012D5B0 /* Database+Statements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Statements.swift"; sourceTree = ""; }; @@ -626,13 +626,13 @@ 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Encodable.swift"; sourceTree = ""; }; 5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+Decodable.swift"; sourceTree = ""; }; - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+Decodable.swift"; sourceTree = ""; }; - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "EncodableRecord+Encodable.swift"; sourceTree = ""; }; + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+Decodable.swift"; sourceTree = ""; }; + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Encodable.swift"; sourceTree = ""; }; 5674A7021F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DatabaseValueConvertible+ReferenceConvertible.swift"; sourceTree = ""; }; 5674A70A1F3087700095F066 /* DatabaseValueConvertibleDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleDecodableTests.swift; sourceTree = ""; }; 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordEncodableTests.swift; sourceTree = ""; }; - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DecodableRecordDecodableTests.swift; sourceTree = ""; }; + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; @@ -712,7 +712,7 @@ 56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = ""; }; 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = ""; }; 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = ""; }; - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; @@ -736,7 +736,7 @@ 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; 56CC9253201E094600CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DecodableRecord.swift; sourceTree = ""; }; + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecord.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS3+QueryInterfaceRequest.swift"; sourceTree = ""; }; @@ -748,7 +748,7 @@ 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLSelectable.swift; sourceTree = ""; }; 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.109.0.swift"; sourceTree = ""; }; 56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = ""; }; - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DecodableRecord+TableRecord.swift"; sourceTree = ""; }; + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = ""; }; 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = ""; }; 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = ""; }; 56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = ""; }; @@ -766,7 +766,7 @@ 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutableEncodableRecordDeleteTests.swift; sourceTree = ""; }; + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; @@ -892,17 +892,17 @@ name = DatabasePool; sourceTree = ""; }; - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */ = { + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = { isa = PBXGroup; children = ( - 563363AA1C933FF8000BE133 /* EncodableRecordTests.swift */, - 566A84422041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift */, - 56FF453F1D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift */, - 5674A71C1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift */, - 56B021C81D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift */, - 563363A91C933FF8000BE133 /* MutableEncodableRecordTests.swift */, + 566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */, + 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */, + 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */, + 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, + 563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */, + 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */, ); - name = EncodableRecord; + name = PersistableRecord; sourceTree = ""; }; 5614DEEE1BA9D6F9003163B3 /* Frameworks */ = { @@ -987,7 +987,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( - 56300B601C53C42C005A543B /* DecodableRecord+QueryInterfaceRequestTests.swift */, + 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, @@ -1056,13 +1056,13 @@ path = Support; sourceTree = ""; }; - 5674A7251F30A8EF0095F066 /* DecodableRecord */ = { + 5674A7251F30A8EF0095F066 /* FetchableRecord */ = { isa = PBXGroup; children = ( - 5674A7261F30A9090095F066 /* DecodableRecordDecodableTests.swift */, - 565B0FEE1BBC7D980098DE03 /* DecodableRecordTests.swift */, + 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */, + 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */, ); - name = DecodableRecord; + name = FetchableRecord; sourceTree = ""; }; 5698AC291D9E5A480056AF8C /* FTS */ = { @@ -1202,10 +1202,10 @@ 56A238251B9C74A90082EB20 /* Record */ = { isa = PBXGroup; children = ( - 5674A7251F30A8EF0095F066 /* DecodableRecord */, + 5674A7251F30A8EF0095F066 /* FetchableRecord */, 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */, 564E73E7203DA278000C443C /* JoinSupportTests.swift */, - 560B3FA41C19DFF800C58EC7 /* EncodableRecord */, + 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, 568052182013295100E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, @@ -1259,12 +1259,12 @@ 56A2389F1B9C753B0082EB20 /* Record */ = { isa = PBXGroup; children = ( - 56CEB4F01EAA2EFA00BFAF62 /* DecodableRecord.swift */, - 5674A6F21F307F600095F066 /* DecodableRecord+Decodable.swift */, - 56D51CFF1EA789FA0074638A /* DecodableRecord+TableRecord.swift */, - 560D92441C672C4B00F4F92B /* EncodableRecord.swift */, - 5674A6F31F307F600095F066 /* EncodableRecord+Encodable.swift */, + 56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */, + 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */, + 56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */, 31A7787C1C6A4DD600F507F6 /* FetchedRecordsController.swift */, + 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, + 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, 568052072013206F00E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, @@ -1697,7 +1697,7 @@ 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F61EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -1719,7 +1719,7 @@ 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F61F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -1737,7 +1737,7 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D051EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, 566475BF1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -1758,12 +1758,12 @@ 56FC987D1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA80111CFB2876003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80281CFB2891003DC1BA /* StandardLibrary.swift in Sources */, - F3BA80331CFB28A4003DC1BA /* EncodableRecord.swift in Sources */, + F3BA80331CFB28A4003DC1BA /* PersistableRecord.swift in Sources */, 56BF6D3B1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BE1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA80211CFB288C003DC1BA /* NSNull.swift in Sources */, 56CEB51E1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FD1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A6FD1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7D1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -1790,7 +1790,7 @@ files = ( F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */, F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */, - 56FF45471D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, + 56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, @@ -1802,7 +1802,7 @@ 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */, 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */, - F3BA81161CFB305E003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + F3BA81161CFB305E003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80F41CFB301D003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA81181CFB305E003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */, @@ -1818,18 +1818,18 @@ F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, - 56B021D01D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, 5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, - F3BA80D11CFB2FF3003DC1BA /* MutableEncodableRecordTests.swift in Sources */, + F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */, 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, - F3BA80D21CFB2FF3003DC1BA /* EncodableRecordTests.swift in Sources */, + F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, 5698AC501DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, @@ -1849,7 +1849,7 @@ 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, - F3BA80EB1CFB3016003DC1BA /* DecodableRecordTests.swift in Sources */, + F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */, F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, @@ -1867,7 +1867,7 @@ 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, - 5674A7291F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, @@ -1903,7 +1903,7 @@ F3BA81231CFB3063003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, F3BA80541CFB2B59003DC1BA /* DatabaseRegionTests.swift in Sources */, 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, - 566A84442041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84442041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, F3BA81171CFB305E003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, F3BA810B1CFB3056003DC1BA /* Row+FoundationTests.swift in Sources */, 5698AC901DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, @@ -1912,7 +1912,7 @@ 56741EAF1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5657AB5D1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, F3BA81241CFB3063003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, - 5674A71F1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A71F1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, F3BA80E81CFB3016003DC1BA /* RowFromDictionaryTests.swift in Sources */, 562393671DEE06D300A6B01F /* CursorTests.swift in Sources */, F3BA80B41CFB2FC9003DC1BA /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -1944,7 +1944,7 @@ 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, - 56CEB4F31EAA2EFA00BFAF62 /* DecodableRecord.swift in Sources */, + 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, @@ -1966,7 +1966,7 @@ 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, - 5674A6F51F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */, + 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, @@ -1984,7 +1984,7 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, - 56D51D021EA789FA0074638A /* DecodableRecord+TableRecord.swift in Sources */, + 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, 566475BC1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, @@ -2005,12 +2005,12 @@ 56FC987A1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, - F3BA808F1CFB2E7A003DC1BA /* EncodableRecord.swift in Sources */, + F3BA808F1CFB2E7A003DC1BA /* PersistableRecord.swift in Sources */, 56BF6D381DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B964BB1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, F3BA807D1CFB2E61003DC1BA /* NSNull.swift in Sources */, 56CEB51B1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, - 5674A6FC1F307F600095F066 /* DecodableRecord+Decodable.swift in Sources */, + 5674A6FC1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */, 5698AC7A1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2050,7 +2050,7 @@ 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */, 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, - 56B021CC1D8C0D3900B239BB /* MutableEncodableRecordPersistenceConflictPolicyTests.swift in Sources */, + 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, F3BA80E31CFB300F003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2071,11 +2071,11 @@ 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, - F3BA80D31CFB2FF4003DC1BA /* MutableEncodableRecordTests.swift in Sources */, + F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */, 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */, F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, - F3BA80D41CFB2FF4003DC1BA /* EncodableRecordTests.swift in Sources */, + F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, F3BA80FF1CFB3025003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, 5698AC4C1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, @@ -2106,15 +2106,15 @@ 5698AC8C1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */, F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, - 56FF45431D2C23BA00F21EF9 /* MutableEncodableRecordDeleteTests.swift in Sources */, - F3BA80F01CFB3017003DC1BA /* DecodableRecordTests.swift in Sources */, + 56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, - 5674A7271F30A9090095F066 /* DecodableRecordDecodableTests.swift in Sources */, + 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */, F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */, @@ -2150,7 +2150,7 @@ 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, F3BA812E1CFB3064003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, F3BA81021CFB3032003DC1BA /* CGFloatTests.swift in Sources */, - 566A84432041AB2D00E50BFD /* MutableEncodableRecordChangesTests.swift in Sources */, + 566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */, 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, F3BA81131CFB305B003DC1BA /* DatabaseMigratorTests.swift in Sources */, F3BA81381CFB3064003DC1BA /* RecordSubClassTests.swift in Sources */, @@ -2159,11 +2159,11 @@ 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */, - 5674A71D1F30A8DF0095F066 /* MutableEncodableRecordEncodableTests.swift in Sources */, + 5674A71D1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 562393511DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, - F3BA811B1CFB305F003DC1BA /* DecodableRecord+QueryInterfaceRequestTests.swift in Sources */, + F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, diff --git a/Playgrounds/Issue156.playground/Contents.swift b/Playgrounds/Issue156.playground/Contents.swift index f01c64c18..60c89dbc7 100644 --- a/Playgrounds/Issue156.playground/Contents.swift +++ b/Playgrounds/Issue156.playground/Contents.swift @@ -76,7 +76,7 @@ class TestDeleteAll: NSObject { } -struct MyRecord: DecodableRecord, TableRecord, EncodableRecord { +struct MyRecord: FetchableRecord, TableRecord, PersistableRecord { static let MyColumn = Column("MyColumn") static var databaseTableName: String { return String(describing: self) } diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index 0c7ec316e..af215f9d5 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -64,8 +64,8 @@ struct PointOfInterest { var coordinate: CLLocationCoordinate2D } -// Adopt DecodableRecord -extension PointOfInterest : DecodableRecord { +// Adopt FetchableRecord +extension PointOfInterest : FetchableRecord { init(row: Row) { id = row["id"] title = row["title"] @@ -81,8 +81,8 @@ extension PointOfInterest : TableRecord { static let databaseTableName = "pointOfInterests" } -// Adopt MutableEncodableRecord -extension PointOfInterest : MutableEncodableRecord { +// Adopt MutablePersistableRecord +extension PointOfInterest : MutablePersistableRecord { func encode(to container: inout PersistenceContainer) { container["id"] = id container["title"] = title diff --git a/README.md b/README.md index b681a9b18..d056e7b3a 100644 --- a/README.md +++ b/README.md @@ -1857,9 +1857,9 @@ Your custom structs and classes can adopt each protocol individually, and opt in **Protocols and the Record class** - [Record Protocols Overview](#record-protocols-overview) -- [DecodableRecord Protocol](#decodablerecord-protocol) +- [FetchableRecord Protocol](#fetchablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) -- [EncodableRecord Protocol](#encodablerecord-protocol) +- [PersistableRecord Protocol](#persistablerecord-protocol) - [Persistence Methods](#persistence-methods) - [Customizing the Persistence Methods](#customizing-the-persistence-methods) - [Codable Records](#codable-records) @@ -1872,7 +1872,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in ### Inserting Records -To insert a record in the database, subclass the [Record](#record-class) class or adopt the [EncodableRecord] protocol, and call the `insert` method: +To insert a record in the database, subclass the [Record](#record-class) class or adopt the [PersistableRecord] protocol, and call the `insert` method: ```swift class Player : Record { ... } @@ -1884,7 +1884,7 @@ try player.insert(db) ### Fetching Records -[Record](#record-class) subclasses and types that adopt the [DecodableRecord] protocol can be fetched from the database: +[Record](#record-class) subclasses and types that adopt the [FetchableRecord] protocol can be fetched from the database: ```swift class Player : Record { ... } @@ -1906,7 +1906,7 @@ See [fetching methods](#fetching-methods), and the [query interface](#the-query- ### Updating Records -[Record](#record-class) subclasses and types that adopt the [EncodableRecord] protocol can be updated in the database: +[Record](#record-class) subclasses and types that adopt the [PersistableRecord] protocol can be updated in the database: ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1933,7 +1933,7 @@ try db.execute("UPDATE players SET synchronized = 1") ### Deleting Records -[Record](#record-class) subclasses and types that adopt the [EncodableRecord] protocol can be deleted from the database: +[Record](#record-class) subclasses and types that adopt the [PersistableRecord] protocol can be deleted from the database: ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1967,9 +1967,9 @@ let playerWithEmailCount = try Player.filter(emailColumn != nil).fetchCount(db) Details follow: - [Record Protocols Overview](#record-protocols-overview) -- [DecodableRecord Protocol](#decodablerecord-protocol) +- [FetchableRecord Protocol](#fetchablerecord-protocol) - [TableRecord Protocol](#tablerecord-protocol) -- [EncodableRecord Protocol](#encodablerecord-protocol) +- [PersistableRecord Protocol](#persistablerecord-protocol) - [Codable Records](#codable-records) - [Record Class](#record-class) - [Changes Tracking](#changes-tracking) @@ -1982,7 +1982,7 @@ Details follow: **GRDB ships with three record protocols**. Your own types will adopt one or several of them, according to the abilities you want to extend your types with. -- [DecodableRecord] is able to **read**: it grants the ability to efficiently decode raw database row. +- [FetchableRecord] is able to **read**: it grants the ability to efficiently decode raw database row. Imagine you want to load places from the `places` database table. @@ -2040,10 +2040,10 @@ Details follow: } ``` - That's better. And that's what DecodableRecord does, with a little performance bonus, and in a single line: + That's better. And that's what FetchableRecord does, with a little performance bonus, and in a single line: ```swift - struct Place : DecodableRecord { + struct Place : FetchableRecord { init(row: Row) { ... } } func fetchPlaces(_ db: Database) throws -> [Place] { @@ -2051,7 +2051,7 @@ Details follow: } ``` - DecodableRecord is not able to build SQL requests, though. For that, you also need TableRecord: + FetchableRecord is not able to build SQL requests, though. For that, you also need TableRecord: - [TableRecord] is able to **build requests without SQL**: @@ -2061,20 +2061,20 @@ Details follow: let request = Place.order(Column("title")) ``` - When a type adopts both TableRecord and DecodableRecord, it can load from those requests: + When a type adopts both TableRecord and FetchableRecord, it can load from those requests: ```swift - struct Place : TableRecord, DecodableRecord { ... } + struct Place : TableRecord, FetchableRecord { ... } try dbQueue.inDatabase { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) } ``` -- [EncodableRecord] is able to **write**: it can create, update, and delete rows in the database: +- [PersistableRecord] is able to **write**: it can create, update, and delete rows in the database: ```swift - struct Place : EncodableRecord { ... } + struct Place : PersistableRecord { ... } try dbQueue.inDatabase { db in try Place.delete(db, key: 1) try Place(...).insert(db) @@ -2082,18 +2082,18 @@ Details follow: ``` -## DecodableRecord Protocol +## FetchableRecord Protocol -**The DecodableRecord protocol grants fetching methods to any type** that can be built from a database row: +**The FetchableRecord protocol grants fetching methods to any type** that can be built from a database row: ```swift -protocol DecodableRecord { +protocol FetchableRecord { /// Row initializer init(row: Row) } ``` -**To use DecodableRecord**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: +**To use FetchableRecord**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: ```swift struct Place { @@ -2102,7 +2102,7 @@ struct Place { var coordinate: CLLocationCoordinate2D } -extension Place : DecodableRecord { +extension Place : FetchableRecord { init(row: Row) { id = row["id"] title = row["title"] @@ -2116,7 +2116,7 @@ extension Place : DecodableRecord { Rows also accept keys of type `Column`: ```swift -extension Place : DecodableRecord { +extension Place : FetchableRecord { enum Columns { static let id = Column("id") static let title = Column("title") @@ -2140,7 +2140,7 @@ See [column values](#column-values) for more information about the `row[]` subsc > > :bulb: **Tip**: the `init(row:)` initializer can be automatically generated when your type adopts the standard `Decodable` protocol. See [Codable Records](#codable-records) for more information. -DecodableRecord allows adopting types to be fetched from SQL queries: +FetchableRecord allows adopting types to be fetched from SQL queries: ```swift try Place.fetchCursor(db, "SELECT ...", arguments:...) // A Cursor of Place @@ -2153,7 +2153,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor ## TableRecord Protocol -**Adopt the TableRecord protocol** on top of [DecodableRecord], and you are granted with the full [query interface](#the-query-interface). +**Adopt the TableRecord protocol** on top of [FetchableRecord], and you are granted with the full [query interface](#the-query-interface). ```swift protocol TableRecord { @@ -2204,12 +2204,12 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci ``` -## EncodableRecord Protocol +## PersistableRecord Protocol **GRDB provides two protocols that let adopting types create, update, and delete rows in the database:** ```swift -protocol MutableEncodableRecord : TableRecord { +protocol MutablePersistableRecord : TableRecord { /// The name of the database table (from TableRecord) static var databaseTableName: String { get } @@ -2223,7 +2223,7 @@ protocol MutableEncodableRecord : TableRecord { ``` ```swift -protocol EncodableRecord : MutableEncodableRecord { +protocol PersistableRecord : MutablePersistableRecord { /// Non-mutating version of the optional didInsert(with:for:) func didInsert(with rowID: Int64, for column: String?) } @@ -2231,11 +2231,11 @@ protocol EncodableRecord : MutableEncodableRecord { Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other: -- *If your type is a struct that mutates on insertion*, choose `MutableEncodableRecord`. +- *If your type is a struct that mutates on insertion*, choose `MutablePersistableRecord`. For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion. -- Otherwise, stick with `EncodableRecord`. Particularly if your type is a class. +- Otherwise, stick with `PersistableRecord`. Particularly if your type is a class. The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns. @@ -2246,7 +2246,7 @@ The optional `didInsert` method lets the adopting type store its rowID after suc **To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitely. For example: ```swift -extension Place : MutableEncodableRecord { +extension Place : MutablePersistableRecord { /// The values persisted in the database func encode(to container: inout PersistenceContainer) { @@ -2274,7 +2274,7 @@ paris.id // some value Persistence containers also accept keys of type `Column`: ```swift -extension Place : MutableEncodableRecord { +extension Place : MutablePersistableRecord { enum Columns { static let id = Column("id") static let title = Column("title") @@ -2294,7 +2294,7 @@ extension Place : MutableEncodableRecord { ### Persistence Methods -[Record](#record-class) subclasses and types that adopt [EncodableRecord] are given default implementations for methods that insert, update, and delete: +[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given default implementations for methods that insert, update, and delete: ```swift // Instance methods @@ -2351,10 +2351,10 @@ class Player : Record { } ``` -If you use the raw [EncodableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: +If you use the raw [PersistableRecord] protocol, use one of the *special methods* `performInsert`, `performUpdate`, `performSave`, `performDelete`, or `performExists`: ```swift -struct Link : EncodableRecord { +struct Link : PersistableRecord { var url: URL func insert(_ db: Database) throws { @@ -2384,7 +2384,7 @@ struct Link : EncodableRecord { [Swift Archival & Serialization](https://github.com/apple/swift-evolution/blob/master/proposals/0166-swift-archival-serialization.md) was introduced with Swift 4. -GRDB provides default implementations for [`DecodableRecord.init(row:)`](#decodablerecord-protocol) and [`EncodableRecord.encode(to:)`](#encodablerecord-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: +GRDB provides default implementations for [`FetchableRecord.init(row:)`](#fetchablerecord-protocol) and [`PersistableRecord.encode(to:)`](#persistablerecord-protocol) for record types that also adopt an archival protocol (`Codable`, `Encodable` or `Decodable`). When all their properties are themselves codable, Swift generates the archiving methods, and you don't need to write them down: ```swift // Declare a plain Codable struct or class... @@ -2394,7 +2394,7 @@ struct Player: Codable { } // Adopt Record protocols... -extension Player: DecodableRecord, EncodableRecord { +extension Player: FetchableRecord, PersistableRecord { static let databaseTableName = "players" } @@ -2409,7 +2409,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: -struct Place: DecodableRecord, EncodableRecord, Codable { +struct Place: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "places" var title: String @@ -2441,14 +2441,14 @@ struct Place: Codable { } // Free database support! -extension Place: DecodableRecord, EncodableRecord { +extension Place: FetchableRecord, PersistableRecord { static let databaseTableName = "places" } ``` GRDB ships with support for nested codable records, but this is a more complex topic. See [Joined Queries Support](#joined-queries-support) for more information. -As documented with the [EncodableRecord] protocol, have your struct records use MutableEncodableRecord instead of EncodableRecord when they store their automatically incremented row id: +As documented with the [PersistableRecord] protocol, have your struct records use MutablePersistableRecord instead of PersistableRecord when they store their automatically incremented row id: ```swift struct Place: Codable { @@ -2459,7 +2459,7 @@ struct Place: Codable { var coordinate: CLLocationCoordinate2D { ... } } -extension Place: DecodableRecord, MutableEncodableRecord { +extension Place: FetchableRecord, MutablePersistableRecord { static let databaseTableName = "places" mutating func didInsert(with rowID: Int64, for column: String?) { @@ -2479,7 +2479,7 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [DecodableRecord, TableRecord, and EncodableRecord](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). Record subclasses define their custom database relationship by overriding database methods: @@ -2526,7 +2526,7 @@ class Place : Record { The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless. -You can use instead the `updateChanges` method, available on the [EncodableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): +You can use instead the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): ```swift let oldPlayer = try Player.fetchOne(db, ...) @@ -2539,7 +2539,7 @@ if try newPlayer.updateChanges(db, from: oldPlayer) { } ``` -> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a EncodableRecord protocol, you don't need to care about Equatable. +> :point_up: **Note**: The comparison is performed of the database representation of records. As long as your record type adopts a PersistableRecord protocol, you don't need to care about Equatable. The [Record](#record-class) class is able to compare against itself, and knows if it has changes that have not been saved since it was last fetched or persisted: @@ -2639,10 +2639,10 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` -When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutableEncodableRecord or EncodableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): +When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutablePersistableRecord or PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): ```swift -protocol MutableEncodableRecord { +protocol MutablePersistableRecord { /// The policy that handles SQLite conflicts when records are inserted /// or updated. /// @@ -2652,7 +2652,7 @@ protocol MutableEncodableRecord { static var persistenceConflictPolicy: PersistenceConflictPolicy { get } } -struct Player : MutableEncodableRecord { +struct Player : MutablePersistableRecord { static let persistenceConflictPolicy = PersistenceConflictPolicy( insert: .replace, update: .replace) @@ -2732,10 +2732,10 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu let events = try Event.fetchAll(db) ``` -2. Have `init(row:)` from the [DecodableRecord] protocol consume the "rowid" column: +2. Have `init(row:)` from the [FetchableRecord] protocol consume the "rowid" column: ```swift - struct Event : DecodableRecord { + struct Event : FetchableRecord { var id: Int64? init(row: Row) { @@ -2759,10 +2759,10 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu event.id // some value ``` -3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [EncodableRecord and MutableEncodableRecord](#encodablerecord-protocol) protocols): +3. Encode the rowid in `encode(to:)`, and keep it in the `didInsert(with:for:)` method (both from the [PersistableRecord and MutablePersistableRecord](#persistablerecord-protocol) protocols): ```swift - struct Event : MutableEncodableRecord { + struct Event : MutablePersistableRecord { var id: Int64? func encode(to container: inout PersistenceContainer) { @@ -2802,54 +2802,54 @@ This is the list of record methods, along with their required protocols. The [Re | Method | Protocols | Notes | | ------ | --------- | :---: | | **Core Methods** | | | -| `init(row:)` | [DecodableRecord] | | +| `init(row:)` | [FetchableRecord] | | | `Type.databaseTableName` | [TableRecord] | | | `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | -| `Type.persistenceConflictPolicy` | [EncodableRecord] | [*](#conflict-resolution) | -| `record.encode(to:)` | [EncodableRecord] | | -| `record.didInsert(with:for:)` | [EncodableRecord] | | +| `Type.persistenceConflictPolicy` | [PersistableRecord] | [*](#conflict-resolution) | +| `record.encode(to:)` | [PersistableRecord] | | +| `record.didInsert(with:for:)` | [PersistableRecord] | | | **Insert and Update Records** | | | -| `record.insert(db)` | [EncodableRecord] | | -| `record.save(db)` | [EncodableRecord] | | -| `record.update(db)` | [EncodableRecord] | | -| `record.update(db, columns:...)` | [EncodableRecord] | | -| `record.updateChanges(db, from:...)` | [EncodableRecord] | | +| `record.insert(db)` | [PersistableRecord] | | +| `record.save(db)` | [PersistableRecord] | | +| `record.update(db)` | [PersistableRecord] | | +| `record.update(db, columns:...)` | [PersistableRecord] | | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | | | `record.updateChanges(db)` | [Record](#record-class) | | | **Delete Records** | | | -| `record.delete(db)` | [EncodableRecord] | | -| `Type.deleteOne(db, key:...)` | [EncodableRecord] | ¹ | -| `Type.deleteAll(db)` | [EncodableRecord] | | -| `Type.deleteAll(db, keys:...)` | [EncodableRecord] | ¹ | -| `Type.filter(...).deleteAll(db)` | [EncodableRecord] | ² | +| `record.delete(db)` | [PersistableRecord] | | +| `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | +| `Type.deleteAll(db)` | [PersistableRecord] | | +| `Type.deleteAll(db, keys:...)` | [PersistableRecord] | ¹ | +| `Type.filter(...).deleteAll(db)` | [PersistableRecord] | ² | | **Check Record Existence** | | | -| `record.exists(db)` | [EncodableRecord] | | +| `record.exists(db)` | [PersistableRecord] | | | **Convert Record to Dictionary** | | | -| `record.databaseDictionary` | [EncodableRecord] | | +| `record.databaseDictionary` | [PersistableRecord] | | | **Count Records** | | | | `Type.fetchCount(db)` | [TableRecord] | | | `Type.filter(...).fetchCount(db)` | [TableRecord] | ² | | **Fetch Record [Cursors](#cursors)** | | | -| `Type.fetchCursor(db)` | [DecodableRecord] & [TableRecord] | | -| `Type.fetchCursor(db, keys:...)` | [DecodableRecord] & [TableRecord] | ¹ | -| `Type.fetchCursor(db, sql)` | [DecodableRecord] | ³ | -| `Type.fetchCursor(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchCursor(db)` | [DecodableRecord] & [TableRecord] | ² | +| `Type.fetchCursor(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchCursor(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchCursor(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchCursor(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchCursor(db)` | [FetchableRecord] & [TableRecord] | ² | | **Fetch Record Arrays** | | | -| `Type.fetchAll(db)` | [DecodableRecord] & [TableRecord] | | -| `Type.fetchAll(db, keys:...)` | [DecodableRecord] & [TableRecord] | ¹ | -| `Type.fetchAll(db, sql)` | [DecodableRecord] | ³ | -| `Type.fetchAll(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchAll(db)` | [DecodableRecord] & [TableRecord] | ² | +| `Type.fetchAll(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchAll(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchAll(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchAll(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchAll(db)` | [FetchableRecord] & [TableRecord] | ² | | **Fetch Individual Records** | | | -| `Type.fetchOne(db)` | [DecodableRecord] & [TableRecord] | | -| `Type.fetchOne(db, key:...)` | [DecodableRecord] & [TableRecord] | ¹ | -| `Type.fetchOne(db, sql)` | [DecodableRecord] | ³ | -| `Type.fetchOne(statement)` | [DecodableRecord] | ⁴ | -| `Type.filter(...).fetchOne(db)` | [DecodableRecord] & [TableRecord] | ² | +| `Type.fetchOne(db)` | [FetchableRecord] & [TableRecord] | | +| `Type.fetchOne(db, key:...)` | [FetchableRecord] & [TableRecord] | ¹ | +| `Type.fetchOne(db, sql)` | [FetchableRecord] | ³ | +| `Type.fetchOne(statement)` | [FetchableRecord] | ⁴ | +| `Type.filter(...).fetchOne(db)` | [FetchableRecord] & [TableRecord] | ² | | **[Changes Tracking](#changes-tracking)** | | | -| `record.databaseEqual(...)` | [EncodableRecord] | | -| `record.databaseChanges(from:...)` | [EncodableRecord] | | -| `record.updateChanges(db, from:...)` | [EncodableRecord] | | +| `record.databaseEqual(...)` | [PersistableRecord] | | +| `record.databaseChanges(from:...)` | [PersistableRecord] | | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | | `record.databaseChanges` | [Record](#record-class) | | | `record.updateChanges(db)` | [Record](#record-class) | | @@ -3526,7 +3526,7 @@ let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player? ``` -**When the selected columns don't fit the source type**, change your target: any other type that adopts the [DecodableRecord] protocol, plain [database rows](#fetching-rows), and even [values](#values): +**When the selected columns don't fit the source type**, change your target: any other type that adopts the [FetchableRecord] protocol, plain [database rows](#fetching-rows), and even [values](#values): ```swift let maxScore = try Player.select(max(scoreColumn)) @@ -3663,7 +3663,7 @@ let request = Player.filter(emailColumn == nil) try request.deleteAll(db) ``` -> :point_up: **Note** Deletion methods are only available for records that adopts the [EncodableRecord] protocol. +> :point_up: **Note** Deletion methods are only available for records that adopts the [PersistableRecord] protocol. **Deleting records according to their primary key** is also quite common. It has a shortcut which accepts any single-column primary key: @@ -4606,7 +4606,7 @@ This technique works pretty well, but it has three drawbacks: 1. The selection becomes hard to read and understand. 2. Such queries are difficult to write by hand. -3. The mangled names are a *very* bad fit for [DecodableRecord] records that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. +3. The mangled names are a *very* bad fit for [FetchableRecord] records that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. We thus need another technique. **Below we'll see how to split rows into slices, and preserve column names.** @@ -4715,7 +4715,7 @@ But we may want to make it more usable and robust: 2. Joined records not always need all columns from a table (see `TableRecord.databaseSelection` in [Columns Selected by a Request](#columns-selected-by-a-request)). 3. Building row adapters is long and error prone. -To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [DecodableRecord] protocol: +To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [FetchableRecord] protocol: ```swift struct Item { @@ -4725,7 +4725,7 @@ struct Item { } /// Item can decode rows: -extension Item: DecodableRecord { +extension Item: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4800,7 +4800,7 @@ let items = try dbQueue.inDatabase { db in > :bulb: In this chapter, we have learned: > -> - how to define a `DecodableRecord` record that consumes rows fetched from a joined query. +> - how to define a `FetchableRecord` record that consumes rows fetched from a joined query. > - how to use `selectionSQL` and `numberOfSelectedColumns` in order to deal with nested record types that define custom selection. > - how to use `splittingRowAdapters` in order to streamline the definition of row slices. > - how to gather all relevant methods and constants in a record type, fully responsible of its relationship with the database. @@ -4820,7 +4820,7 @@ struct Item { } /// Item can decode rows: -extension Item: DecodableRecord { +extension Item: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4893,18 +4893,18 @@ Item.all() You can consume complex joined queries with Codable records as well. As a demonstration, we'll rewrite the [above](#splitting-rows-the-request-way) sample code: ```swift -struct Player: Decodable, DecodableRecord, TableRecord { +struct Player: Decodable, FetchableRecord, TableRecord { static let databaseTableName = "players" var id: Int64 var name: String } -struct Team: Decodable, DecodableRecord, TableRecord { +struct Team: Decodable, FetchableRecord, TableRecord { static let databaseTableName = "teams" var id: Int64 var name: String var color: Color } -struct Item: Decodable, DecodableRecord { +struct Item: Decodable, FetchableRecord { var player: Player var team: Team? var maxScore: Int @@ -5303,7 +5303,7 @@ protocol TransactionObserverType : class { It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/). -Given a fetch request, and a type that adopts the [DecodableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. +Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record. See [GRDBDemoiOS](DemoApps/GRDBDemoiOS/GRDBDemoiOS) for an sample app that uses FetchedRecordsController. @@ -5324,7 +5324,7 @@ See also [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), an [RxSwift](https When you initialize a fetched records controller, you provide the following mandatory information: - A [database connection](#database-connections) -- The type of the fetched records. It must be a type that adopts the [DecodableRecord] protocol, such as a subclass of the [Record](#record-class) class +- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](#record-class) class - A fetch request ```swift @@ -5849,7 +5849,7 @@ do { ### PersistenceError -**PersistenceError** is thrown by the [EncodableRecord] protocol, in a single case: when the `update` method could not find any row to update: +**PersistenceError** is thrown by the [PersistableRecord] protocol, in a single case: when the `update` method could not find any row to update: ```swift do { @@ -6918,16 +6918,16 @@ Legacy #### Persistable Protocol -This protocol has been renamed [EncodableRecord] in GRDB 3.0. +This protocol has been renamed [PersistableRecord] in GRDB 3.0. #### RowConvertible Protocol -This protocol has been renamed [DecodableRecord] in GRDB 3.0. +This protocol has been renamed [FetchableRecord] in GRDB 3.0. #### TableMapping Protocol This protocol has been renamed [TableRecord] in GRDB 3.0. -[DecodableRecord]: #decodablerecord-protocol -[EncodableRecord]: #encodablerecord-protocol +[FetchableRecord]: #fetchablerecord-protocol +[PersistableRecord]: #persistablerecord-protocol [TableRecord]: #tablerecord-protocol diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index fe2a4e959..5ee1b405f 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -110,27 +110,27 @@ private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer { } #endif -// MARK: - MutableEncodableRecord +// MARK: - MutablePersistableRecord -private struct UserMutableEncodableRecord1 : MutableEncodableRecord { - static let databaseTableName = "UserMutableEncodableRecord1" +private struct UserMutablePersistableRecord1 : MutablePersistableRecord { + static let databaseTableName = "UserMutablePersistableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserMutableEncodableRecord2 : MutableEncodableRecord { - static let databaseTableName = "UserMutableEncodableRecord2" +private class UserMutablePersistableRecord2 : MutablePersistableRecord { + static let databaseTableName = "UserMutablePersistableRecord2" func encode(to container: inout PersistenceContainer) { } } -// MARK: - EncodableRecord +// MARK: - PersistableRecord -private struct UserEncodableRecord1 : EncodableRecord { - static let databaseTableName = "UserEncodableRecord1" +private struct UserPersistableRecord1 : PersistableRecord { + static let databaseTableName = "UserPersistableRecord1" func encode(to container: inout PersistenceContainer) { } } -private class UserEncodableRecord2 : EncodableRecord { - static let databaseTableName = "UserEncodableRecord2" +private class UserPersistableRecord2 : PersistableRecord { + static let databaseTableName = "UserPersistableRecord2" func encode(to container: inout PersistenceContainer) { } } @@ -142,13 +142,13 @@ private struct UserRowRequest : FetchRequest { func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { preconditionFailure() } } -// MARK: - DecodableRecord +// MARK: - FetchableRecord -private struct UserDecodableRecord1 : DecodableRecord { +private struct UserFetchableRecord1 : FetchableRecord { init(row: Row) { } } -private class UserDecodableRecord2 : DecodableRecord { +private class UserFetchableRecord2 : FetchableRecord { required init(row: Row) { } } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index fd799dbe7..aa606459c 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -14,7 +14,7 @@ private struct Book { let body: String } -extension Book : DecodableRecord { +extension Book : FetchableRecord { init(row: Row) { id = row[.rowID] title = row["title"] @@ -23,7 +23,7 @@ extension Book : DecodableRecord { } } -extension Book : MutableEncodableRecord { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index c590d09ce..42d1e201a 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -14,7 +14,7 @@ private struct Book { let body: String } -extension Book : DecodableRecord { +extension Book : FetchableRecord { init(row: Row) { id = row[.rowID] title = row["title"] @@ -23,7 +23,7 @@ extension Book : DecodableRecord { } } -extension Book : MutableEncodableRecord { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 4984b62a8..815fb0201 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -15,7 +15,7 @@ private struct Book { let body: String } -extension Book : DecodableRecord { +extension Book : FetchableRecord { init(row: Row) { id = row[.rowID] title = row["title"] @@ -24,7 +24,7 @@ extension Book : DecodableRecord { } } -extension Book : MutableEncodableRecord { +extension Book : MutablePersistableRecord { static let databaseTableName = "books" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] diff --git a/Tests/GRDBTests/FetchRequestTests.swift b/Tests/GRDBTests/FetchRequestTests.swift index 181422123..6ba92882a 100644 --- a/Tests/GRDBTests/FetchRequestTests.swift +++ b/Tests/GRDBTests/FetchRequestTests.swift @@ -60,7 +60,7 @@ class FetchRequestTests: GRDBTestCase { } func testRequestFetchRecords() throws { - struct CustomRecord: DecodableRecord, Decodable { + struct CustomRecord: FetchableRecord, Decodable { var id: Int } struct CustomRequest : FetchRequest { diff --git a/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift similarity index 96% rename from Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift rename to Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 657ac2e45..7363a7753 100644 --- a/Tests/GRDBTests/DecodableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -13,7 +13,7 @@ private struct Reader { let age: Int? } -extension Reader : DecodableRecord { +extension Reader : FetchableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -21,7 +21,7 @@ extension Reader : DecodableRecord { } } -extension Reader : MutableEncodableRecord { +extension Reader : MutablePersistableRecord { static let databaseTableName = "readers" func encode(to container: inout PersistenceContainer) { @@ -41,7 +41,7 @@ private struct AltReader { let age: Int? } -extension AltReader : DecodableRecord { +extension AltReader : FetchableRecord { init(row: Row) { id = row["id"] name = row["name"] @@ -50,7 +50,7 @@ extension AltReader : DecodableRecord { } -class DecodableRecordQueryInterfaceRequestTests: GRDBTestCase { +class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -66,7 +66,7 @@ class DecodableRecordQueryInterfaceRequestTests: GRDBTestCase { } - // MARK: - Fetch DecodableRecord + // MARK: - Fetch FetchableRecord func testAll() throws { let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/DecodableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift similarity index 89% rename from Tests/GRDBTests/DecodableRecordDecodableTests.swift rename to Tests/GRDBTests/FetchableRecordDecodableTests.swift index 35b469c0b..03ab93312 100644 --- a/Tests/GRDBTests/DecodableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -8,14 +8,14 @@ import XCTest import GRDB #endif -class DecodableRecordDecodableTests: GRDBTestCase { } +class FetchableRecordDecodableTests: GRDBTestCase { } -// MARK: - DecodableRecord conformance derived from Decodable +// MARK: - FetchableRecord conformance derived from Decodable -extension DecodableRecordDecodableTests { +extension FetchableRecordDecodableTests { func testTrivialDecodable() { - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: String } @@ -26,7 +26,7 @@ extension DecodableRecordDecodableTests { } func testCustomDecodable() { - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: String private enum CodingKeys : String, CodingKey { @@ -45,28 +45,28 @@ extension DecodableRecordDecodableTests { } } - func testCustomDecodableRecord() { - struct Struct : DecodableRecord, Decodable { + func testCustomFetchableRecord() { + struct Struct : FetchableRecord, Decodable { let value: String init(row: Row) { - value = (row["value"] as String) + " (DecodableRecord)" + value = (row["value"] as String) + " (FetchableRecord)" } } do { let s = Struct(row: ["value": "foo"]) - XCTAssertEqual(s.value, "foo (DecodableRecord)") + XCTAssertEqual(s.value, "foo (FetchableRecord)") } } } // MARK: - Different kinds of single-value properties -extension DecodableRecordDecodableTests { +extension FetchableRecordDecodableTests { func testTrivialProperty() { - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let int64: Int64 let optionalInt64: Int64? } @@ -100,7 +100,7 @@ extension DecodableRecordDecodableTests { } } - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -144,7 +144,7 @@ extension DecodableRecordDecodableTests { } } - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -181,7 +181,7 @@ extension DecodableRecordDecodableTests { case foo, bar } - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -239,7 +239,7 @@ extension DecodableRecordDecodableTests { } } - struct Struct : DecodableRecord, Decodable { + struct Struct : FetchableRecord, Decodable { let value: Value let optionalValue: Value? } @@ -269,10 +269,10 @@ extension DecodableRecordDecodableTests { // MARK: - Foundation Codable Types -extension DecodableRecordDecodableTests { +extension FetchableRecordDecodableTests { func testStructWithDate() { - struct StructWithDate : DecodableRecord, Decodable { + struct StructWithDate : FetchableRecord, Decodable { let date: Date } @@ -282,7 +282,7 @@ extension DecodableRecordDecodableTests { } func testStructWithURL() { - struct StructWithURL : DecodableRecord, Decodable { + struct StructWithURL : FetchableRecord, Decodable { let url: URL } @@ -292,7 +292,7 @@ extension DecodableRecordDecodableTests { } func testStructWithUUID() { - struct StructWithUUID : DecodableRecord, Decodable { + struct StructWithUUID : FetchableRecord, Decodable { let uuid: UUID } diff --git a/Tests/GRDBTests/DecodableRecordTests.swift b/Tests/GRDBTests/FetchableRecordTests.swift similarity index 99% rename from Tests/GRDBTests/DecodableRecordTests.swift rename to Tests/GRDBTests/FetchableRecordTests.swift index 94468a520..3ca8be371 100644 --- a/Tests/GRDBTests/DecodableRecordTests.swift +++ b/Tests/GRDBTests/FetchableRecordTests.swift @@ -12,14 +12,14 @@ private struct Fetched { var lastName: String } -extension Fetched : DecodableRecord { +extension Fetched : FetchableRecord { init(row: Row) { firstName = row["firstName"] lastName = row["lastName"] } } -class DecodableRecordTests: GRDBTestCase { +class FetchableRecordTests: GRDBTestCase { func testRowInitializer() { let row = Row(["firstName": "Arthur", "lastName": "Martin"]) diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift index 2037cbba0..ad7da48d3 100644 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ b/Tests/GRDBTests/FetchedRecordsControllerTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private class ChangesRecorder { +private class ChangesRecorder { var changes: [(record: Record, change: FetchedRecordChange)] = [] var recordsBeforeChanges: [Record]! var recordsAfterChanges: [Record]! @@ -85,7 +85,7 @@ private class Person : Record { } } -private struct Book : DecodableRecord { +private struct Book : FetchableRecord { var id: Int64 var authorID: Int64 var title: String diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index c9c0fac79..314cb5b67 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -131,7 +131,7 @@ class GRDBTestCase: XCTestCase { XCTAssertTrue(sqlQueries.contains(sql), "Did not execute \(sql)") } - func assert(_ record: MutableEncodableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { + func assert(_ record: MutablePersistableRecord, isEncodedIn row: Row, file: StaticString = #file, line: UInt = #line) { let recordDict = record.databaseDictionary let rowDict = Dictionary(row, uniquingKeysWith: { (left, _) in left }) XCTAssertEqual(recordDict, rowDict, file: file, line: line) diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index bb638889e..a144bb860 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -41,33 +41,33 @@ let testedSQL = """ ORDER BY t1.id """ -private struct T1: Codable, DecodableRecord, TableRecord { +private struct T1: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t1" var id: Int64 var name: String } -private struct T2: Codable, DecodableRecord, TableRecord { +private struct T2: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t2" var id: Int64 var t1id: Int64 var name: String } -private struct T3: Codable, DecodableRecord, TableRecord { +private struct T3: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t3" static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")] var t1id: Int64 var name: String } -private struct T4: Codable, DecodableRecord, TableRecord { +private struct T4: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t4" var t1id: Int64 var name: String } -private struct T5: Codable, DecodableRecord, TableRecord { +private struct T5: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t5" var id: Int64 var t3id: Int64? @@ -75,7 +75,7 @@ private struct T5: Codable, DecodableRecord, TableRecord { var name: String } -private struct FlatModel: DecodableRecord { +private struct FlatModel: FetchableRecord { private enum Scopes { static let t1 = "t1" static let t2Left = "t2Left" @@ -115,7 +115,7 @@ private struct FlatModel: DecodableRecord { } } -private struct CodableFlatModel: DecodableRecord, Codable { +private struct CodableFlatModel: FetchableRecord, Codable { var t1: T1 var t2Left: T2? var t2Right: T2? @@ -138,7 +138,7 @@ private struct CodableFlatModel: DecodableRecord, Codable { } } -private struct CodableNestedModel: DecodableRecord, Codable { +private struct CodableNestedModel: FetchableRecord, Codable { struct T2Pair: Codable { var left: T2? var right: T2? diff --git a/Tests/GRDBTests/MutableEncodableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift similarity index 97% rename from Tests/GRDBTests/MutableEncodableRecordChangesTests.swift rename to Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index 04d918c7d..bf2acc47f 100644 --- a/Tests/GRDBTests/MutableEncodableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct Player: DecodableRecord, MutableEncodableRecord, Codable { +private struct Player: FetchableRecord, MutablePersistableRecord, Codable { static let databaseTableName = "players" var id: Int64? @@ -34,7 +34,7 @@ private struct Player: DecodableRecord, MutableEncodableRecord, Codable { } } -class MutableEncodableRecordChangesTests: GRDBTestCase { +class MutablePersistableRecordChangesTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "players") { t in @@ -47,7 +47,7 @@ class MutableEncodableRecordChangesTests: GRDBTestCase { } func testDegenerateDatabaseEqualWithSelf() throws { - struct DegenerateRecord: MutableEncodableRecord { + struct DegenerateRecord: MutablePersistableRecord { static let databaseTableName = "ignored" func encode(to container: inout PersistenceContainer) { } @@ -174,7 +174,7 @@ class MutableEncodableRecordChangesTests: GRDBTestCase { func testDatabaseEqualWithDifferentTypesAndDifferentWidth() throws { // Mangle column case as well, for fun ;-) - struct NarrowPlayer: MutableEncodableRecord, Codable { + struct NarrowPlayer: MutablePersistableRecord, Codable { static let databaseTableName = "players" var ID: Int64? var NAME: String? diff --git a/Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift similarity index 97% rename from Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift rename to Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index d0455f179..011927b1c 100644 --- a/Tests/GRDBTests/MutableEncodableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -7,23 +7,23 @@ import XCTest import GRDB #endif -private struct Hacker : MutableEncodableRecord { +private struct Hacker : MutablePersistableRecord { static let databaseTableName = "hackers" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Person : MutableEncodableRecord { +private struct Person : MutablePersistableRecord { static let databaseTableName = "persons" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -private struct Citizenship : MutableEncodableRecord { +private struct Citizenship : MutablePersistableRecord { static let databaseTableName = "citizenships" func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } } -class MutableEncodableRecordDeleteTests: GRDBTestCase { +class MutablePersistableRecordDeleteTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in diff --git a/Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift similarity index 91% rename from Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift rename to Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 7d270ebf7..70f238d7a 100644 --- a/Tests/GRDBTests/MutableEncodableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -8,14 +8,14 @@ import Foundation import GRDB #endif -class MutableEncodableRecordEncodableTests: GRDBTestCase { } +class MutablePersistableRecordEncodableTests: GRDBTestCase { } -// MARK: - MutableEncodableRecord conformance derived from Encodable +// MARK: - MutablePersistableRecord conformance derived from Encodable -extension MutableEncodableRecordEncodableTests { +extension MutablePersistableRecordEncodableTests { func testTrivialEncodable() throws { - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String } @@ -36,7 +36,7 @@ extension MutableEncodableRecordEncodableTests { } func testCustomEncodable() throws { - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String @@ -65,13 +65,13 @@ extension MutableEncodableRecordEncodableTests { } } - func testCustomMutableEncodableRecord() throws { - struct Struct : MutableEncodableRecord, Encodable { + func testCustomMutablePersistableRecord() throws { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: String func encode(to container: inout PersistenceContainer) { - container["value"] = value + " (MutableEncodableRecord)" + container["value"] = value + " (MutablePersistableRecord)" } } @@ -82,21 +82,21 @@ extension MutableEncodableRecordEncodableTests { } var value = Struct(value: "foo") - assert(value, isEncodedIn: ["value": "foo (MutableEncodableRecord)"]) + assert(value, isEncodedIn: ["value": "foo (MutablePersistableRecord)"]) try value.insert(db) let string = try String.fetchOne(db, "SELECT value FROM t1")! - XCTAssertEqual(string, "foo (MutableEncodableRecord)") + XCTAssertEqual(string, "foo (MutablePersistableRecord)") } } } // MARK: - Different kinds of single-value properties -extension MutableEncodableRecordEncodableTests { +extension MutablePersistableRecordEncodableTests { func testTrivialProperty() throws { - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let int64: Int64 let optionalInt64: Int64? @@ -141,7 +141,7 @@ extension MutableEncodableRecordEncodableTests { } } - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -195,7 +195,7 @@ extension MutableEncodableRecordEncodableTests { } } - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -240,7 +240,7 @@ extension MutableEncodableRecordEncodableTests { case foo, bar } - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -303,7 +303,7 @@ extension MutableEncodableRecordEncodableTests { } } - struct Struct : MutableEncodableRecord, Encodable { + struct Struct : MutablePersistableRecord, Encodable { static let databaseTableName = "t1" let value: Value let optionalValue: Value? @@ -341,10 +341,10 @@ extension MutableEncodableRecordEncodableTests { // MARK: - Foundation Codable Types -extension MutableEncodableRecordEncodableTests { +extension MutablePersistableRecordEncodableTests { func testStructWithDate() throws { - struct StructWithDate : EncodableRecord, Encodable { + struct StructWithDate : PersistableRecord, Encodable { static let databaseTableName = "t1" let date: Date } @@ -371,7 +371,7 @@ extension MutableEncodableRecordEncodableTests { } func testStructWithURL() throws { - struct StructWithURL : EncodableRecord, Encodable { + struct StructWithURL : PersistableRecord, Encodable { static let databaseTableName = "t1" let url: URL } @@ -394,7 +394,7 @@ extension MutableEncodableRecordEncodableTests { } func testStructWithUUID() throws { - struct StructWithUUID : EncodableRecord, Encodable { + struct StructWithUUID : PersistableRecord, Encodable { static let databaseTableName = "t1" let uuid: UUID } diff --git a/Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift similarity index 95% rename from Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift rename to Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index ca7a75ee4..b4f022efe 100644 --- a/Tests/GRDBTests/MutableEncodableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct DefaultPolicy: MutableEncodableRecord { +private struct DefaultPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -21,7 +21,7 @@ private struct DefaultPolicy: MutableEncodableRecord { } } -private struct MixedPolicy: MutableEncodableRecord { +private struct MixedPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -36,7 +36,7 @@ private struct MixedPolicy: MutableEncodableRecord { } } -private struct ReplacePolicy: MutableEncodableRecord { +private struct ReplacePolicy: MutablePersistableRecord { var id: Int64? var email: String @@ -53,7 +53,7 @@ private struct ReplacePolicy: MutableEncodableRecord { } } -private struct IgnorePolicy: MutableEncodableRecord { +private struct IgnorePolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -68,7 +68,7 @@ private struct IgnorePolicy: MutableEncodableRecord { } } -private struct FailPolicy: MutableEncodableRecord { +private struct FailPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -83,7 +83,7 @@ private struct FailPolicy: MutableEncodableRecord { } } -private struct AbortPolicy: MutableEncodableRecord { +private struct AbortPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -98,7 +98,7 @@ private struct AbortPolicy: MutableEncodableRecord { } } -private struct RollbackPolicy: MutableEncodableRecord { +private struct RollbackPolicy: MutablePersistableRecord { var id: Int64? static let databaseTableName = "records" @@ -113,7 +113,7 @@ private struct RollbackPolicy: MutableEncodableRecord { } } -class MutableEncodableRecordPersistenceConflictPolicyTests: GRDBTestCase { +class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { func testPolicyDefaultArguments() { let policy = PersistenceConflictPolicy() diff --git a/Tests/GRDBTests/MutableEncodableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift similarity index 86% rename from Tests/GRDBTests/MutableEncodableRecordTests.swift rename to Tests/GRDBTests/MutablePersistableRecordTests.swift index f9f860fc9..0ef4f7b01 100644 --- a/Tests/GRDBTests/MutableEncodableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct MutableEncodableRecordPerson : MutableEncodableRecord { +private struct MutablePersistableRecordPerson : MutablePersistableRecord { var id: Int64? var name: String? var age: Int? @@ -26,7 +26,7 @@ private struct MutableEncodableRecordPerson : MutableEncodableRecord { } } -private struct MutableEncodableRecordCountry : MutableEncodableRecord { +private struct MutablePersistableRecordCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String @@ -43,7 +43,7 @@ private struct MutableEncodableRecordCountry : MutableEncodableRecord { } } -private struct MutableEncodableRecordCustomizedCountry : MutableEncodableRecord { +private struct MutablePersistableRecordCustomizedCountry : MutablePersistableRecord { var rowID: Int64? var isoCode: String var name: String @@ -90,7 +90,7 @@ private struct MutableEncodableRecordCustomizedCountry : MutableEncodableRecord } } -class MutableEncodableRecordTests: GRDBTestCase { +class MutablePersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -109,12 +109,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } - // MARK: - MutableEncodableRecordPerson + // MARK: - MutablePersistableRecordPerson - func testInsertMutableEncodableRecordPerson() throws { + func testInsertMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -124,12 +124,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testUpdateMutableEncodableRecordPerson() throws { + func testUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) person1.name = "Craig" @@ -148,12 +148,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testPartialUpdateMutableEncodableRecordPerson() throws { + func testPartialUpdateMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 36) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -204,10 +204,10 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testSaveMutableEncodableRecordPerson() throws { + func testSaveMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -215,7 +215,7 @@ class MutableEncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.save(db) person1.name = "Craig" @@ -240,12 +240,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testDeleteMutableEncodableRecordPerson() throws { + func testDeleteMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person1 = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person1 = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person1.insert(db) - var person2 = MutableEncodableRecordPerson(id: nil, name: "Barbara", age: 24) + var person2 = MutablePersistableRecordPerson(id: nil, name: "Barbara", age: 24) try person2.insert(db) var deleted = try person1.delete(db) @@ -260,10 +260,10 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testExistsMutableEncodableRecordPerson() throws { + func testExistsMutablePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + var person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -272,18 +272,18 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testMutableEncodableRecordPersonDatabaseDictionary() { - let person = MutableEncodableRecordPerson(id: nil, name: "Arthur", age: 24) + func testMutablePersistableRecordPersonDatabaseDictionary() { + let person = MutablePersistableRecordPerson(id: nil, name: "Arthur", age: 24) let dict = person.databaseDictionary XCTAssertEqual(dict, ["iD": DatabaseValue.null, "NAme": "Arthur".databaseValue, "aGe": 24.databaseValue]) } - // MARK: - MutableEncodableRecordCountry + // MARK: - MutablePersistableRecordCountry - func testInsertMutableEncodableRecordCountry() throws { + func testInsertMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -293,12 +293,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testUpdateMutableEncodableRecordCountry() throws { + func testUpdateMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -314,10 +314,10 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testSaveMutableEncodableRecordCountry() throws { + func testSaveMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT rowID, * FROM countries") @@ -325,7 +325,7 @@ class MutableEncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -350,12 +350,12 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testDeleteMutableEncodableRecordCountry() throws { + func testDeleteMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") + var country1 = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country1.insert(db) - var country2 = MutableEncodableRecordCountry(rowID: nil, isoCode: "US", name: "United States") + var country2 = MutablePersistableRecordCountry(rowID: nil, isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -370,10 +370,10 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testExistsMutableEncodableRecordCountry() throws { + func testExistsMutablePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country = MutableEncodableRecordCountry(rowID: nil, isoCode: "FR", name: "France") + var country = MutablePersistableRecordCountry(rowID: nil, isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -383,9 +383,9 @@ class MutableEncodableRecordTests: GRDBTestCase { } - // MARK: - MutableEncodableRecordCustomizedCountry + // MARK: - MutablePersistableRecordCustomizedCountry - func testInsertMutableEncodableRecordCustomizedCountry() throws { + func testInsertMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -393,7 +393,7 @@ class MutableEncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutableEncodableRecordCustomizedCountry( + var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -417,7 +417,7 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testUpdateMutableEncodableRecordCustomizedCountry() throws { + func testUpdateMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -425,7 +425,7 @@ class MutableEncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutableEncodableRecordCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -435,7 +435,7 @@ class MutableEncodableRecordTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutableEncodableRecordCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -465,7 +465,7 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testSaveMutableEncodableRecordCustomizedCountry() throws { + func testSaveMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -473,7 +473,7 @@ class MutableEncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutableEncodableRecordCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -495,7 +495,7 @@ class MutableEncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["rowID"] as Int64, country1.rowID!) XCTAssertEqual(rows[0]["name"] as String, "France") - var country2 = MutableEncodableRecordCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -540,7 +540,7 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testDeleteMutableEncodableRecordCustomizedCountry() throws { + func testDeleteMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -548,7 +548,7 @@ class MutableEncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = MutableEncodableRecordCustomizedCountry( + var country1 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -558,7 +558,7 @@ class MutableEncodableRecordTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - var country2 = MutableEncodableRecordCustomizedCountry( + var country2 = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "US", name: "United States", @@ -587,7 +587,7 @@ class MutableEncodableRecordTests: GRDBTestCase { } } - func testExistsMutableEncodableRecordCustomizedCountry() throws { + func testExistsMutablePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -595,7 +595,7 @@ class MutableEncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country = MutableEncodableRecordCustomizedCountry( + var country = MutablePersistableRecordCustomizedCountry( rowID: nil, isoCode: "FR", name: "France", @@ -627,7 +627,7 @@ class MutableEncodableRecordTests: GRDBTestCase { // MARK: - Misc func testPartiallyEncodedRecord() throws { - struct PartialRecord : MutableEncodableRecord { + struct PartialRecord : MutablePersistableRecord { var id: Int64? var a: String diff --git a/Tests/GRDBTests/EncodableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift similarity index 85% rename from Tests/GRDBTests/EncodableRecordTests.swift rename to Tests/GRDBTests/PersistableRecordTests.swift index 86ccb3c8d..33ddb04d1 100644 --- a/Tests/GRDBTests/EncodableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -7,7 +7,7 @@ import XCTest import GRDB #endif -private struct EncodableRecordPerson : EncodableRecord { +private struct PersistableRecordPerson : PersistableRecord { var name: String? var age: Int? @@ -19,7 +19,7 @@ private struct EncodableRecordPerson : EncodableRecord { } } -private class EncodableRecordPersonClass : EncodableRecord { +private class PersistableRecordPersonClass : PersistableRecord { var id: Int64? var name: String? var age: Int? @@ -44,7 +44,7 @@ private class EncodableRecordPersonClass : EncodableRecord { } } -private struct EncodableRecordCountry : EncodableRecord { +private struct PersistableRecordCountry : PersistableRecord { var isoCode: String var name: String @@ -56,7 +56,7 @@ private struct EncodableRecordCountry : EncodableRecord { } } -private struct EncodableRecordCustomizedCountry : EncodableRecord { +private struct PersistableRecordCustomizedCountry : PersistableRecord { var isoCode: String var name: String let willInsert: () -> Void @@ -98,7 +98,7 @@ private struct EncodableRecordCustomizedCountry : EncodableRecord { } } -private struct Citizenship : EncodableRecord { +private struct Citizenship : PersistableRecord { let personID: Int64 let countryIsoCode: String @@ -110,7 +110,7 @@ private struct Citizenship : EncodableRecord { } } -class EncodableRecordTests: GRDBTestCase { +class PersistableRecordTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() @@ -132,12 +132,12 @@ class EncodableRecordTests: GRDBTestCase { } - // MARK: - EncodableRecordPerson + // MARK: - PersistableRecordPerson - func testInsertEncodableRecordPerson() throws { + func testInsertPersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = EncodableRecordPerson(name: "Arthur", age: 42) + let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -146,10 +146,10 @@ class EncodableRecordTests: GRDBTestCase { } } - func testSaveEncodableRecordPerson() throws { + func testSavePersistableRecordPerson() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = EncodableRecordPerson(name: "Arthur", age: 42) + let person = PersistableRecordPerson(name: "Arthur", age: 42) try person.save(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -159,12 +159,12 @@ class EncodableRecordTests: GRDBTestCase { } - // MARK: - EncodableRecordPersonClass + // MARK: - PersistableRecordPersonClass - func testInsertEncodableRecordPersonClass() throws { + func testInsertPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -174,12 +174,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testUpdateEncodableRecordPersonClass() throws { + func testUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) person1.name = "Craig" @@ -198,12 +198,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testPartialUpdateEncodableRecordPersonClass() throws { + func testPartialUpdatePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 24) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 24) try person1.insert(db) - let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 36) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 36) try person2.insert(db) do { @@ -254,10 +254,10 @@ class EncodableRecordTests: GRDBTestCase { } } - func testSaveEncodableRecordPersonClass() throws { + func testSavePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM persons") @@ -265,7 +265,7 @@ class EncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["id"] as Int64, person1.id!) XCTAssertEqual(rows[0]["name"] as String, "Arthur") - let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.save(db) person1.name = "Craig" @@ -290,12 +290,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testDeleteEncodableRecordPersonClass() throws { + func testDeletePersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person1 = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) + let person1 = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person1.insert(db) - let person2 = EncodableRecordPersonClass(id: nil, name: "Barbara", age: 39) + let person2 = PersistableRecordPersonClass(id: nil, name: "Barbara", age: 39) try person2.insert(db) var deleted = try person1.delete(db) @@ -310,10 +310,10 @@ class EncodableRecordTests: GRDBTestCase { } } - func testExistsEncodableRecordPersonClass() throws { + func testExistsPersistableRecordPersonClass() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 42) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 42) try person.insert(db) XCTAssertTrue(try person.exists(db)) @@ -323,12 +323,12 @@ class EncodableRecordTests: GRDBTestCase { } - // MARK: - EncodableRecordCountry + // MARK: - PersistableRecordCountry - func testInsertEncodableRecordCountry() throws { + func testInsertPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = EncodableRecordCountry(isoCode: "FR", name: "France") + let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) let rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -338,12 +338,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testUpdateEncodableRecordCountry() throws { + func testUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) country1.name = "France Métropolitaine" @@ -359,12 +359,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testPartialUpdateEncodableRecordCountry() throws { + func testPartialUpdatePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) do { @@ -395,10 +395,10 @@ class EncodableRecordTests: GRDBTestCase { } } - func testSaveEncodableRecordCountry() throws { + func testSavePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var country1 = EncodableRecordCountry(isoCode: "FR", name: "France") + var country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.save(db) var rows = try Row.fetchAll(db, "SELECT * FROM countries") @@ -406,7 +406,7 @@ class EncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.save(db) country1.name = "France Métropolitaine" @@ -431,12 +431,12 @@ class EncodableRecordTests: GRDBTestCase { } } - func testDeleteEncodableRecordCountry() throws { + func testDeletePersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country1 = EncodableRecordCountry(isoCode: "FR", name: "France") + let country1 = PersistableRecordCountry(isoCode: "FR", name: "France") try country1.insert(db) - let country2 = EncodableRecordCountry(isoCode: "US", name: "United States") + let country2 = PersistableRecordCountry(isoCode: "US", name: "United States") try country2.insert(db) var deleted = try country1.delete(db) @@ -451,10 +451,10 @@ class EncodableRecordTests: GRDBTestCase { } } - func testExistsEncodableRecordCountry() throws { + func testExistsPersistableRecordCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let country = EncodableRecordCountry(isoCode: "FR", name: "France") + let country = PersistableRecordCountry(isoCode: "FR", name: "France") try country.insert(db) XCTAssertTrue(try country.exists(db)) @@ -464,9 +464,9 @@ class EncodableRecordTests: GRDBTestCase { } - // MARK: - EncodableRecordCustomizedCountry + // MARK: - PersistableRecordCustomizedCountry - func testInsertEncodableRecordCustomizedCountry() throws { + func testInsertPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -474,7 +474,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = EncodableRecordCustomizedCountry( + let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -497,7 +497,7 @@ class EncodableRecordTests: GRDBTestCase { } } - func testUpdateEncodableRecordCustomizedCountry() throws { + func testUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -505,7 +505,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = EncodableRecordCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -514,7 +514,7 @@ class EncodableRecordTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = EncodableRecordCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -543,7 +543,7 @@ class EncodableRecordTests: GRDBTestCase { } } - func testPartialUpdateEncodableRecordCustomizedCountry() throws { + func testPartialUpdatePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -551,7 +551,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = EncodableRecordCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -560,7 +560,7 @@ class EncodableRecordTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = EncodableRecordCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -589,7 +589,7 @@ class EncodableRecordTests: GRDBTestCase { } } - func testSaveEncodableRecordCustomizedCountry() throws { + func testSavePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -597,7 +597,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - var country1 = EncodableRecordCustomizedCountry( + var country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -618,7 +618,7 @@ class EncodableRecordTests: GRDBTestCase { XCTAssertEqual(rows[0]["isoCode"] as String, "FR") XCTAssertEqual(rows[0]["name"] as String, "France") - let country2 = EncodableRecordCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -662,7 +662,7 @@ class EncodableRecordTests: GRDBTestCase { } } - func testDeleteEncodableRecordCustomizedCountry() throws { + func testDeletePersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -670,7 +670,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country1 = EncodableRecordCustomizedCountry( + let country1 = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -679,7 +679,7 @@ class EncodableRecordTests: GRDBTestCase { willDelete: { deleteCount += 1 }, willExists: { existsCount += 1 }) try country1.insert(db) - let country2 = EncodableRecordCustomizedCountry( + let country2 = PersistableRecordCustomizedCountry( isoCode: "US", name: "United States", willInsert: { }, @@ -707,7 +707,7 @@ class EncodableRecordTests: GRDBTestCase { } } - func testExistsEncodableRecordCustomizedCountry() throws { + func testExistsPersistableRecordCustomizedCountry() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var insertCount: Int = 0 @@ -715,7 +715,7 @@ class EncodableRecordTests: GRDBTestCase { var saveCount: Int = 0 var deleteCount: Int = 0 var existsCount: Int = 0 - let country = EncodableRecordCustomizedCountry( + let country = PersistableRecordCustomizedCountry( isoCode: "FR", name: "France", willInsert: { insertCount += 1 }, @@ -749,9 +749,9 @@ class EncodableRecordTests: GRDBTestCase { func testInsertErrorDoesNotPreventSubsequentInserts() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let person = EncodableRecordPersonClass(id: nil, name: "Arthur", age: 12) + let person = PersistableRecordPersonClass(id: nil, name: "Arthur", age: 12) try person.insert(db) - try EncodableRecordCountry(isoCode: "FR", name: "France").insert(db) + try PersistableRecordCountry(isoCode: "FR", name: "France").insert(db) do { try Citizenship(personID: person.id!, countryIsoCode: "US").insert(db) } catch let error as DatabaseError { diff --git a/Tests/GRDBTests/RecordBoxTests.swift b/Tests/GRDBTests/RecordBoxTests.swift index 481590e47..8872ca6f3 100644 --- a/Tests/GRDBTests/RecordBoxTests.swift +++ b/Tests/GRDBTests/RecordBoxTests.swift @@ -10,7 +10,7 @@ import XCTest typealias RecordBox = GRDB.RecordBox // Single deprecation warning #endif -private struct Player: DecodableRecord, MutableEncodableRecord, Codable { +private struct Player: FetchableRecord, MutablePersistableRecord, Codable { static let databaseTableName = "players" var id: Int64? diff --git a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift index c6611fd02..27f9adc71 100644 --- a/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift +++ b/Tests/GRDBTests/RecordPersistenceConflictPolicy.swift @@ -20,14 +20,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase { func testDefaultPersistenceConflictPolicy() { let record = RecordWithoutPersistenceConflictPolicy() - let policy = type(of: record as MutableEncodableRecord).persistenceConflictPolicy + let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .abort) XCTAssertEqual(policy.conflictResolutionForUpdate, .abort) } func testConfigurablePersistenceConflictPolicy() { let record = RecordWithPersistenceConflictPolicy() - let policy = type(of: record as MutableEncodableRecord).persistenceConflictPolicy + let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy XCTAssertEqual(policy.conflictResolutionForInsert, .fail) XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore) } diff --git a/Tests/GRDBTests/RecordUniqueIndexTests.swift b/Tests/GRDBTests/RecordUniqueIndexTests.swift index 2ffd67fe4..6633e444f 100644 --- a/Tests/GRDBTests/RecordUniqueIndexTests.swift +++ b/Tests/GRDBTests/RecordUniqueIndexTests.swift @@ -7,7 +7,7 @@ import XCTest @testable import GRDB #endif -private struct Person : DecodableRecord, TableRecord { +private struct Person : FetchableRecord, TableRecord { static let databaseTableName = "persons" init(row: Row) { } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 3f9bf8730..07db51c5a 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -100,7 +100,7 @@ private final class Artist: Codable { } } -extension Artist : DecodableRecord, EncodableRecord { +extension Artist : FetchableRecord, PersistableRecord { static let databaseTableName = "artists" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID @@ -119,7 +119,7 @@ private final class Artwork : Codable { } } -extension Artwork : DecodableRecord, EncodableRecord { +extension Artwork : FetchableRecord, PersistableRecord { static let databaseTableName = "artworks" func didInsert(with rowID: Int64, for column: String?) { self.id = rowID diff --git a/Tests/Performance/PerformanceTests.swift b/Tests/Performance/PerformanceTests.swift index 0e319e24f..a606b2f30 100644 --- a/Tests/Performance/PerformanceTests.swift +++ b/Tests/Performance/PerformanceTests.swift @@ -7,7 +7,7 @@ import RealmSwift // MARK:- GRDB -struct ItemStruct : DecodableRecord, EncodableRecord { +struct ItemStruct : FetchableRecord, PersistableRecord { var i0: Int var i1: Int var i2: Int diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index c3ce2678b..7757a0a38 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -103,11 +103,11 @@ As a bottom line, the raw SQLite C API is used as efficiently as possible, witho This test fetches an array of 100000 record objects initiated from rows of 10 ints. - It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [DecodableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#decodablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. + It builds records from FMDB's `-[FMResultSet resultDictionary]`, GRDB's built-in [FetchableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#fetchablerecord-protocol) protocol, and the values returned by the high-level query builder of SQLite.swift. - **Insert** ([source](https://github.com/groue/GRDB.swift/blob/master/Tests/Performance/InsertRecordStructTests.swift)) - This tests inserts 20000 records with the persistence method provided by GRDB's [EncodableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#encodablerecord-protocol) protocol. + This tests inserts 20000 records with the persistence method provided by GRDB's [PersistableRecord](https://github.com/groue/GRDB.swift/blob/master/README.md#persistablerecord-protocol) protocol. - **Records with change tracking**: From 6a8dec11ea10db1a02d05204f04af95b8ad5110c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 20:10:06 +0100 Subject: [PATCH 023/348] Record protocols changelog --- CHANGELOG.md | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e153e9f9f..00d5be4d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,12 +5,33 @@ Release Notes ### Breaking Changes +- The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord`. - `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([311](https://github.com/groue/GRDB.swift/pull/311)) - The `IteratorCursor` type has been removed. Use `AnyCursor` instead. ### API diff +**Record protocols** + +```diff +-protocol RowConvertible { ++protocol FetchableRecord { + } + +-protocol TableMapping { ++protocol TableRecord { + } + +-protocol MutablePersistable: TableMapping { ++protocol MutablePersistableRecord: TableRecord { + } + +-protocol Persistable: MutablePersistable { ++protocol PersistableRecord: MutablePersistableRecord { + } +``` + **FetchRequest** ```diff @@ -60,7 +81,7 @@ Release Notes + func fetchOne(_ db: Database) throws -> Row? +} -+extension FetchRequest where RowDecoder: RowConvertible { ++extension FetchRequest where RowDecoder: FetchableRecord { + func fetchCursor(_ db: Database) throws -> RecordCursor + func fetchAll(_ db: Database) throws -> [RowDecoder] + func fetchOne(_ db: Database) throws -> RowDecoder? From 487f4e220f8a2933f15dd812fa1123d93d86ea1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 27 Feb 2018 20:10:13 +0100 Subject: [PATCH 024/348] Record protocols fixit --- GRDB/Legacy/Fixits-3.0.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index a2e9f8b8c..b27bc9362 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -1,3 +1,14 @@ @available(*, unavailable, renamed:"FetchRequest") public typealias Request = FetchRequest +@available(*, unavailable, renamed:"FetchableRecord") +public typealias RowConvertible = FetchableRecord + +@available(*, unavailable, renamed:"TableRecord") +public typealias TableMapping = TableRecord + +@available(*, unavailable, renamed:"MutablePersistableRecord") +public typealias MutablePersistable = MutablePersistableRecord + +@available(*, unavailable, renamed:"PersistableRecord") +public typealias Persistable = PersistableRecord From dbde432948508cf303e1725453f4cad16b8ab66c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Feb 2018 08:35:07 +0100 Subject: [PATCH 025/348] Remove deprecated APIs --- CHANGELOG.md | 23 +- GRDB.xcodeproj/project.pbxproj | 14 - GRDB/Core/Database+Schema.swift | 8 - GRDB/Core/Statement.swift | 10 +- GRDB/Core/TransactionObserver.swift | 6 - GRDB/Legacy/Fixits-3.0.swift | 40 +++ GRDB/Record/Record.swift | 13 - GRDB/Record/RecordBox.swift | 101 ------ GRDBCipher.xcodeproj/project.pbxproj | 16 - GRDBCustom.xcodeproj/project.pbxproj | 12 - Tests/GRDBTests/RecordBoxTests.swift | 483 --------------------------- 11 files changed, 63 insertions(+), 663 deletions(-) delete mode 100644 GRDB/Record/RecordBox.swift delete mode 100644 Tests/GRDBTests/RecordBoxTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 00d5be4d3..5e6989370 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ Release Notes ### Breaking Changes - The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord`. -- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([311](https://github.com/groue/GRDB.swift/pull/311)) +- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([311](https://github.com/groue/GRDB.swift/pull/311)). - The `IteratorCursor` type has been removed. Use `AnyCursor` instead. +- Deprecated APIs have been removed. ### API diff @@ -132,6 +133,26 @@ Release Notes -final class IteratorCursor : Cursor { } ``` +**Removed Deprecated APIs** + +```diff + final class Database { +- func columnCount(in tableName: String) throws -> Int + } + final class SelectStatement : Statement { +- typealias SelectionInfo = DatabaseRegion +- var selectionInfo: DatabaseRegion + } + enum DatabaseEventKind { +- func impacts(_ region: DatabaseRegion) -> Bool + } + open class Record: FetchableRecord, TableRecord, PersistableRecord { +- var hasPersistentChangedValues: Bool +- var persistentChangedValues: [String: DatabaseValue?] + } +-final class RecordBox: Record { } +``` + ## 2.9.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 1d9908b7a..3735d08d1 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -290,9 +290,6 @@ 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */; }; 5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; 5674A72D1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */; }; - 567517C820131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; - 567517C920131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; - 567517CA20131B220094BF41 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567517C720131B220094BF41 /* RecordBox.swift */; }; 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; }; 567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; 567DAF1F1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; }; @@ -301,8 +298,6 @@ 567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 56805210201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; }; - 56805211201320E600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520F201320E600E87861 /* RecordBoxTests.swift */; }; 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568735A21CEDE16C009B9116 /* Betty.jpeg in Resources */ = {isa = PBXBuildFile; fileRef = 5687359E1CEDE16C009B9116 /* Betty.jpeg */; }; @@ -856,12 +851,10 @@ 5674A70B1F3087700095F066 /* DatabaseValueConvertibleEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEncodableTests.swift; sourceTree = ""; }; 5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = ""; }; 5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FetchableRecordDecodableTests.swift; sourceTree = ""; }; - 567517C720131B220094BF41 /* RecordBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = ""; }; 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 5680520F201320E600E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -1496,7 +1489,6 @@ 564E73DE203D50B9000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 5680520F201320E600E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; @@ -1555,7 +1547,6 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 567517C720131B220094BF41 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; @@ -2234,7 +2225,6 @@ 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, - 567517CA20131B220094BF41 /* RecordBox.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 565490C61D5AE236005622CB /* Statement.swift in Sources */, 56CEB5071EAA2F4D00BFAF62 /* FTS4.swift in Sources */, @@ -2330,7 +2320,6 @@ 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, - 567517C920131B220094BF41 /* RecordBox.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, @@ -2399,7 +2388,6 @@ 564448871EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56A238461B9C74A90082EB20 /* RowFromDictionaryTests.swift in Sources */, 569C1EB51CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, - 56805211201320E600E87861 /* RecordBoxTests.swift in Sources */, 562EA82A1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */, 56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2546,7 +2534,6 @@ 564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56D496811D813131008276D7 /* TransactionObserverSavepointsTests.swift in Sources */, 56D496AB1D8132CA008276D7 /* DatabasePoolFunctionTests.swift in Sources */, - 56805210201320E600E87861 /* RecordBoxTests.swift in Sources */, 562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */, 562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, @@ -2766,7 +2753,6 @@ 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, - 567517C820131B220094BF41 /* RecordBox.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index af1a5f6e4..e0da07cc1 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -129,14 +129,6 @@ extension Database { return primaryKey } - /// The number of columns in the table named `tableName`. - /// - /// - throws: A DatabaseError if table does not exist. - @available(*, deprecated, message: "Use db.columns(in: tableName).count instead") - public func columnCount(in tableName: String) throws -> Int { - return try columns(in: tableName).count - } - /// The indexes on table named `tableName`; returns the empty array if the /// table does not exist. /// diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index dbbcf86e8..38873941d 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -291,15 +291,7 @@ extension AuthorizedStatement { /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// } -public final class SelectStatement : Statement { - /// :nodoc: - @available(*, deprecated, renamed:"DatabaseRegion") - public typealias SelectionInfo = DatabaseRegion - - /// :nodoc: - @available(*, deprecated, renamed:"fetchedRegion") - public var selectionInfo: DatabaseRegion { return fetchedRegion } - +public final class SelectStatement : Statement { /// The database region that the statement looks into. public private(set) var fetchedRegion: DatabaseRegion diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index 00df65ec3..f27921111 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -874,12 +874,6 @@ public enum DatabaseEventKind { return DatabaseRegion(table: tableName, columns: updatedColumnNames) } } - - /// :nodoc: - @available(*, deprecated, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead") - public func impacts(_ region: DatabaseRegion) -> Bool { - return region.isModified(byEventsOfKind: self) - } } extension DatabaseEventKind { diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index b27bc9362..b8b822a7a 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -1,14 +1,54 @@ +/// :nodoc: @available(*, unavailable, renamed:"FetchRequest") public typealias Request = FetchRequest +/// :nodoc: @available(*, unavailable, renamed:"FetchableRecord") public typealias RowConvertible = FetchableRecord +/// :nodoc: @available(*, unavailable, renamed:"TableRecord") public typealias TableMapping = TableRecord +/// :nodoc: @available(*, unavailable, renamed:"MutablePersistableRecord") public typealias MutablePersistable = MutablePersistableRecord +/// :nodoc: @available(*, unavailable, renamed:"PersistableRecord") public typealias Persistable = PersistableRecord + +extension Database { + /// :nodoc: + @available(*, unavailable, message: "Use db.columns(in: tableName).count instead") + public func columnCount(in tableName: String) throws -> Int { preconditionFailure() } +} + +extension SelectStatement { + /// :nodoc: + @available(*, unavailable, renamed:"DatabaseRegion") + public typealias SelectionInfo = DatabaseRegion + + /// :nodoc: + @available(*, unavailable, renamed:"fetchedRegion") + public var selectionInfo: DatabaseRegion { preconditionFailure() } +} + +extension DatabaseEventKind { + /// :nodoc: + @available(*, unavailable, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead") + public func impacts(_ region: DatabaseRegion) -> Bool { preconditionFailure() } +} + +extension Record { + /// :nodoc: + @available(*, unavailable, renamed: "hasDatabaseChanges") + public var hasPersistentChangedValues: Bool { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, renamed: "databaseChanges") + public var persistentChangedValues: [String: DatabaseValue?] { preconditionFailure() } +} + +@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") +public final class RecordBox: Record { } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index a526703f3..317fbb316 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -186,13 +186,6 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { set { referenceRow = newValue ? nil : Row(self) } } - /// Deprecated alias for `hasDatabaseChanges`. - @available(*, deprecated, renamed: "hasDatabaseChanges") - public var hasPersistentChangedValues: Bool { - get { return hasDatabaseChanges } - set { hasDatabaseChanges = newValue } - } - /// A dictionary of changes that have not been saved. /// /// Its keys are column names, and values the old values that have been @@ -206,12 +199,6 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { return Dictionary(uniqueKeysWithValues: databaseChangesIterator()) } - /// Deprecated alias for `databaseChanges`. - @available(*, deprecated, renamed: "databaseChanges") - public var persistentChangedValues: [String: DatabaseValue?] { - return databaseChanges - } - // A change iterator that is used by both hasDatabaseChanges and // persistentChangedValues properties. private func databaseChangesIterator() -> AnyIterator<(String, DatabaseValue?)> { diff --git a/GRDB/Record/RecordBox.swift b/GRDB/Record/RecordBox.swift deleted file mode 100644 index 523c00544..000000000 --- a/GRDB/Record/RecordBox.swift +++ /dev/null @@ -1,101 +0,0 @@ -/// RecordBox is a subclass of Record that aims at giving any record type the -/// changes tracking provided by the Record class. -/// -/// // A Regular record struct -/// struct Player: FetchableRecord, MutablePersistableRecord, Codable { -/// static let databaseTableName = "players" -/// var id: Int64? -/// var name: String -/// var score: Int -/// mutating func didInsert(with rowID: Int64, for column: String?) { -/// id = rowID -/// } -/// } -/// -/// try dbQueue.inDatabase { db in -/// // Fetch a player record -/// let playerRecord = try RecordBox.fetchOne(db, key: 1)! -/// -/// // Profit from changes tracking -/// playerRecord.value.score = 300 -/// playerRecord.hasPersistentChangedValues // true -/// playerRecord.persistentChangedValues["score"] // 100 (the old value) -/// } -@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") -public final class RecordBox: Record { - /// The boxed record - public var value: T - - /// Creates a RecordBox that wraps the given record - public init(value: T) { - self.value = value - super.init() - } - - // MARK: - FetchableRecord - - /// Initializes a record from `row`. - public required init(row: Row) { - self.value = T(row: row) - super.init(row: row) - } - - // MARK: - TableRecord - - /// :nodoc: - override public class var databaseTableName: String { - return T.databaseTableName - } - - /// :nodoc: - override public class var databaseSelection: [SQLSelectable] { - return T.databaseSelection - } - - // MARK: - MutablePersistableRecord - - /// :nodoc: - override public class var persistenceConflictPolicy: PersistenceConflictPolicy { - return T.persistenceConflictPolicy - } - - /// :nodoc: - override public func encode(to container: inout PersistenceContainer) { - value.encode(to: &container) - } - - /// :nodoc: - override public func didInsert(with rowID: Int64, for column: String?) { - value.didInsert(with: rowID, for: column) - } - - /// :nodoc: - override public func insert(_ db: Database) throws { - try value.insert(db) - hasPersistentChangedValues = false - } - - /// :nodoc: - override public func update(_ db: Database, columns: Set) throws { - try value.update(db, columns: columns) - hasPersistentChangedValues = false - } - - /// :nodoc: - @discardableResult - override public func delete(_ db: Database) throws -> Bool { - defer { - // Future calls to update() will throw NotFound. Make the user - // a favor and make sure this error is thrown even if she checks the - // hasPersistentChangedValues flag: - hasPersistentChangedValues = true - } - return try value.delete(db) - } - - /// :nodoc: - public func exists(_ db: Database) throws -> Bool { - return try value.exists(db) - } -} - diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index bd66efde7..9e732ebec 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -394,12 +394,6 @@ 567F45AA1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AD1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AE1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 5680520C2013209300E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; }; - 5680520D2013209900E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680520A2013209300E87861 /* RecordBox.swift */; }; - 5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 568052202013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; - 568052212013297000E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5680521C2013296800E87861 /* RecordBoxTests.swift */; }; 568068321EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068331EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068361EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; @@ -937,8 +931,6 @@ 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 5680520A2013209300E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; - 5680521C2013296800E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -1533,7 +1525,6 @@ 564E73EB203DA29B000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 5680521C2013296800E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; @@ -1592,7 +1583,6 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 5680520A2013209300E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; @@ -2070,7 +2060,6 @@ 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, - 5680520C2013209300E87861 /* RecordBox.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2097,7 +2086,6 @@ 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 560FC5B21CB031E30014AA8E /* StatementColumnConvertibleFetchTests.swift in Sources */, 561667021D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, - 5680521E2013296F00E87861 /* RecordBoxTests.swift in Sources */, 562EA8271F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 560FC5651CB00B880014AA8E /* RecordPrimaryKeyNoneTests.swift in Sources */, @@ -2244,7 +2232,6 @@ 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 567156241CB16729007DC145 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 567156251CB16729007DC145 /* RowFromDictionaryTests.swift in Sources */, - 5680521F2013296F00E87861 /* RecordBoxTests.swift in Sources */, 562EA8281F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 565F03C41CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, 567156261CB16729007DC145 /* SelectStatementTests.swift in Sources */, @@ -2464,7 +2451,6 @@ 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, - 5680520D2013209900E87861 /* RecordBox.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2491,7 +2477,6 @@ 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56AFCA341CB1AA9900F48B96 /* RowFromDictionaryTests.swift in Sources */, 569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, - 568052202013297000E87861 /* RecordBoxTests.swift in Sources */, 562EA82B1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56DAA2D71DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 5698AC4E1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, @@ -2638,7 +2623,6 @@ 564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 56AFCA8D1CB1ABC800F48B96 /* RowFromDictionaryTests.swift in Sources */, 5657AB541D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, - 568052212013297000E87861 /* RecordBoxTests.swift in Sources */, 562EA82C1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56DAA2D81DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 5698AC4F1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 15f7843c5..92a5115ac 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -139,10 +139,6 @@ 567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; }; 567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; 567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; }; - 568052092013207000E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; }; - 5680520E201320A200E87861 /* RecordBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052072013206F00E87861 /* RecordBox.swift */; }; - 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; }; - 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568052182013295100E87861 /* RecordBoxTests.swift */; }; 568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; }; 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */; }; @@ -637,8 +633,6 @@ 567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = ""; }; 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = ""; }; 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = ""; }; - 568052072013206F00E87861 /* RecordBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBox.swift; sourceTree = ""; }; - 568052182013295100E87861 /* RecordBoxTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordBoxTests.swift; sourceTree = ""; }; 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = ""; }; 5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = ""; }; 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Fixits-1.2.swift"; sourceTree = ""; }; @@ -1207,7 +1201,6 @@ 564E73E7203DA278000C443C /* JoinSupportTests.swift */, 560B3FA41C19DFF800C58EC7 /* PersistableRecord */, 56176C9E1EACEDF9000F3F2B /* Record */, - 568052182013295100E87861 /* RecordBoxTests.swift */, 56176C9C1EACEA8C000F3F2B /* TableRecord */, ); name = Record; @@ -1266,7 +1259,6 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */, 5674A6F31F307F600095F066 /* PersistableRecord+Encodable.swift */, 56A238A11B9C753B0082EB20 /* Record.swift */, - 568052072013206F00E87861 /* RecordBox.swift */, 560D92461C672C4B00F4F92B /* TableRecord.swift */, ); path = Record; @@ -1773,7 +1765,6 @@ F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, - 5680520E201320A200E87861 /* RecordBox.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -1799,7 +1790,6 @@ 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, F3BA80BE1CFB2FD1003DC1BA /* DatabasePoolReadOnlyTests.swift in Sources */, - 5680521B2013295700E87861 /* RecordBoxTests.swift in Sources */, 562EA82D1F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, F3BA80C61CFB2FD8003DC1BA /* DatabaseQueueConcurrencyTests.swift in Sources */, F3BA81161CFB305E003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, @@ -2020,7 +2010,6 @@ F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, - 568052092013207000E87861 /* RecordBox.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2047,7 +2036,6 @@ 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, 5698ACCB1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, - 5680521A2013295600E87861 /* RecordBoxTests.swift in Sources */, 562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */, 56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B021CC1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, diff --git a/Tests/GRDBTests/RecordBoxTests.swift b/Tests/GRDBTests/RecordBoxTests.swift deleted file mode 100644 index 8872ca6f3..000000000 --- a/Tests/GRDBTests/RecordBoxTests.swift +++ /dev/null @@ -1,483 +0,0 @@ -import XCTest -#if GRDBCIPHER - import GRDBCipher - typealias RecordBox = GRDBCipher.RecordBox // Single deprecation warning -#elseif GRDBCUSTOMSQLITE - import GRDBCustomSQLite - typealias RecordBox = GRDBCustomSQLite.RecordBox // Single deprecation warning -#else - import GRDB - typealias RecordBox = GRDB.RecordBox // Single deprecation warning -#endif - -private struct Player: FetchableRecord, MutablePersistableRecord, Codable { - static let databaseTableName = "players" - - var id: Int64? - var name: String? - var score: Int? - var creationDate: Date? - - init(id: Int64? = nil, name: String? = nil, score: Int? = nil, creationDate: Date? = nil) { - self.id = id - self.name = name - self.score = score - self.creationDate = creationDate - } - - mutating func insert(_ db: Database) throws { - if creationDate == nil { - creationDate = Date() - } - try performInsert(db) - } - - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } -} - -class RecordBoxTests: GRDBTestCase { - override func setup(_ dbWriter: DatabaseWriter) throws { - try dbWriter.write { db in - try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() - t.column("name", .text) - t.column("score", .integer) - t.column("creationDate", .datetime) - } - } - } - - func testRecordIsEditedAfterInit() { - // Create a Record. No fetch has happen, so we don't know if it is - // identical to its eventual row in the database. So it is edited. - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - XCTAssertTrue(player.hasDatabaseChanges) - } - - func testRecordIsEditedAfterInitFromRow() { - // Create a Record from a row. The row may not come from the database. - // So it is edited. - let row = Row(["name": "Arthur", "score": 41]) - let player = RecordBox(row: row) - XCTAssertTrue(player.hasDatabaseChanges) - } - - func testRecordIsNotEditedAfterFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container: An update statement, which only saves the - // columns in persistence container would perform no change. So the - // record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT * FROM players")! - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterWiderThanFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container, plus extra ones: An update statement, - // which only saves the columns in persistence container would - // perform no change. So the record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT *, 1 AS foo FROM players")! - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterPartialFetch() throws { - // Fetch a record from a row that does not contain all the columns in - // persistence container: An update statement saves the columns in - // persistence container, so it may perform unpredictable change. - // So the record is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT name FROM players")! - XCTAssertTrue(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterInsert() throws { - // After insertion, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterValueChange() throws { - // Any change in a value exposed in persistence container yields a - // record that is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = "Bobby" // non-nil vs. non-nil - XCTAssertTrue(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = nil // non-nil vs. nil - XCTAssertTrue(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.score == nil) - player.value.score = 41 // nil vs. non-nil - XCTAssertTrue(player.hasDatabaseChanges) - } - } - } - - func testRecordIsNotEditedAfterSameValueChange() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.name != nil) - player.value.name = "Arthur" // non-nil vs. non-nil - XCTAssertFalse(player.hasDatabaseChanges) - } - do { - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - XCTAssertTrue(player.value.score == nil) - player.value.score = nil // nil vs. nil - XCTAssertFalse(player.hasDatabaseChanges) - } - } - } - - func testRecordIsNotEditedAfterUpdate() throws { - // After update, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.name = "Bobby" - try player.update(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsNotEditedAfterSave() throws { - // After save, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.save(db) - XCTAssertFalse(player.hasDatabaseChanges) - player.value.name = "Bobby" - XCTAssertTrue(player.hasDatabaseChanges) - try player.save(db) - XCTAssertFalse(player.hasDatabaseChanges) - } - } - - func testRecordIsEditedAfterPrimaryKeyChange() throws { - // After reload, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.id = player.value.id! + 1 - XCTAssertTrue(player.hasDatabaseChanges) - } - } - - func testCopyTransfersEditedFlag() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - try player.insert(db) - XCTAssertFalse(player.hasDatabaseChanges) - XCTAssertFalse(player.copy().hasDatabaseChanges) - - player.value.name = "Barbara" - XCTAssertTrue(player.hasDatabaseChanges) - XCTAssertTrue(player.copy().hasDatabaseChanges) - - player.hasDatabaseChanges = false - XCTAssertFalse(player.hasDatabaseChanges) - XCTAssertFalse(player.copy().hasDatabaseChanges) - - player.hasDatabaseChanges = true - XCTAssertTrue(player.hasDatabaseChanges) - XCTAssertTrue(player.copy().hasDatabaseChanges) - } - } - - func testChangesAfterInit() { - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 4) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "name": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - - func testChangesAfterInitFromRow() { - let player = RecordBox(row: Row(["name": "Arthur", "score": 41])) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 4) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "name": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - - func testChangesAfterFullFetch() throws { - // Fetch a record from a row that contains all the columns in - // persistence container: An update statement, which only saves the - // columns in persistence container would perform no change. So the - // record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - do { - let player = try RecordBox.fetchOne(db, "SELECT * FROM players")! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let players = try RecordBox.fetchAll(db, "SELECT * FROM players") - let changes = players[0].databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let players = try RecordBox.fetchCursor(db, "SELECT * FROM players") - let changes = try players.next()!.databaseChanges - XCTAssertEqual(changes.count, 0) - } - do { - let player = try RecordBox.fetchOne(db, "SELECT * FROM players", adapter: SuffixRowAdapter(fromIndex: 0))! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - } - } - - func testChangesAfterPartialFetch() throws { - // Fetch a record from a row that does not contain all the columns in - // persistence container: An update statement saves the columns in - // persistence container, so it may perform unpredictable change. - // So the record is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try RecordBox(value: Player(name: "Arthur", score: 41)).insert(db) - let player = try RecordBox.fetchOne(db, "SELECT name FROM players")! - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 3) - for (column, old) in changes { - switch column { - case "id": - XCTAssertTrue(old == nil) - case "score": - XCTAssertTrue(old == nil) - case "creationDate": - XCTAssertTrue(old == nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testChangesAfterInsert() throws { - // After insertion, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 0) - } - } - - func testChangesAfterValueChange() throws { - // Any change in a value exposed in persistence container yields a - // record that is edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur")) - try player.insert(db) - - player.value.name = "Bobby" // non-nil -> non-nil - player.value.score = 41 // nil -> non-nil - player.value.creationDate = nil // non-nil -> nil - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 3) - for (column, old) in changes { - switch column { - case "name": - XCTAssertEqual(old, "Arthur".databaseValue) - case "score": - XCTAssertEqual(old, DatabaseValue.null) - case "creationDate": - XCTAssertTrue(Date.fromDatabaseValue(old!) != nil) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testChangesAfterUpdate() throws { - // After update, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.name = "Bobby" - try player.update(db) - XCTAssertEqual(player.databaseChanges.count, 0) - } - } - - func testChangesAfterSave() throws { - // After save, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.save(db) - XCTAssertEqual(player.databaseChanges.count, 0) - - player.value.name = "Bobby" - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 1) - for (column, old) in changes { - switch column { - case "name": - XCTAssertEqual(old, "Arthur".databaseValue) - default: - XCTFail("Unexpected column: \(column)") - } - } - try player.save(db) - XCTAssertEqual(player.databaseChanges.count, 0) - } - } - - func testChangesAfterPrimaryKeyChange() throws { - // After reload, a record is not edited. - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - try player.insert(db) - player.value.id = player.value.id! + 1 - let changes = player.databaseChanges - XCTAssertEqual(changes.count, 1) - for (column, old) in changes { - switch column { - case "id": - XCTAssertEqual(old, (player.value.id! - 1).databaseValue) - default: - XCTFail("Unexpected column: \(column)") - } - } - } - } - - func testCopyTransfersChanges() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - try player.insert(db) - XCTAssertEqual(player.databaseChanges.count, 0) - XCTAssertEqual(player.copy().databaseChanges.count, 0) - - player.value.name = "Barbara" - XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count) - - player.hasDatabaseChanges = false - XCTAssertEqual(player.databaseChanges.count, 0) - XCTAssertEqual(player.copy().databaseChanges.count, 0) - - player.hasDatabaseChanges = true - XCTAssertTrue(player.databaseChanges.count > 0) // TODO: compare actual changes - XCTAssertEqual(player.databaseChanges.count, player.copy().databaseChanges.count) - } - } - - func testUpdateChanges() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - let player = RecordBox(value: Player(name: "Arthur", score: 41)) - - do { - XCTAssertTrue(player.hasDatabaseChanges) - try player.updateChanges(db) - XCTFail("Expected PersistenceError") - } catch is PersistenceError { } - - try player.insert(db) - - // Nothing to update - let initialChangesCount = db.totalChangesCount - XCTAssertFalse(player.hasDatabaseChanges) - try XCTAssertFalse(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount) - - // Nothing to update - player.value.score = 41 - XCTAssertFalse(player.hasDatabaseChanges) - try XCTAssertFalse(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount) - - // Update single column - player.value.score = 42 - XCTAssertEqual(Set(player.databaseChanges.keys), ["score"]) - try XCTAssertTrue(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount + 1) - XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"score\"=42 WHERE \"id\"=1") - - // Update two columns - player.value.name = "Barbara" - player.value.score = 43 - XCTAssertEqual(Set(player.databaseChanges.keys), ["score", "name"]) - try XCTAssertTrue(player.updateChanges(db)) - XCTAssertEqual(db.totalChangesCount, initialChangesCount + 2) - let fetchedPlayer = try RecordBox.fetchOne(db, key: player.value.id)! - XCTAssertEqual(fetchedPlayer.value.name, player.value.name) - XCTAssertEqual(fetchedPlayer.value.score, player.value.score) - } - } -} From ce984783ec190f3ab845b8a04a205022bf8a7351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Feb 2018 08:36:58 +0100 Subject: [PATCH 026/348] Intra-doc links --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d056e7b3a..63870ab66 100644 --- a/README.md +++ b/README.md @@ -2813,8 +2813,8 @@ This is the list of record methods, along with their required protocols. The [Re | `record.save(db)` | [PersistableRecord] | | | `record.update(db)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | -| `record.updateChanges(db, from:...)` | [PersistableRecord] | | -| `record.updateChanges(db)` | [Record](#record-class) | | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#changes-tracking) | +| `record.updateChanges(db)` | [Record](#record-class) | [*](#changes-tracking) | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | | `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | From 8cff147029ff9a24b2ecda3032559724e7b69fc0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Feb 2018 08:41:46 +0100 Subject: [PATCH 027/348] TODO.md --- TODO.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/TODO.md b/TODO.md index c1c598c8b..4f3fb051e 100644 --- a/TODO.md +++ b/TODO.md @@ -21,7 +21,6 @@ GRDB 3.0 - [ ] Rename "changes tracking" (ambiguous with database observation) to "record comparison" - [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. Remove QueryInterfaceExtensibilityTests.swift -- [ ] Hide useless scheduling methods behind protocols : https://forums.swift.org/t/discouraging-protocol-methods-on-concrete-values/8737/4?u=gwendal.roue - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. @@ -30,7 +29,6 @@ GRDB 3.0 - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename RowConvertible, TableRecord, MutableEncodableRecord and EncodableRecord so that their names contain Record: FetchableRecord, TableRecord, MutableEncodableRecordRecord, EncodableRecordRecord? - [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutableEncodableRecordRecord. This would allow keeping fetching and persistence methods private in some files. - [X] Drop IteratorCursor, use AnyCursor instead - [X] Rename TypedRequest to FetchRequest, drop Request From 3bbc17fe4ae44773da61b17bdbd6d7c71031a48e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Feb 2018 08:58:27 +0100 Subject: [PATCH 028/348] Rename "record changes tracking" to "record comparison" in order to avoid confusion with database changes tracking performed by database observation --- Documentation/WhyAdoptGRDB.md | 2 +- GRDB/Record/PersistableRecord.swift | 2 +- GRDB/Record/Record.swift | 2 +- .../Contents.swift | 2 +- README.md | 29 +++++++++++-------- TODO.md | 2 +- Tests/generatePerformanceReport.rb | 2 +- 7 files changed, 23 insertions(+), 18 deletions(-) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index db582af51..8aef278a5 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -37,7 +37,7 @@ GRDB puts all bets on SQLite, and focuses on front-end GUI applications. This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB is not an alternative to IBM's [Swift-Kuery], Vapor's [Fluent], or Perfect's [StORM]. -Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, changes tracking, database observation, multi-threading safety, table view animations, support for reactive streams... +Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams... Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index f3bcdfd6d..067d65a14 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -437,7 +437,7 @@ extension MutablePersistableRecord { return try performExists(db) } - // MARK: - Changes Tracking + // MARK: - Record Comparison /// Returns a boolean indicating whether this record and the other record /// have the same database representation. diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 317fbb316..ddad9f547 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -163,7 +163,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { } - // MARK: - Changes Tracking + // MARK: - Compare with Previous Versions /// A boolean that indicates whether the record has changes that have not /// been saved. diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index fb3b7eef2..039c1ad3a 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -31,7 +31,7 @@ try dbQueue.inDatabase { db in // Define the Player subclass of GRDB's Record. // -// Record provides change tracking that helps avoiding useless UPDATE statements. +// Record can compare against itself, and that helps avoiding useless UPDATE statements. class Player : Record { var id: Int64 var name: String diff --git a/README.md b/README.md index 63870ab66..f8cb505e9 100644 --- a/README.md +++ b/README.md @@ -1842,7 +1842,7 @@ try dbQueue.inDatabase { db in Of course, you need to open a [database connection](#database-connections), and [create a database table](#database-schema) first. -Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and changes tracking. See the [list of record methods](#list-of-record-methods) for an overview. +Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and record comparison. See the [list of record methods](#list-of-record-methods) for an overview. > :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, and do not auto-update. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. @@ -1864,7 +1864,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Customizing the Persistence Methods](#customizing-the-persistence-methods) - [Codable Records](#codable-records) - [Record Class](#record-class) -- [Changes Tracking](#changes-tracking) +- [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) - [List of Record Methods](#list-of-record-methods) @@ -1914,7 +1914,7 @@ player.name = "Arthur" try player.update(db) ``` -Records can [track their changes](#changes-tracking), so that you can avoid useless updates: +Records can [avoid useless updates](#record-comparison): ```swift let player = try Player.fetchOne(db, key: 1)! @@ -1972,7 +1972,7 @@ Details follow: - [PersistableRecord Protocol](#persistablerecord-protocol) - [Codable Records](#codable-records) - [Record Class](#record-class) -- [Changes Tracking](#changes-tracking) +- [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) - [List of Record Methods](#list-of-record-methods) @@ -2479,7 +2479,7 @@ place.id // A unique id ## Record Class -**Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can [track their changes](#changes-tracking). +**Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can compare against previous versions of themselves in order to [avoid useless updates](#record-comparison). Record subclasses define their custom database relationship by overriding database methods: @@ -2520,11 +2520,11 @@ class Place : Record { ``` -## Changes Tracking +## Record Comparison -**Changes tracking is the ability, for a record, to compare against another record, or against previous versions of itself.** +**Records can compare against other records, or against previous versions of themselves.** -The `update()` [method](#persistence-methods) always executes an UPDATE statement. When the record has not been edited, this costly database access is generally useless. +This helps avoiding costly UPDATE statements when a record has not been edited. You can use instead the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): @@ -2813,8 +2813,8 @@ This is the list of record methods, along with their required protocols. The [Re | `record.save(db)` | [PersistableRecord] | | | `record.update(db)` | [PersistableRecord] | | | `record.update(db, columns:...)` | [PersistableRecord] | | -| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#changes-tracking) | -| `record.updateChanges(db)` | [Record](#record-class) | [*](#changes-tracking) | +| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | +| `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | | **Delete Records** | | | | `record.delete(db)` | [PersistableRecord] | | | `Type.deleteOne(db, key:...)` | [PersistableRecord] | ¹ | @@ -2846,7 +2846,7 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.fetchOne(db, sql)` | [FetchableRecord] | ³ | | `Type.fetchOne(statement)` | [FetchableRecord] | ⁴ | | `Type.filter(...).fetchOne(db)` | [FetchableRecord] & [TableRecord] | ² | -| **[Changes Tracking](#changes-tracking)** | | | +| **[Record Comparison]** | | | | `record.databaseEqual(...)` | [PersistableRecord] | | | `record.databaseChanges(from:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | | @@ -6631,7 +6631,7 @@ if player.hasDatabaseChanges { } ``` -See [changes tracking](#changes-tracking) for more information. +See [Record Comparison] for more information. ### Performance tip: learn about SQL strengths and weaknesses @@ -6916,6 +6916,10 @@ Sample Code Legacy ====== +#### Changes Tracking + +This chapter has been renamed [Record Comparison]. + #### Persistable Protocol This protocol has been renamed [PersistableRecord] in GRDB 3.0. @@ -6930,4 +6934,5 @@ This protocol has been renamed [TableRecord] in GRDB 3.0. [FetchableRecord]: #fetchablerecord-protocol [PersistableRecord]: #persistablerecord-protocol +[Record Comparison]: #record-comparison [TableRecord]: #tablerecord-protocol diff --git a/TODO.md b/TODO.md index 4f3fb051e..8283d1390 100644 --- a/TODO.md +++ b/TODO.md @@ -19,7 +19,7 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 -- [ ] Rename "changes tracking" (ambiguous with database observation) to "record comparison" +- [X] Rename "changes tracking" (ambiguous with database observation) to "record comparison" - [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. Remove QueryInterfaceExtensibilityTests.swift - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index 7757a0a38..ac5bc49eb 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -48,7 +48,7 @@ All tests use the default settings of each library. For each library, we: - Build and consume database rows with raw SQL and column indexes (aiming at the best performance) - Build and consume database rows with column names (sacrificing performance for maintainability) - Build and consume records values to and from database rows (aiming at the shortest code from database to records) -- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#changes-tracking) (records know if they have unsaved changes) +- Build and consume records values to and from database rows, with [change tracking](https://github.com/groue/GRDB.swift/blob/master/README.md#record-comparison) (records know if they have unsaved changes) As a bottom line, the raw SQLite C API is used as efficiently as possible, without any error checking. From 3a625157ffb8e62552faafb1fd8ba9d35929e6bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 28 Feb 2018 09:02:48 +0100 Subject: [PATCH 029/348] README typos --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f8cb505e9..99ba1e9ea 100644 --- a/README.md +++ b/README.md @@ -2526,7 +2526,7 @@ class Place : Record { This helps avoiding costly UPDATE statements when a record has not been edited. -You can use instead the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): +You can use the `updateChanges` method, available on the [PersistableRecord] protocol, which performs an update of the changed columns only (and does nothing if record has no change): ```swift let oldPlayer = try Player.fetchOne(db, ...) @@ -4606,7 +4606,7 @@ This technique works pretty well, but it has three drawbacks: 1. The selection becomes hard to read and understand. 2. Such queries are difficult to write by hand. -3. The mangled names are a *very* bad fit for [FetchableRecord] records that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. +3. The mangled names are a *very* bad fit for [FetchableRecord] types that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. We thus need another technique. **Below we'll see how to split rows into slices, and preserve column names.** From 4a4f4e37bafb737abadabada8a08f5138f467479 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 2 Mar 2018 15:13:12 +0100 Subject: [PATCH 030/348] Improve Record overview --- README.md | 80 ++++++++++++++----------------------------------------- 1 file changed, 20 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 99ba1e9ea..b8d821d63 100644 --- a/README.md +++ b/README.md @@ -1914,14 +1914,12 @@ player.name = "Arthur" try player.update(db) ``` -Records can [avoid useless updates](#record-comparison): +It is possible to [avoid useless updates](#record-comparison): ```swift let player = try Player.fetchOne(db, key: 1)! player.name = "Arthur" -if player.hasDatabaseChanges { - try player.update(db) -} +try player.updateChanges(db) ``` For batch updates, execute an [SQL query](#executing-updates): @@ -1948,7 +1946,7 @@ try Player.deleteOne(db, key: ["email": "arthur@example.com"]) try Country.deleteAll(db, keys: ["FR", "US"]) ``` -For batch deletes, see the [query interface](#the-query-interface): +For batch deletes, execute an [SQL query](#executing-updates), or see the [query interface](#the-query-interface): ```swift try Player.filter(emailColumn == nil).deleteAll(db) @@ -1982,27 +1980,16 @@ Details follow: **GRDB ships with three record protocols**. Your own types will adopt one or several of them, according to the abilities you want to extend your types with. -- [FetchableRecord] is able to **read**: it grants the ability to efficiently decode raw database row. +- [FetchableRecord] is able to **decode database rows**. - Imagine you want to load places from the `places` database table. - - One way to do it is to load raw database rows: + You can always decode rows yourself: ```swift - func fetchPlaceRows(_ db: Database) throws -> [Row] { - return try Row.fetchAll(db, "SELECT * FROM places") - } - ``` - - The problem is that [raw rows](#row-queries) are not easy to deal with, and you may prefer using a proper `Place` type: - - ```swift - // Dedicated model struct Place { ... } - func fetchPlaces(_ db: Database) throws -> [Place] { + try dbQueue.inDatabase { db in let rows = try Row.fetchAll(db, "SELECT * FROM places") - return rows.map { row in - Place( + let places: [Place] = rows.map { row in + return Place( id: row["id"], title: row["title"], coordinate: CLLocationCoordinate2D( @@ -2013,50 +2000,21 @@ Details follow: } ``` - This code is verbose, and so you define an `init(row:)` initializer: + But FetchableRecord lets you write code that is much more readable, and much more efficient as well, both in terms of performance and memory usage: ```swift - // Row initializer - struct Place { - init(row: Row) { - id = row["id"] - ... - } - } - func fetchPlaces(_ db: Database) throws -> [Place] { - let rows = try Row.fetchAll(db, "SELECT * FROM places") - return rows.map { Place(row: $0) } + struct Place: FetchableRecord { ... } + try dbQueue.inDatabase { db in + let places = try Place.fetchAll(db, "SELECT * FROM places") } ``` - Now you notice that this code may use a lot of memory when you have many rows: a full array of database rows is created in order to build an array of places. Furthermore, rows that have been copied from the database have lost the ability to directly load values from SQLite: that's inefficient. You thus use a [database cursor](#cursors), which is both lazy and efficient: + FetchableRecord is not able to build SQL requests for you, though. For that, you also need TableRecord: + +- [TableRecord] is able to **generate SQL queries**: ```swift - // Cursor for efficiency - func fetchPlaces(_ db: Database) throws -> [Place] { - let rowCursor = try Row.fetchCursor(db, "SELECT * FROM places") - let placeCursor = rowCursor.map { Place(row: $0) } - return try Array(placeCursor) - } - ``` - - That's better. And that's what FetchableRecord does, with a little performance bonus, and in a single line: - - ```swift - struct Place : FetchableRecord { - init(row: Row) { ... } - } - func fetchPlaces(_ db: Database) throws -> [Place] { - return try Place.fetchAll(db, "SELECT * FROM places") - } - ``` - - FetchableRecord is not able to build SQL requests, though. For that, you also need TableRecord: - -- [TableRecord] is able to **build requests without SQL**: - - ```swift - struct Place : TableRecord { ... } + struct Place: TableRecord { ... } // SELECT * FROM places ORDER BY title let request = Place.order(Column("title")) ``` @@ -2064,7 +2022,7 @@ Details follow: When a type adopts both TableRecord and FetchableRecord, it can load from those requests: ```swift - struct Place : TableRecord, FetchableRecord { ... } + struct Place: TableRecord, FetchableRecord { ... } try dbQueue.inDatabase { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) @@ -2080,7 +2038,9 @@ Details follow: try Place(...).insert(db) } ``` - + + A persistable record can also [compare](#record-comparison) itself against other records, and avoid useless database updates. + ## FetchableRecord Protocol From 1cd8467b8fa93d97b6c42e6db627508a75d71dd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Mar 2018 09:59:01 +0100 Subject: [PATCH 031/348] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 8283d1390..1c8c6e65b 100644 --- a/TODO.md +++ b/TODO.md @@ -34,6 +34,7 @@ GRDB 3.0 - [X] Rename TypedRequest to FetchRequest, drop Request - [ ] Rename columnCount -> numberOfColumns - [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? +- [ ] DatabaseMigrator exposes the name of its support table (useful for tests that check which application tables are present). Alternative: have GRDB tell if a database table name is reserved by GRDB. Not sure From f202ad5e3f555262ce6864a1f4a99feb5be6ed36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Mar 2018 10:18:44 +0100 Subject: [PATCH 032/348] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 1c8c6e65b..b068db81c 100644 --- a/TODO.md +++ b/TODO.md @@ -35,6 +35,7 @@ GRDB 3.0 - [ ] Rename columnCount -> numberOfColumns - [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? - [ ] DatabaseMigrator exposes the name of its support table (useful for tests that check which application tables are present). Alternative: have GRDB tell if a database table name is reserved by GRDB. +- [ ] Ask DatabaseMigrator if a migration has been applied (useful for tests that check if a legacy database resource should be tested or not) Not sure From 5defb058d34dee8800c3958767d047dcb9e064aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 5 Mar 2018 14:22:58 +0100 Subject: [PATCH 033/348] TODO --- TODO.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/TODO.md b/TODO.md index b068db81c..6f8477983 100644 --- a/TODO.md +++ b/TODO.md @@ -36,6 +36,10 @@ GRDB 3.0 - [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? - [ ] DatabaseMigrator exposes the name of its support table (useful for tests that check which application tables are present). Alternative: have GRDB tell if a database table name is reserved by GRDB. - [ ] Ask DatabaseMigrator if a migration has been applied (useful for tests that check if a legacy database resource should be tested or not) +- [ ] DatabaseMigrator.isInternalTable +- [ ] DatabaseMigrator.canMigrate(_:upTo:) +- [ ] Database.isSQLiteInternalTable +- [ ] HiddenColumnsAdapter Not sure From 95933e93dddff6c2bf81f076a4450bc1864fa395 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 12 Mar 2018 23:03:46 +0100 Subject: [PATCH 034/348] Fix SQLRequest inline documentation --- GRDB/Core/FetchRequest.swift | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 052bd312a..b10915c27 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -178,8 +178,12 @@ public struct SQLRequest : FetchRequest { /// Creates a new request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// For example: + /// + /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// try dbQueue.inDatabase { db in + /// let player = try request.fetchOne(db) // Player? + /// } /// /// - parameters: /// - sql: An SQL query. @@ -194,6 +198,17 @@ public struct SQLRequest : FetchRequest { /// Creates a new SQL request from any other fetch request. /// + /// For example: + /// + /// let request = Player.filter(Column("name") == "Arthur") + /// try dbQueue.inDatabase { db in + /// let sqlRequest = try SQLRequest(db, request: request) // SQLRequest + /// print(sqlRequest.sql) + /// // Prints "SELECT * FROM players WHERE name = ?" + /// print(sqlRequest.arguments) + /// // Prints ["Arthur"] + /// } + /// /// - parameters: /// - db: A database connection. /// - request: A request. @@ -208,14 +223,14 @@ public struct SQLRequest : FetchRequest { /// Creates a new SQL request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// The *cache* arguments should be `.internal` for requests generated by + /// GRDB, and `.public` for requests generated by the user. /// /// - parameters: /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter. - /// - statementCacheName: Optional statement cache name. + /// - cache: Optional statement cache name. /// - returns: A SQLRequest init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { self.sql = sql From 07b944039ce5b3a07a5cb3534289010c0937e7d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 19:52:44 +0100 Subject: [PATCH 035/348] Database.isSQLiteInternalTable(_:) --- GRDB/Core/Database+Schema.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index e0da07cc1..748bbb4fc 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -30,6 +30,19 @@ extension Database { return try Row.fetchOne(self, "SELECT 1 FROM (SELECT sql, type, name FROM sqlite_master UNION SELECT sql, type, name FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ?", arguments: [tableName.lowercased()]) != nil } + /// Returns whether a table is an internal SQLite table. + /// + /// For more information, see https://www.sqlite.org/fileformat2.html + public func isSQLiteInternalTable(_ tableName: String) -> Bool { + // https://www.sqlite.org/fileformat2.html#internal_schema_objects + // > The names of internal schema objects always begin with "sqlite_" + // > and any table, index, view, or trigger whose name begins with + // > "sqlite_" is an internal schema object. SQLite prohibits + // > applications from creating objects whose names begin with + // > "sqlite_". + return tableName.starts(with: "sqlite_") + } + /// Returns whether a view exists. public func viewExists(_ viewName: String) throws -> Bool { // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) From d61551cedb0936e26791b5c044e7d11841f15adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 19:57:03 +0100 Subject: [PATCH 036/348] Database.isSQLiteInternalTable(_:) doc --- CHANGELOG.md | 4 ++++ README.md | 1 + 2 files changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e6989370..0e28e766e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,10 @@ Release Notes ## Next Version +### New + +- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table. + ### Breaking Changes - The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord`. diff --git a/README.md b/README.md index b8d821d63..368828eea 100644 --- a/README.md +++ b/README.md @@ -1647,6 +1647,7 @@ try db.indexes(on: "players") // [IndexInfo], the indexes defined on the tab try db.foreignKeys(on: "players") // [ForeignKeyInfo], the foreign keys defined on the table try db.primaryKey("players") // PrimaryKeyInfo try db.table("players", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key +Database.isSQLiteInternalTable("players") // Bool, true if argument is the name of an internal to SQLite table ``` From 0d7f392bcde975262bdcb6a18cb25ddcdd0f5261 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:04:50 +0100 Subject: [PATCH 037/348] Database.isGRDBInternalTable(_:) --- CHANGELOG.md | 1 + GRDB/Core/Database+Schema.swift | 11 ++++++++++- README.md | 3 ++- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e28e766e..4ccbb6642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ Release Notes ### New - `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table. +- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table. ### Breaking Changes diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 748bbb4fc..4c053acb5 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -32,6 +32,8 @@ extension Database { /// Returns whether a table is an internal SQLite table. /// + /// Those are tables whose name begins with "sqlite_". + /// /// For more information, see https://www.sqlite.org/fileformat2.html public func isSQLiteInternalTable(_ tableName: String) -> Bool { // https://www.sqlite.org/fileformat2.html#internal_schema_objects @@ -42,7 +44,14 @@ extension Database { // > "sqlite_". return tableName.starts(with: "sqlite_") } - + + /// Returns whether a table is an internal GRDB table. + /// + /// Those are tables whose name begins with "grdb_". + public func isGRDBInternalTable(_ tableName: String) -> Bool { + return tableName.starts(with: "grdb_") + } + /// Returns whether a view exists. public func viewExists(_ viewName: String) throws -> Bool { // SQlite identifiers are case-insensitive, case-preserving (http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html) diff --git a/README.md b/README.md index 368828eea..cae0b6f3a 100644 --- a/README.md +++ b/README.md @@ -1647,7 +1647,8 @@ try db.indexes(on: "players") // [IndexInfo], the indexes defined on the tab try db.foreignKeys(on: "players") // [ForeignKeyInfo], the foreign keys defined on the table try db.primaryKey("players") // PrimaryKeyInfo try db.table("players", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key -Database.isSQLiteInternalTable("players") // Bool, true if argument is the name of an internal to SQLite table +Database.isSQLiteInternalTable(...) // Bool, true if argument is the name of an internal SQLite table +Database.isGRDBInternalTable(...) // Bool, true if argument is the name of an internal GRDB table ``` From fa8ed89eae9230e545a05ec7035e68e883960739 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:10:59 +0100 Subject: [PATCH 038/348] DatabaseMigrator.appliedMigrations(_:) --- GRDB/Migration/DatabaseMigrator.swift | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index b6de0e654..d378b900a 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -146,6 +146,11 @@ public struct DatabaseMigrator { } } + /// Returns the set of applied migration identifiers. + public func appliedMigrations(_ reader: DatabaseReader) throws -> Set { + return try reader.read { try appliedMigrations($0) } + } + // MARK: - Non public @@ -160,13 +165,13 @@ public struct DatabaseMigrator { try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") } - private func appliedIdentifiers(_ db: Database) throws -> Set { + private func appliedMigrations(_ db: Database) throws -> Set { return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations")) } private func runMigrations(_ db: Database) throws { - let appliedIdentifiers = try self.appliedIdentifiers(db) - for migration in migrations where !appliedIdentifiers.contains(migration.identifier) { + let appliedMigrations = try self.appliedMigrations(db) + for migration in migrations where !appliedMigrations.contains(migration.identifier) { try migration.run(db) } } @@ -184,13 +189,13 @@ public struct DatabaseMigrator { GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied - let appliedIdentifiers = try self.appliedIdentifiers(db) + let appliedMigrations = try self.appliedMigrations(db) if prefixMigrations.count < migrations.count { let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + GRDBPrecondition(!appliedMigrations.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } - for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { + for migration in prefixMigrations where !appliedMigrations.contains(migration.identifier) { try migration.run(db) } } From c7ad3ef4a93b194b1e14ed60e575b5669d051b90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:15:23 +0100 Subject: [PATCH 039/348] DatabaseMigrator.appliedMigrations(in:) doc & changelog --- CHANGELOG.md | 1 + GRDB/Migration/DatabaseMigrator.swift | 2 +- README.md | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ccbb6642..03c8fbd21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Release Notes - `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table. - `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table. +- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers. ### Breaking Changes diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index d378b900a..d9390a6b5 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -147,7 +147,7 @@ public struct DatabaseMigrator { } /// Returns the set of applied migration identifiers. - public func appliedMigrations(_ reader: DatabaseReader) throws -> Set { + public func appliedMigrations(in reader: DatabaseReader) throws -> Set { return try reader.read { try appliedMigrations($0) } } diff --git a/README.md b/README.md index cae0b6f3a..50f8a8a04 100644 --- a/README.md +++ b/README.md @@ -3854,6 +3854,15 @@ try migrator.migrate(dbQueue, upTo: "v1") // fatal error: database is already migrated beyond migration "v1" ``` +Check if a migration has been applied: + +```swift +let appliedMigrations = try migrator.appliedMigration(in: dbQueue) +if appliedMigrations.contains("v2") { + // "v2" has been applied +} +``` + ### Advanced Database Schema Changes From ebe1d93c3afa93b611a3153ed64cba461ceb292c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:22:39 +0100 Subject: [PATCH 040/348] Polish --- CHANGELOG.md | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 03c8fbd21..33c757cf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ Release Notes - `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table. - `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table. -- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers. +- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database. ### Breaking Changes diff --git a/README.md b/README.md index 50f8a8a04..448db7e93 100644 --- a/README.md +++ b/README.md @@ -3859,7 +3859,7 @@ Check if a migration has been applied: ```swift let appliedMigrations = try migrator.appliedMigration(in: dbQueue) if appliedMigrations.contains("v2") { - // "v2" has been applied + // "v2" migration has been applied } ``` From 930246592a8632faf8042ac6296287e5c4621f40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:32:04 +0100 Subject: [PATCH 041/348] Cleanup TODO --- TODO.md | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/TODO.md b/TODO.md index 6f8477983..c5655589b 100644 --- a/TODO.md +++ b/TODO.md @@ -19,8 +19,6 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 -- [X] Rename "changes tracking" (ambiguous with database observation) to "record comparison" -- [ ] Refactor SQL generation and rowId extraction from expression on the visitor pattern. Provide more documentation for literal expressions which become the only way to extend GRDB. Remove QueryInterfaceExtensibilityTests.swift - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. @@ -29,16 +27,8 @@ GRDB 3.0 - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Not sure: Consider introducing RowDecodable and RowEncodable on top of FetchableRecord and MutableEncodableRecordRecord. This would allow keeping fetching and persistence methods private in some files. -- [X] Drop IteratorCursor, use AnyCursor instead -- [X] Rename TypedRequest to FetchRequest, drop Request - [ ] Rename columnCount -> numberOfColumns - [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? -- [ ] DatabaseMigrator exposes the name of its support table (useful for tests that check which application tables are present). Alternative: have GRDB tell if a database table name is reserved by GRDB. -- [ ] Ask DatabaseMigrator if a migration has been applied (useful for tests that check if a legacy database resource should be tested or not) -- [ ] DatabaseMigrator.isInternalTable -- [ ] DatabaseMigrator.canMigrate(_:upTo:) -- [ ] Database.isSQLiteInternalTable - [ ] HiddenColumnsAdapter Not sure From b35cf4afdc99fa8fc1fa749a48514afe17dec73d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 15 Mar 2018 20:46:03 +0100 Subject: [PATCH 042/348] Record.save(_:) documents that is can't be overridden --- GRDB/Record/Record.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index ddad9f547..ad24dc289 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -332,6 +332,9 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// This method is guaranteed to have inserted or updated a row in the /// database if it returns without error. /// + /// You can't override this method. Instead, override `insert(_:)` + /// or `update(_:columns:)`. + /// /// - parameter db: A database connection. /// - throws: A DatabaseError whenever an SQLite error occurs, or errors /// thrown by update(). From 4ee9580d31543825ae75879d381b591e66341456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 29 Mar 2018 15:31:22 +0200 Subject: [PATCH 043/348] Remove redundant conformance of DatabaseValue to SQLExpressible --- GRDB/Core/DatabaseValue.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 95b313efd..cfb32ef97 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -10,7 +10,7 @@ import Foundation /// DatabaseValue is the intermediate type between SQLite and your values. /// /// See https://www.sqlite.org/datatype3.html -public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpressible, SQLExpression { +public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression { /// The SQLite storage public let storage: Storage From 31ed3ce2771c90cabf3bcff3c77ec17013a071d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 30 Mar 2018 09:12:35 +0200 Subject: [PATCH 044/348] GRDB3 TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index c5655589b..500732252 100644 --- a/TODO.md +++ b/TODO.md @@ -19,6 +19,7 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 +- [ ] Replace stopObservingDatabaseChangesUntilNextTransaction with a return value from `databaseDidChange` - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. From 2992bd544e2cb090cbfa058bdc3500d56cf14a8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 30 Mar 2018 10:49:43 +0200 Subject: [PATCH 045/348] GRDB3 TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 500732252..c2642bfde 100644 --- a/TODO.md +++ b/TODO.md @@ -19,6 +19,7 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 +- [ ] Rename `databaseEqual` to `databaseEquals` - [ ] Replace stopObservingDatabaseChangesUntilNextTransaction with a return value from `databaseDidChange` - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: From c3f9c75b3cc64fce69adcb63f579bbb4d9b840e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Mar 2018 14:53:22 +0200 Subject: [PATCH 046/348] Rename `databaseEqual` to `databaseEquals` --- GRDB/Legacy/Fixits-3.0.swift | 8 +++++++- GRDB/Record/PersistableRecord.swift | 2 +- README.md | 6 +++--- TODO.md | 1 - ...MutablePersistableRecordChangesTests.swift | 20 +++++++++---------- 5 files changed, 21 insertions(+), 16 deletions(-) diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index b8b822a7a..6d9eb8c5d 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -50,5 +50,11 @@ extension Record { public var persistentChangedValues: [String: DatabaseValue?] { preconditionFailure() } } -@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)") +@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEquals(_:), databaseChanges(from:), updateChanges(from:)") public final class RecordBox: Record { } + +extension MutablePersistableRecord { + /// :nodoc: + @available(*, unavailable, renamed: "databaseEquals") + public func databaseEqual(_ record: Self) -> Bool { preconditionFailure() } +} diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index bceff2f7a..f3d8f9ade 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -441,7 +441,7 @@ extension MutablePersistableRecord { /// Returns a boolean indicating whether this record and the other record /// have the same database representation. - public func databaseEqual(_ record: Self) -> Bool { + public func databaseEquals(_ record: Self) -> Bool { return databaseChangesIterator(from: record).next() == nil } diff --git a/README.md b/README.md index fcf8263f5..59522ad77 100644 --- a/README.md +++ b/README.md @@ -2525,12 +2525,12 @@ if try player.updateChanges(db) { } ``` -You can also use the `databaseEqual` method, which returns whether two records have the same database representation: +You can also use the `databaseEquals` method, which returns whether two records have the same database representation: ```swift let oldPlayer: Player = ... var newPlayer: Player = ... -if newPlayer.databaseEqual(oldPlayer) == false { +if newPlayer.databaseEquals(oldPlayer) == false { try newPlayer.save(db) } ``` @@ -2818,7 +2818,7 @@ This is the list of record methods, along with their required protocols. The [Re | `Type.fetchOne(statement)` | [FetchableRecord] | ⁴ | | `Type.filter(...).fetchOne(db)` | [FetchableRecord] & [TableRecord] | ² | | **[Record Comparison]** | | | -| `record.databaseEqual(...)` | [PersistableRecord] | | +| `record.databaseEquals(...)` | [PersistableRecord] | | | `record.databaseChanges(from:...)` | [PersistableRecord] | | | `record.updateChanges(db, from:...)` | [PersistableRecord] | | | `record.hasDatabaseChanges` | [Record](#record-class) | | diff --git a/TODO.md b/TODO.md index c2642bfde..500732252 100644 --- a/TODO.md +++ b/TODO.md @@ -19,7 +19,6 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 -- [ ] Rename `databaseEqual` to `databaseEquals` - [ ] Replace stopObservingDatabaseChangesUntilNextTransaction with a return value from `databaseDidChange` - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index bf2acc47f..b7fab1a80 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -46,14 +46,14 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } } - func testDegenerateDatabaseEqualWithSelf() throws { + func testDegenerateDatabaseEqualsWithSelf() throws { struct DegenerateRecord: MutablePersistableRecord { static let databaseTableName = "ignored" func encode(to container: inout PersistenceContainer) { } } let record = DegenerateRecord() - XCTAssertTrue(record.databaseEqual(record)) + XCTAssertTrue(record.databaseEquals(record)) XCTAssertTrue(record.databaseChanges(from: record).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -64,10 +64,10 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } } - func testDatabaseEqualWithSelf() throws { + func testDatabaseEqualsWithSelf() throws { do { let player = Player(id: nil, name: nil, score: nil, creationDate: nil) - XCTAssertTrue(player.databaseEqual(player)) + XCTAssertTrue(player.databaseEquals(player)) XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -79,7 +79,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { let player = Player(id: 1, name: "foo", score: 42, creationDate: Date()) - XCTAssertTrue(player.databaseEqual(player)) + XCTAssertTrue(player.databaseEquals(player)) XCTAssertTrue(player.databaseChanges(from: player).isEmpty) let dbQueue = try makeDatabaseQueue() @@ -103,7 +103,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var newPlayer = player newPlayer.name = "Bobby" - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -120,7 +120,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var newPlayer = player newPlayer.name = nil - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -137,7 +137,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { var newPlayer = player newPlayer.score = 41 - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 1) XCTAssertEqual(changes["score"]!, .null) @@ -155,7 +155,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { newPlayer.name = "Bobby" newPlayer.score = 41 - XCTAssertFalse(newPlayer.databaseEqual(player)) + XCTAssertFalse(newPlayer.databaseEquals(player)) let changes = newPlayer.databaseChanges(from: player) XCTAssertEqual(changes.count, 2) XCTAssertEqual(changes["name"]!, "Arthur".databaseValue) @@ -172,7 +172,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } } - func testDatabaseEqualWithDifferentTypesAndDifferentWidth() throws { + func testDatabaseEqualsWithDifferentTypesAndDifferentWidth() throws { // Mangle column case as well, for fun ;-) struct NarrowPlayer: MutablePersistableRecord, Codable { static let databaseTableName = "players" From e9d45b543598d012568ceb92fc13d0d79c0a5623 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Mar 2018 15:07:19 +0200 Subject: [PATCH 047/348] GRDB3 TODO --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 500732252..c5655589b 100644 --- a/TODO.md +++ b/TODO.md @@ -19,7 +19,6 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 -- [ ] Replace stopObservingDatabaseChangesUntilNextTransaction with a return value from `databaseDidChange` - [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 - [ ] Do one of those two: 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. From 2dfbe8e5f2d6164c193f9da04598ceef58a3f1f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Mar 2018 15:56:42 +0200 Subject: [PATCH 048/348] Prevent snapshot creation from within a transaction --- GRDB/Core/DatabasePool.swift | 38 ++++++++++++++++++++- Tests/GRDBTests/DatabaseSnapshotTests.swift | 15 -------- 2 files changed, 37 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index f21e3e8fe..ade0ad076 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -622,7 +622,7 @@ extension DatabasePool { // MARK: - Snapshots /// Creates a database snapshot. - //: + /// /// The snapshot sees an unchanging database content, as it existed at the /// moment it was created. /// @@ -646,11 +646,47 @@ extension DatabasePool { /// try Player.fetchCount(db) /// } /// + /// It is forbidden to create a snapshot from the writer protected dispatch + /// queue when a transaction is opened, though, because it is likely a + /// programmer error: + /// + /// try dbPool.write { db in + /// try db.inTransaction { + /// try Player.deleteAll() + /// // fatal error: makeSnapshot() must not be called from inside a transaction + /// let snapshot = dbPool.makeSnapshot() + /// return .commit + /// } + /// } + /// + /// To avoid this fatal error, create the snapshot *before* or *after* the + /// transaction: + /// + /// try dbPool.write { db in + /// // OK + /// let snapshot = dbPool.makeSnapshot() + /// + /// try db.inTransaction { + /// try Player.deleteAll() + /// return .commit + /// } + /// + /// // OK + /// let snapshot = dbPool.makeSnapshot() + /// } + /// /// You can create as many snapshots as you need, regardless of the maximum /// number of reader connections in the pool. /// /// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html public func makeSnapshot() throws -> DatabaseSnapshot { + // Sanity check + if writer.onValidQueue { + writer.execute { db in + GRDBPrecondition(!db.isInsideTransaction, "makeSnapshot() must not be called from inside a transaction.") + } + } + let snapshot = try DatabaseSnapshot(path: path, configuration: writer.configuration) snapshot.read { setupDatabase($0) } return snapshot diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index aa5799a9e..e988626f9 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -40,21 +40,6 @@ class DatabaseSnapshotTests: GRDBTestCase { } } - func testSnapshotDoesNotSeeUncommittedTransaction() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "t") { $0.column("id", .integer).primaryKey() } - try db.beginTransaction() - try db.execute("INSERT INTO t DEFAULT VALUES") - let snapshot = try dbPool.makeSnapshot() - try db.commit() - try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) - try snapshot.read { db in - try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 0) - } - } - } - func testSnapshotCreatedOutsideOfWriterQueue() throws { let dbPool = try makeDatabasePool() try dbPool.write { db in From ce919f0411737e0168c95d56a903acbcd6fcee1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 31 Mar 2018 16:00:34 +0200 Subject: [PATCH 049/348] GRDB3 TODO --- TODO.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/TODO.md b/TODO.md index c5655589b..5e125bb80 100644 --- a/TODO.md +++ b/TODO.md @@ -19,16 +19,9 @@ Xcode 9.3, Swift 4.1 GRDB 3.0 -- [ ] Make DatabasePool.write safe. See https://github.com/groue/GRDB.swift/commit/5e3c7d9c430df606a1cccfd4983be6b50e778a5c#commitcomment-26988970 -- [ ] Do one of those two: - 1. Make save() impossible to customize: remove it from EncodableRecord protocol, and remove performSave() from tne public API. - 2. Open Record.save(), and have RecordBox.save() forward this method to its underlying type. -- [ ] Not sure: Make the MutableEncodableRecord.update(_:columns:) method mutating (as support for an updatedDate column). If so, allow type to change the set of changed columns. - [ ] Not sure: type safety - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? -- [ ] Rename columnCount -> numberOfColumns -- [ ] Try to remove double EncodableRecord/MutableEncodableRecord protocols: Would non-mutating Record methods help? - [ ] HiddenColumnsAdapter Not sure From 3160b65172675ff27c2280995b9863b7c037101d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 4 Apr 2018 13:23:46 +0200 Subject: [PATCH 050/348] Upgrade SQLiteCustom to 3.22.0 --- SQLiteCustom/src | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SQLiteCustom/src b/SQLiteCustom/src index ced281555..a1732cac8 160000 --- a/SQLiteCustom/src +++ b/SQLiteCustom/src @@ -1 +1 @@ -Subproject commit ced281555317b9313b26c33185669730b5819765 +Subproject commit a1732cac8dc7314b4c943daf20956dbfb895872d From 03f5a83cbfc0b5deab86188911f33f6c7739bdd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Apr 2018 12:08:51 +0200 Subject: [PATCH 051/348] Introduce and DatabaseRequest and SelectStatementRequest on top of FetchRequest --- GRDB/Core/FetchRequest.swift | 131 ++++++++++-------- .../QueryInterfaceRequest.swift | 10 +- 2 files changed, 75 insertions(+), 66 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index b10915c27..d17185743 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,39 +1,39 @@ -/// The protocol for all types that define a way to fetch database content. -/// -/// struct Player: FetchableRecord { ... } -/// let request: ... // Some FetchRequest that fetches Player -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchOne(db) // Player? -public protocol FetchRequest { - /// The type that can convert raw database rows to fetched values - associatedtype RowDecoder - - /// A tuple that contains a prepared statement that is ready to be - /// executed, and an eventual row adapter. - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) - - /// The number of rows fetched by the request. - /// - /// Default implementation builds a naive SQL query based on the statement - /// returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. - /// - /// Adopting types can refine this countRequest method and return more - /// efficient SQL. - /// - /// - parameter db: A database connection. - func fetchCount(_ db: Database) throws -> Int - - /// The database region that the request looks into. - /// - /// This method has a default implementation. +// MARK: - DatabaseRequest + +/// The protocol for all types that request database values. +public protocol DatabaseRequest { + /// Returns the database region that the request looks into. /// /// - parameter db: A database connection. func fetchedRegion(_ db: Database) throws -> DatabaseRegion } -extension FetchRequest { - /// The number of rows fetched by the request. +// MARK: - SelectStatementRequest + +/// The protocol for all requests that run from a single select statement. +public protocol SelectStatementRequest: DatabaseRequest { + /// Returns a tuple that contains a prepared statement that is ready to be + /// executed, and an eventual row adapter. + /// + /// - parameter db: A database connection. + /// - returns: A prepared statement and an eventual row adapter. + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + + /// Returns the number of rows fetched by the request. + /// + /// The default implementation builds a naive SQL query based on the + /// statement returned by the `prepare` method: + /// `SELECT COUNT(*) FROM (...)`. + /// + /// Adopting types can refine this method in order to use more + /// efficient SQL. + /// + /// - parameter db: A database connection. + func fetchCount(_ db: Database) throws -> Int +} + +extension SelectStatementRequest { + /// Returns the number of rows fetched by the request. /// /// This default implementation builds a naive SQL query based on the /// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`. @@ -45,7 +45,10 @@ extension FetchRequest { return try Int.fetchOne(db, sql, arguments: statement.arguments)! } - /// The database region that the request looks into. + /// Returns the database region that the request looks into. + /// + /// This default implementation returns a region built from the statement + /// returned by the `prepare` method. /// /// - parameter db: A database connection. public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { @@ -54,6 +57,21 @@ extension FetchRequest { } } +// MARK: - FetchRequest + +/// The protocol for all requests that run from a single select statement, and +/// tell how fetched rows should be interpreted. +/// +/// struct Player: FetchableRecord { ... } +/// let request: ... // Some FetchRequest that fetches Player +/// try request.fetchCursor(db) // Cursor of Player +/// try request.fetchAll(db) // [Player] +/// try request.fetchOne(db) // Player? +public protocol FetchRequest: SelectStatementRequest { + /// The type that tells how fetched database rows should be interpreted. + associatedtype RowDecoder +} + extension FetchRequest { /// Returns a request bound to type T. /// @@ -78,6 +96,8 @@ extension FetchRequest { } } +// MARK: - AdaptedFetchRequest + /// An adapted request. public struct AdaptedFetchRequest : FetchRequest { public typealias RowDecoder = Base.RowDecoder @@ -113,6 +133,8 @@ public struct AdaptedFetchRequest : FetchRequest { } } +// MARK: - AnyFetchRequest + /// A type-erased FetchRequest. /// /// An AnyFetchRequest forwards its operations to an underlying request, @@ -124,14 +146,14 @@ public struct AnyFetchRequest : FetchRequest { private let _fetchCount: (Database) throws -> Int private let _fetchedRegion: (Database) throws -> DatabaseRegion - /// Creates a new request that wraps and forwards operations to `request`. + /// Creates a request that wraps and forwards operations to `request`. public init(_ request: Request) { _prepare = request.prepare _fetchCount = request.fetchCount _fetchedRegion = request.fetchedRegion } - /// Creates a new request whose `prepare()` method wraps and forwards + /// Creates a request whose `prepare()` method wraps and forwards /// operations the argument closure. public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) { _prepare = { db in @@ -166,24 +188,22 @@ public struct AnyFetchRequest : FetchRequest { } } -/// A Request built from raw SQL. +// MARK: - SQLRequest + +/// A FetchRequest built from raw SQL. public struct SQLRequest : FetchRequest { public typealias RowDecoder = T - public let sql: String - public let arguments: StatementArguments? - public let adapter: RowAdapter? + public var sql: String + public var arguments: StatementArguments? + public var adapter: RowAdapter? private let cache: Cache? - /// Creates a new request from an SQL string, optional arguments, and + /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// - /// For example: - /// - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) - /// try dbQueue.inDatabase { db in - /// let player = try request.fetchOne(db) // Player? - /// } + /// let request = SQLRequest("SELECT * FROM players") + /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. @@ -196,18 +216,7 @@ public struct SQLRequest : FetchRequest { self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil) } - /// Creates a new SQL request from any other fetch request. - /// - /// For example: - /// - /// let request = Player.filter(Column("name") == "Arthur") - /// try dbQueue.inDatabase { db in - /// let sqlRequest = try SQLRequest(db, request: request) // SQLRequest - /// print(sqlRequest.sql) - /// // Prints "SELECT * FROM players WHERE name = ?" - /// print(sqlRequest.arguments) - /// // Prints ["Arthur"] - /// } + /// Creates an SQL request from any other fetch request. /// /// - parameters: /// - db: A database connection. @@ -220,17 +229,17 @@ public struct SQLRequest : FetchRequest { self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached) } - /// Creates a new SQL request from an SQL string, optional arguments, and + /// Creates an SQL request from an SQL string, optional arguments, and /// optional row adapter. /// - /// The *cache* arguments should be `.internal` for requests generated by - /// GRDB, and `.public` for requests generated by the user. + /// let request = SQLRequest("SELECT * FROM players") + /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter. - /// - cache: Optional statement cache name. + /// - statementCacheName: Optional statement cache name. /// - returns: A SQLRequest init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) { self.sql = sql diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index c3b9d655e..635401fa3 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -12,27 +12,27 @@ public struct QueryInterfaceRequest { extension QueryInterfaceRequest : FetchRequest { public typealias RowDecoder = T - /// A tuple that contains a prepared statement that is ready to be + /// Returns a tuple that contains a prepared statement that is ready to be /// executed, and an eventual row adapter. /// /// - parameter db: A database connection. - /// + /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { return try query.prepare(db) } - /// The number of rows fetched by the request. + /// Returns the number of rows fetched by the request. /// /// - parameter db: A database connection. - /// /// :nodoc: public func fetchCount(_ db: Database) throws -> Int { return try query.fetchCount(db) } - /// The database region that the request looks into. + /// Returns the database region that the request looks into. /// + /// - parameter db: A database connection. /// :nodoc: public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { return try query.fetchedRegion(db) From 67ae1d4cf0592df818fa895876840122d410a05c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Apr 2018 13:09:24 +0200 Subject: [PATCH 052/348] Document request protocols --- README.md | 110 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 92 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 59522ad77..cd6d51715 100644 --- a/README.md +++ b/README.md @@ -3694,7 +3694,7 @@ try request.fetchCount(db) // Int try Player.fetchAll(db, "SELECT ...") // [Player] ``` -But you may prefer to bring some elegance back in, and build custom requests on top of the `FetchRequest` protocol: +But you may prefer to bring some elegance back in, and build custom requests: ```swift // No custom SQL in sight @@ -3711,39 +3711,104 @@ Player.customRequest(...).rx }) ``` +- [DatabaseRequest Protocol](#databaserequest-protocol) +- [SelectStatementRequest Protocol](#selectstatementrequest-protocol) +- [FetchRequest Protocol](#fetchrequest-protocol) +- [Building Custom Requests](#building-custom-requests) +- [Fetching From Custom Requests](#fetching-from-custom-requests) -### FetchRequest Protocol -**FetchRequest is the protocol for all types that define a way to fetch database rows:** +### DatabaseRequest Protocol + +**DatabaseRequest** is the highest-level protocol for all types that request database values. It does not tell how values are fetched, but it allows database observation tools ([transaction observers](#transactionobserver-protocol) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB)) the ability to notify changes in the request content. ```swift -protocol FetchRequest { - /// The type that tells how fetched rows should be decoded - associatedtype RowDecoder +protocol DatabaseRequest { + func fetchedRegion(_ db: Database) throws -> DatabaseRegion +} +``` + +**You'll use DatabaseRequest when you want to encapsulate your most complex fetching strategies.** + +For example: + +```swift +struct LibraryRequest: DatabaseRequest { + func fetchAll(_ db: Database) throws -> [(Author, [Books])] { + let authors = try Author.fetchAll(db) + let books = try Dictionary( + grouping: Book.fetchAll(db), + by: { book in book.authorId }) + return authors.map { author in (author, books[author.id]!) } + } + func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + let authorsRegion = try Author.all().fetchedRegion(db) + let booksRegion = try Book.all().fetchedRegion(db) + return authorsRegion.union(booksRegion) + } +} + +// Track library content with RxGRDB +let request = LibraryRequest() +dbQueue.rx + .fetchTokens(in: [request]) + .mapFetch { db in try request.fetchAll(db) } + .subscribe(onNext: { library: [(Author, [Books])] in + print("Library has changed.") + }) +``` + +See [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/2.10/Structs/DatabaseRegion.html) reference for more information. + + +### SelectStatementRequest Protocol + +**SelectStatementRequest** is the protocol for all requests that run a single select statement: + +```swift +protocol SelectStatementRequest: DatabaseRequest { /// A tuple that contains a prepared statement, and an eventual row adapter. func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int - - /// The database region that the request looks into. - func fetchedRegion(_ db: Database) throws -> DatabaseRegion } ``` -The `RowDecoder` associated type tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. - The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. -The `fetchedRegion` method helps [transaction observers](#transactionobserver-protocol) efficiently track modifications in requests results. It has a default implementation that you can't really improve in the current state of the API. +The `fetchedRegion` method inherited from [DatabaseRequest](#databaserequest-protocol) is also given a default implementation, based on the statement returned by `prepare`. + +There are few use cases for SelectStatementRequest. Usually, your custom requests will adopt its derivative [FetchRequest](#fetchrequest-protocol), introduced below: + + +### FetchRequest Protocol + +**FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted: + +```swift +protocol FetchRequest: SelectStatementRequest { + /// The type that tells how fetched rows should be decoded + associatedtype RowDecoder +} +``` + +The `RowDecoder` associated type tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. + +FetchRequest is adopted, for example, by [query interface requests](#requests): + +```swift +// A FetchRequest whose RowDecoder associated type is Player. +let request = Player.all() +``` ### Building Custom Requests -**To build custom requests**, you can create your own type that adopts the [FetchRequest](#fetchrequest-protocol) protocol, derive requests from other requests, or use one of the built-in concrete types: +**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts one of the request protocols described above ([FetchRequest](#fetchrequest-protocol), [SelectStatementRequest](#selectstatementrequest-protocol), or [DatabaseRequest](#databaserequest-protocol)). - [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: @@ -3776,22 +3841,31 @@ The `fetchedRegion` method helps [transaction observers](#transactionobserver-pr ### Fetching From Custom Requests -A fetch request knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [records](#records)): +A type adopting [FetchRequest](#fetchrequest-protocol) knows exactly what it has to do when its RowDecoder associated type can decode database rows ([Row](#fetching-rows) itself, [values](#value-queries), or [FetchableRecord]): ```swift -let rowRequest = ... // Some TypedRequest that fetches Row +let rowRequest = ... // Some FetchRequest that fetches Row try request.fetchCursor(db) // A cursor of rows -let playerRequest = ... // Some TypedRequest that fetches Player +let playerRequest = ... // Some FetchRequest that fetches Player try request.fetchAll(db) // [Player] -let intRequest = ... // Some TypedRequest that fetches Int +let intRequest = ... // Some FetchRequest that fetches Int try request.fetchOne(db) // Int? ``` +For example: + +```swift +let playerRequest = SQLRequest( + "SELECT * FROM players WHERE color = ?" + arguments: [color]) +try request.fetchAll(db) // [Player] +``` + See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. -When RowDecoder is another type, you can write your own convenience methods. +When the RowDecoder type associated with the FetchRequest is not Row, DatabaseValueConvertible, or FetchableRecord, you can write your own convenience methods in an extension of the FetchRequest protocol. Application Tools From b7239c4b6f67216194068b39768ef28fc8c99f6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 8 Apr 2018 13:18:02 +0200 Subject: [PATCH 053/348] Document request protocols --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cd6d51715..f4541e5c9 100644 --- a/README.md +++ b/README.md @@ -3796,12 +3796,12 @@ protocol FetchRequest: SelectStatementRequest { } ``` -The `RowDecoder` associated type tells a request how to decode rows. It can be any type, but not all types have built-in support. See [Fetching From Custom Requests](#fetching-from-custom-requests) below. +The `RowDecoder` associated type can be any type. Yet, not all types have built-in support: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. FetchRequest is adopted, for example, by [query interface requests](#requests): ```swift -// A FetchRequest whose RowDecoder associated type is Player. +// A FetchRequest whose RowDecoder associated type is Player: let request = Player.all() ``` From 64899e5a399fdf4821221bbc5e6c5bfc1ff1b867 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 10 Apr 2018 13:44:23 +0200 Subject: [PATCH 054/348] Introduce SelectionRequest, FilteredRequest, AggregatingRequest, and OrderedRequest. Those request protocols allow types that are not QueryInterfaceRequest to expose the same derivation API. This is a necessary step towards associations. --- GRDB.xcodeproj/project.pbxproj | 8 + .../QueryInterfaceRequest.swift | 157 ++++---------- GRDB/QueryInterface/RequestProtocols.swift | 201 ++++++++++++++++++ .../SQLExpression+QueryInterface.swift | 50 +++-- GRDB/QueryInterface/SQLSelectable.swift | 42 ++++ GRDB/QueryInterface/TableDefinition.swift | 12 +- GRDBCipher.xcodeproj/project.pbxproj | 13 +- GRDBCustom.xcodeproj/project.pbxproj | 11 +- 8 files changed, 350 insertions(+), 144 deletions(-) create mode 100644 GRDB/QueryInterface/RequestProtocols.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 22486938e..ea6c98747 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -50,6 +50,9 @@ 560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 561667051D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; + 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; + 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */; }; 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; }; 56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; 56176C5B1EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; }; @@ -766,6 +769,7 @@ 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 560FC5101CAEEDF10014AA8E /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -1274,6 +1278,7 @@ 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -2160,6 +2165,7 @@ buildActionMask = 2147483647; files = ( 569A98EF2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, + 5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 565490CE1D5AE252005622CB /* NSNull.swift in Sources */, @@ -2321,6 +2327,7 @@ 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, + 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, 56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */, 56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */, @@ -2670,6 +2677,7 @@ files = ( 56873BEC1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3D1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */, diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 635401fa3..f04147f6c 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -39,27 +39,11 @@ extension QueryInterfaceRequest : FetchRequest { } } -extension QueryInterfaceRequest { +extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, AggregatingRequest, OrderedRequest { // MARK: Request Derivation - - /// A new QueryInterfaceRequest with a new net of selected columns. - /// - /// // SELECT id, email FROM players - /// var request = Player.all() - /// request = request.select(Column("id"), Column("email")) - /// - /// Any previous selection is replaced: - /// - /// // SELECT email FROM players - /// request - /// .select(Column("id")) - /// .select(Column("email")) - public func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { - return select(selection) - } - - /// A new QueryInterfaceRequest with a new net of selected columns. + + /// Creates a request with a new net of selected columns. /// /// // SELECT id, email FROM players /// var request = Player.all() @@ -77,23 +61,7 @@ extension QueryInterfaceRequest { return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest with a new net of selected columns. - /// - /// // SELECT id, email FROM players - /// var request = Player.all() - /// request = request.select(sql: "id, email") - /// - /// Any previous selection is replaced: - /// - /// // SELECT email FROM players - /// request - /// .select(sql: "id") - /// .select(sql: "email") - public func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return select(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest which returns distinct rows. + /// Creates a request which returns distinct rows. /// /// // SELECT DISTINCT * FROM players /// var request = Player.all() @@ -108,7 +76,7 @@ extension QueryInterfaceRequest { return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest with the provided *predicate* added to the + /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// /// // SELECT * FROM players WHERE email = 'arthur@example.com' @@ -124,34 +92,25 @@ extension QueryInterfaceRequest { }) } - /// A new QueryInterfaceRequest with the provided *predicate* added to the - /// eventual set of already applied predicates. + /// Creates a request that matches nothing. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM players WHERE 0 /// var request = Player.all() - /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) - public func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return filter(SQLExpressionLiteral(sql, arguments: arguments)) + /// request = request.none() + public func none() -> QueryInterfaceRequest { + var query = self.query + query.wherePromise = DatabasePromise(value: false.sqlExpression) + return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest grouped according to *expressions*. - public func group(_ expressions: SQLExpressible...) -> QueryInterfaceRequest { - return group(expressions) - } - - /// A new QueryInterfaceRequest grouped according to *expressions*. + /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest { var query = self.query query.groupByExpressions = expressions.map { $0.sqlExpression } return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest with a new grouping. - public func group(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return group(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest with the provided *predicate* added to the + /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { var query = self.query @@ -163,30 +122,7 @@ extension QueryInterfaceRequest { return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest with the provided *sql* added to the - /// eventual set of already applied predicates. - public func having(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return having(SQLExpressionLiteral(sql, arguments: arguments)) - } - - /// A new QueryInterfaceRequest with the provided *orderings*. - /// - /// // SELECT * FROM players ORDER BY name - /// var request = Player.all() - /// request = request.order(Column("name")) - /// - /// Any previous ordering is replaced: - /// - /// // SELECT * FROM players ORDER BY name - /// request - /// .order(Column("email")) - /// .reversed() - /// .order(Column("name")) - public func order(_ orderings: SQLOrderingTerm...) -> QueryInterfaceRequest { - return order(orderings) - } - - /// A new QueryInterfaceRequest with the provided *orderings*. + /// Creates a request with the provided *orderings*. /// /// // SELECT * FROM players ORDER BY name /// var request = Player.all() @@ -206,23 +142,7 @@ extension QueryInterfaceRequest { return QueryInterfaceRequest(query: query) } - /// A new QueryInterfaceRequest with the provided *sql* used for sorting. - /// - /// // SELECT * FROM players ORDER BY name - /// var request = Player.all() - /// request = request.order(sql: "name") - /// - /// Any previous ordering is replaced: - /// - /// // SELECT * FROM players ORDER BY name - /// request - /// .order(sql: "email") - /// .order(sql: "name") - public func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { - return order([SQLExpressionLiteral(sql, arguments: arguments)]) - } - - /// A new QueryInterfaceRequest sorted in reversed order. + /// Creates a request sorted in reversed order. /// /// // SELECT * FROM players ORDER BY name DESC /// var request = Player.all().order(Column("name")) @@ -233,12 +153,13 @@ extension QueryInterfaceRequest { return QueryInterfaceRequest(query: query) } - /// A QueryInterfaceRequest which fetches *limit* rows, starting - /// at *offset*. + /// Creates a request which fetches *limit* rows, starting at *offset*. /// /// // SELECT * FROM players LIMIT 1 /// var request = Player.all() /// request = request.limit(1) + /// + /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { var query = self.query query.limit = SQLLimit(limit: limit, offset: offset) @@ -248,7 +169,9 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest where T: TableRecord { - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + // MARK: Request Derivation + + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM players WHERE id = 1 /// var request = Player.all() @@ -265,7 +188,7 @@ extension QueryInterfaceRequest where T: TableRecord { return filter(keys: [key]) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM players WHERE id IN (1, 2, 3) /// var request = Player.all() @@ -298,7 +221,7 @@ extension QueryInterfaceRequest where T: TableRecord { }) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' /// var request = Player.all() @@ -318,7 +241,7 @@ extension QueryInterfaceRequest where T: TableRecord { return filter(keys: [key]) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) @@ -385,7 +308,7 @@ extension TableRecord { // MARK: Request Derivation - /// Creates a QueryInterfaceRequest which fetches all records. + /// Creates a request which fetches all records. /// /// // SELECT * FROM players /// let request = Player.all() @@ -400,12 +323,12 @@ extension TableRecord { return QueryInterfaceRequest(query: query) } - /// Creates a QueryInterfaceRequest which fetches no record. + /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { return filter(false) } - /// Creates a QueryInterfaceRequest which selects *selection*. + /// Creates a request which selects *selection*. /// /// // SELECT id, email FROM players /// let request = Player.select(Column("id"), Column("email")) @@ -413,7 +336,7 @@ extension TableRecord { return all().select(selection) } - /// Creates a QueryInterfaceRequest which selects *selection*. + /// Creates a request which selects *selection*. /// /// // SELECT id, email FROM players /// let request = Player.select([Column("id"), Column("email")]) @@ -421,7 +344,7 @@ extension TableRecord { return all().select(selection) } - /// Creates a QueryInterfaceRequest which selects *sql*. + /// Creates a request which selects *sql*. /// /// // SELECT id, email FROM players /// let request = Player.select(sql: "id, email") @@ -429,7 +352,7 @@ extension TableRecord { return all().select(sql: sql, arguments: arguments) } - /// Creates a QueryInterfaceRequest with the provided *predicate*. + /// Creates a request with the provided *predicate*. /// /// // SELECT * FROM players WHERE email = 'arthur@example.com' /// let request = Player.filter(Column("email") == "arthur@example.com") @@ -441,7 +364,7 @@ extension TableRecord { return all().filter(predicate) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM players WHERE id = 1 /// let request = Player.filter(key: 1) @@ -453,7 +376,7 @@ extension TableRecord { return all().filter(key: key) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM players WHERE id IN (1, 2, 3) /// let request = Player.filter(keys: [1, 2, 3]) @@ -465,7 +388,7 @@ extension TableRecord { return all().filter(keys: keys) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' /// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"]) @@ -480,7 +403,7 @@ extension TableRecord { return all().filter(key: key) } - /// Creates a QueryInterfaceRequest with the provided primary key *predicate*. + /// Creates a request with the provided primary key *predicate*. /// /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) @@ -495,7 +418,7 @@ extension TableRecord { return all().filter(keys: keys) } - /// Creates a QueryInterfaceRequest with the provided *predicate*. + /// Creates a request with the provided *predicate*. /// /// // SELECT * FROM players WHERE email = 'arthur@example.com' /// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"]) @@ -507,7 +430,7 @@ extension TableRecord { return all().filter(sql: sql, arguments: arguments) } - /// Creates a QueryInterfaceRequest sorted according to the + /// Creates a request sorted according to the /// provided *orderings*. /// /// // SELECT * FROM players ORDER BY name @@ -520,7 +443,7 @@ extension TableRecord { return all().order(orderings) } - /// Creates a QueryInterfaceRequest sorted according to the + /// Creates a request sorted according to the /// provided *orderings*. /// /// // SELECT * FROM players ORDER BY name @@ -533,7 +456,7 @@ extension TableRecord { return all().order(orderings) } - /// Creates a QueryInterfaceRequest sorted according to *sql*. + /// Creates a request sorted according to *sql*. /// /// // SELECT * FROM players ORDER BY name /// let request = Player.order(sql: "name") @@ -545,7 +468,7 @@ extension TableRecord { return all().order(sql: sql, arguments: arguments) } - /// Creates a QueryInterfaceRequest which fetches *limit* rows, starting at + /// Creates a request which fetches *limit* rows, starting at /// *offset*. /// /// // SELECT * FROM players LIMIT 1 diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift new file mode 100644 index 000000000..4fa777d9b --- /dev/null +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -0,0 +1,201 @@ +// MARK: - SelectionRequest + +/// The protocol for all requests that can refine their selection. +public protocol SelectionRequest { + /// Creates a request with a new net of selected columns. + /// + /// // SELECT id, email FROM players + /// var request = Player.all() + /// request = request.select([Column("id"), Column("email")]) + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM players + /// request + /// .select([Column("id")]) + /// .select([Column("email")]) + func select(_ selection: [SQLSelectable]) -> Self +} + +extension SelectionRequest { + /// Creates a request with a new net of selected columns. + /// + /// // SELECT id, email FROM players + /// var request = Player.all() + /// request = request.select(Column("id"), Column("email")) + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM players + /// request + /// .select(Column("id")) + /// .select(Column("email")) + public func select(_ selection: SQLSelectable...) -> Self { + return select(selection) + } + + /// Creates a request with a new net of selected columns. + /// + /// // SELECT id, email FROM players + /// var request = Player.all() + /// request = request.select(sql: "id, email") + /// + /// Any previous selection is replaced: + /// + /// // SELECT email FROM players + /// request + /// .select(sql: "id") + /// .select(sql: "email") + public func select(sql: String, arguments: StatementArguments? = nil) -> Self { + return select(SQLSelectionLiteral(sql, arguments: arguments)) + } +} + +// MARK: - FilteredRequest + +/// The protocol for all requests that can be filtered. +public protocol FilteredRequest { + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// var request = Player.all() + /// request = request.filter(Column("email") == "arthur@example.com") + func filter(_ predicate: SQLExpressible) -> Self + + /// Creates a request that matches nothing. + /// + /// // SELECT * FROM players WHERE 0 + /// var request = Player.all() + /// request = request.none() + func none() -> Self +} + +extension FilteredRequest { + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// var request = Player.all() + /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) + public func filter(sql: String, arguments: StatementArguments? = nil) -> Self { + return filter(SQLExpressionLiteral(sql, arguments: arguments)) + } +} + +// MARK: - AggregatingRequest + +/// The protocol for all requests that can aggregate. +public protocol AggregatingRequest { + /// Creates a request grouped according to *expressions*. + func group(_ expressions: [SQLExpressible]) -> Self + + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + func having(_ predicate: SQLExpressible) -> Self +} + +extension AggregatingRequest { + /// Creates a request grouped according to *expressions*. + public func group(_ expressions: SQLExpressible...) -> Self { + return group(expressions) + } + + /// Creates a request with a new grouping. + public func group(sql: String, arguments: StatementArguments? = nil) -> Self { + // This "expression" is not a real expression. We support raw sql which + // actually contains several expressions: + // + // request = Player.group(sql: "teamId, level") + // + // This is why we use the "unsafe" flag, so that the SQLExpressionLiteral + // does not output its safe wrapping parenthesis, and generates + // invalid SQL. + var expression = SQLExpressionLiteral(sql, arguments: arguments) + expression.unsafeRaw = true + return group(expression) + } + + /// Creates a request with the provided *sql* added to the + /// eventual set of already applied predicates. + public func having(sql: String, arguments: StatementArguments? = nil) -> Self { + return having(SQLExpressionLiteral(sql, arguments: arguments)) + } +} + +// MARK: - OrderedRequest + +/// The protocol for all requests that be ordered. +public protocol OrderedRequest { + /// Creates a request with the provided *orderings*. + /// + /// // SELECT * FROM players ORDER BY name + /// var request = Player.all() + /// request = request.order([Column("name")]) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM players ORDER BY name + /// request + /// .order([Column("email")]) + /// .reversed() + /// .order([Column("name")]) + func order(_ orderings: [SQLOrderingTerm]) -> Self + + /// Creates a request that reverses applied orderings. If no ordering + /// was applied, the returned request is identical. + /// + /// // SELECT * FROM players ORDER BY name DESC + /// var request = Player.all().order(Column("name")) + /// request = request.reversed() + /// + /// // SELECT * FROM players + /// var request = Player.all() + /// request = request.reversed() + func reversed() -> Self +} + +extension OrderedRequest { + /// Creates a request with the provided *orderings*. + /// + /// // SELECT * FROM players ORDER BY name + /// var request = Player.all() + /// request = request.order(Column("name")) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM players ORDER BY name + /// request + /// .order(Column("email")) + /// .reversed() + /// .order(Column("name")) + public func order(_ orderings: SQLOrderingTerm...) -> Self { + return order(orderings) + } + + /// Creates a request with the provided *sql* used for sorting. + /// + /// // SELECT * FROM players ORDER BY name + /// var request = Player.all() + /// request = request.order(sql: "name") + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM players ORDER BY name + /// request + /// .order(sql: "email") + /// .order(sql: "name") + public func order(sql: String, arguments: StatementArguments? = nil) -> Self { + // This "expression" is not a real expression. We support raw sql which + // actually contains several expressions: + // + // request = Player.order(sql: "teamId, level") + // + // This is why we use the "unsafe" flag, so that the SQLExpressionLiteral + // does not output its safe wrapping parenthesis, and generates + // invalid SQL. + var expression = SQLExpressionLiteral(sql, arguments: arguments) + expression.unsafeRaw = true + return order([expression]) + } +} diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index ce34318f3..187214a06 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -46,6 +46,12 @@ public struct SQLExpressionLiteral : SQLExpression { /// SQL literal public let arguments: StatementArguments? + /// If safe, an SQLExpressionLiteral("foo") wraps itself in parenthesis, + /// and outputs "(foo)" in SQL queries. This avoids any bug due to operator + /// precedence. When unsafe, the expression literal does not wrap itself + /// in parenthesis and outputs its raw sql. + var unsafeRaw: Bool = false + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Creates an SQL literal expression. @@ -70,7 +76,11 @@ public struct SQLExpressionLiteral : SQLExpression { } arguments! += literalArguments } - return sql + if unsafeRaw { + return sql + } else { + return "(" + sql + ")" + } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -232,17 +242,7 @@ public struct SQLBinaryOperator : Hashable { case 1: return expressions[0] default: - let literals = expressions.map { $0.literal } - let firstLiteral = literals[0] - var sql = firstLiteral.sql - var arguments = firstLiteral.arguments ?? StatementArguments() - for literal in literals.suffix(from: 1) { - sql += " \(self.sql) \(literal.sql)" - if let args = literal.arguments { - arguments += args - } - } - return SQLExpressionLiteral("(\(sql))", arguments: arguments.isEmpty ? nil : arguments) + return SQLExpressionBinaryOperatorChain(op: self, expressions: expressions) } } } @@ -356,6 +356,32 @@ public struct SQLExpressionBinary : SQLExpression { } } +// MARK: - SQLExpressionBinaryOperatorChain + +struct SQLExpressionBinaryOperatorChain : SQLExpression { + let op: SQLBinaryOperator + let expressions: [SQLExpression] + + // Exposed to SQLBinaryOperator.join + fileprivate init(op: SQLBinaryOperator, expressions: [SQLExpression]) { + assert(expressions.count >= 2) + self.op = op + self.expressions = expressions + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } + let joiner = " \(op.sql) " + return "(" + expressionSQLs.joined(separator: joiner) + ")" + } + + func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinaryOperatorChain { + return SQLExpressionBinaryOperatorChain( + op: op, + expressions: expressions.map { $0.qualified(by: qualifier) }) + } +} + // MARK: - SQLExpressionContains /// SQLExpressionContains is an expression that checks the inclusion of a diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 257269eea..4f9f4ce35 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -23,6 +23,48 @@ public protocol SQLSelectable { func qualified(by qualifier: SQLTableQualifier) -> Self } +// MARK: - SQLSelectionLiteral + +struct SQLSelectionLiteral : SQLSelectable { + let sql: String + let arguments: StatementArguments? + + init(_ sql: String, arguments: StatementArguments? = nil) { + self.sql = sql + self.arguments = arguments + } + + func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + if let literalArguments = self.arguments { + guard arguments != nil else { + // GRDB limitation: we don't know how to look for `?` in sql and + // replace them with with literals. + fatalError("Not implemented") + } + arguments! += literalArguments + } + return sql + } + + func countedSQL(_ arguments: inout StatementArguments?) -> String { + fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func count(distinct: Bool) -> SQLCount? { + fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func columnCount(_ db: Database) throws -> Int { + fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") + } + + func qualified(by qualifier: SQLTableQualifier) -> SQLSelectionLiteral { + return self + } +} + +// MARK: - SQLTableQualifier + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 52b704542..49c3d8d41 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -360,7 +360,9 @@ public final class TableDefinition { /// /// - parameter sql: An SQL snippet public func check(sql: String) { - checkConstraints.append(SQLExpressionLiteral(sql)) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + checkConstraints.append(expression) } fileprivate func sql(_ db: Database) throws -> String { @@ -663,7 +665,9 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func check(sql: String) -> Self { - checkConstraints.append(SQLExpressionLiteral(sql)) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + checkConstraints.append(expression) return self } @@ -695,7 +699,9 @@ public final class ColumnDefinition { /// - returns: Self so that you can further refine the column definition. @discardableResult public func defaults(sql: String) -> Self { - defaultExpression = SQLExpressionLiteral(sql) + var expression = SQLExpressionLiteral(sql) + expression.unsafeRaw = true // It's safe because this expression can't be composed with others + defaultExpression = expression return self } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 0018216b0..d03e81f71 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -94,6 +94,8 @@ 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667061D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667071D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; }; + 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */; }; 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD001DAA8ACA0056AF8C /* FTS5CustomTokenizerTests.swift */; }; 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; }; 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; }; @@ -845,6 +847,7 @@ 560FC5501CB004AD0014AA8E /* sqlcipher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = sqlcipher.xcodeproj; path = SQLCipher/src/sqlcipher.xcodeproj; sourceTree = ""; }; 560FC5B01CB00B880014AA8E /* GRDBCipherOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -1325,6 +1328,7 @@ 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -1977,6 +1981,7 @@ files = ( 56873BED1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3E1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5616AAF9207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9BD1D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -2368,6 +2373,7 @@ files = ( 56873BF01F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D411DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5616AAFA207CD5A900AC3664 /* RequestProtocols.swift in Sources */, 5636E9C01D22574100B9B05F /* FetchRequest.swift in Sources */, 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -2827,7 +2833,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2864,7 +2869,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2901,7 +2905,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipherOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2952,7 +2955,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -2990,7 +2992,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3027,7 +3028,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCipheriOSEncryptedTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -3127,7 +3127,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ec5d7b610..d96f277b3 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -10,6 +10,8 @@ 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 561667041D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; 561667081D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */; }; + 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; + 5616AAF7207CD59400AC3664 /* RequestProtocols.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */; }; 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; }; 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; }; @@ -548,6 +550,7 @@ 560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = ""; }; 560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = ""; }; 561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = ""; }; + 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -1001,6 +1004,7 @@ 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, @@ -1682,6 +1686,7 @@ files = ( 56873BF11F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5616AAF7207CD59400AC3664 /* RequestProtocols.swift in Sources */, 5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -1927,6 +1932,7 @@ files = ( 56873BEE1F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5616AAF6207CD59400AC3664 /* RequestProtocols.swift in Sources */, 5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */, F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, @@ -2287,7 +2293,6 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; @@ -2344,7 +2349,6 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SDKROOT = iphoneos; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -2382,7 +2386,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLite.GRDBCustomSQLiteiOSTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2431,7 +2434,6 @@ INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; SKIP_INSTALL = YES; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; @@ -2470,7 +2472,6 @@ PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCustomSQLiteOSXTests; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; }; name = Release; From b9333fab340f4eb922f06a3ec76b4ed6966b35fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 10 Apr 2018 13:45:31 +0200 Subject: [PATCH 055/348] Update a few tests that have been broken by 64899e5a399fdf4821221bbc5e6c5bfc1ff1b867. (Some expressions which were not safely wrapped inside parenthesis now are wrapped inside parenthesis) --- .../MutablePersistableRecordDeleteTests.swift | 2 +- .../GRDBTests/QueryInterfaceExtensibilityTests.swift | 2 +- Tests/GRDBTests/QueryInterfaceRequestTests.swift | 12 ++++++------ .../TableRecord+QueryInterfaceRequestTests.swift | 6 +++--- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index 011927b1c..bee0a4c0d 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -151,7 +151,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (\"name\" = 'Arthur')") try Person.filter(sql: "id = 1").deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1") + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1)") try Person.select(Column("name")).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index 269d89fe0..b415dd871 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -112,7 +112,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { default: XCTFail("Expected data blob") } - XCTAssertEqual(self.lastSQLQuery, "SELECT CAST(\"text\" AS BLOB) FROM \"records\"") + XCTAssertEqual(self.lastSQLQuery, "SELECT (CAST(\"text\" AS BLOB)) FROM \"records\"") } } } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 00fdf0f94..f1d71d783 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -237,21 +237,21 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> 1")), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> ?", arguments: [1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.filter(sql: "id <> :id", arguments: ["id": 1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilter() throws { @@ -316,21 +316,21 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > 18")), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHavingLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > ?", arguments: [18])), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHavingLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > :age", arguments: ["age": 18])), - "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (min(age) > 18)") } func testHaving() throws { diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 6448b5ad6..7e6845684 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -166,21 +166,21 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> 1")), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> ?", arguments: [1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilterLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, Reader.filter(sql: "id <> :id", arguments: ["id": 1])), - "SELECT * FROM \"readers\" WHERE id <> 1") + "SELECT * FROM \"readers\" WHERE (id <> 1)") } func testFilter() throws { From c34380cf5c6a19f1e2da0610d292a04490a35c22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 08:19:15 +0200 Subject: [PATCH 056/348] SQLExpression and SQLSelectable are no longer PATs --- GRDB/Core/DatabaseValue.swift | 17 +++--- GRDB/QueryInterface/Column.swift | 4 +- .../SQLExpression+QueryInterface.swift | 52 +++++++++---------- GRDB/QueryInterface/SQLExpression.swift | 16 +++++- .../SQLSelectable+QueryInterface.swift | 6 +-- GRDB/QueryInterface/SQLSelectable.swift | 4 +- GRDB/Record/TableRecord.swift | 4 +- 7 files changed, 53 insertions(+), 50 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index cfb32ef97..b19c2b9fc 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -204,17 +204,6 @@ extension DatabaseValue { } } -// MARK: - SQLSelectable - -extension DatabaseValue { - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// - /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> DatabaseValue { - return self - } -} - // MARK: - Lossless conversions extension DatabaseValue { @@ -360,6 +349,12 @@ extension DatabaseValue { return SQLExpressionNot(self) } } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return self + } } // CustomStringConvertible diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 5740c0464..337cd2107 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -16,7 +16,6 @@ public struct Column : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { if let qualifierName = qualifier?.name { @@ -26,9 +25,8 @@ public struct Column : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> Column { + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { if self.qualifier != nil { // Never requalify return self diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 187214a06..ee48475f6 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -65,7 +65,6 @@ public struct SQLExpressionLiteral : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { if let literalArguments = self.arguments { @@ -84,9 +83,8 @@ public struct SQLExpressionLiteral : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionLiteral { + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return self } } @@ -166,17 +164,15 @@ public struct SQLExpressionUnary : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionUnary { - return SQLExpressionUnary(op, expression.qualified(by: qualifier)) + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionUnary(op, expression.qualifiedExpression(with: qualifier)) } } @@ -285,11 +281,13 @@ public struct SQLExpressionBinary : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: public var negated: SQLExpression { if let negatedOp = op.negated { return SQLExpressionBinary(negatedOp, lhs, rhs) @@ -299,6 +297,7 @@ public struct SQLExpressionBinary : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: public func matchedRowIds(rowIdName: String?) -> Set? { switch op { case .equal, .is: @@ -349,10 +348,9 @@ public struct SQLExpressionBinary : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinary { - return SQLExpressionBinary(op, lhs.qualified(by: qualifier), rhs.qualified(by: qualifier)) + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionBinary(op, lhs.qualifiedExpression(with: qualifier), rhs.qualifiedExpression(with: qualifier)) } } @@ -375,10 +373,10 @@ struct SQLExpressionBinaryOperatorChain : SQLExpression { return "(" + expressionSQLs.joined(separator: joiner) + ")" } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBinaryOperatorChain { + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionBinaryOperatorChain( op: op, - expressions: expressions.map { $0.qualified(by: qualifier) }) + expressions: expressions.map { $0.qualifiedExpression(with: qualifier) }) } } @@ -440,8 +438,8 @@ struct SQLExpressionContains : SQLExpression { return rowIDs } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionContains { - return SQLExpressionContains(expression.qualified(by: qualifier), collection, negated: isNegated) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionContains(expression.qualifiedExpression(with: qualifier), collection, negated: isNegated) } } @@ -479,11 +477,11 @@ struct SQLExpressionBetween : SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionBetween { + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionBetween( - expression.qualified(by: qualifier), - lowerBound.qualified(by: qualifier), - upperBound.qualified(by: qualifier), + expression.qualifiedExpression(with: qualifier), + lowerBound.qualifiedExpression(with: qualifier), + upperBound.qualifiedExpression(with: qualifier), negated: isNegated) } } @@ -570,15 +568,15 @@ public struct SQLExpressionFunction : SQLExpression { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionFunction { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualified(by: qualifier) }) + public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: qualifier) }) } } @@ -600,8 +598,8 @@ struct SQLExpressionCount : SQLExpression { return "COUNT(" + counted.countedSQL(&arguments) + ")" } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCount { - return SQLExpressionCount(counted.qualified(by: qualifier)) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionCount(counted.qualifiedSelectable(with: qualifier)) } } @@ -622,8 +620,8 @@ struct SQLExpressionCountDistinct : SQLExpression { return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")" } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCountDistinct { - return SQLExpressionCountDistinct(counted.qualified(by: qualifier)) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionCountDistinct(counted.qualifiedExpression(with: qualifier)) } } @@ -651,7 +649,7 @@ struct SQLExpressionCollate : SQLExpression { } } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionCollate { - return SQLExpressionCollate(expression.qualified(by: qualifier), collationName: collationName) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionCollate(expression.qualifiedExpression(with: qualifier), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index 9922a669c..3aa9d989c 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -60,6 +60,9 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// /// Returns the rowIds matched by the expression. func matchedRowIds(rowIdName: String?) -> Set? // TODO: this method should take SQLTableQualifier in account + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression } extension SQLExpression { @@ -84,6 +87,15 @@ extension SQLExpression { public func matchedRowIds(rowIdName: String?) -> Set? { return nil } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The default implementation returns qualifiedExpression(with:) + /// + /// :nodoc: + public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + return qualifiedExpression(with: qualifier) + } } // SQLExpression: SQLExpressible @@ -137,7 +149,7 @@ struct SQLExpressionNot : SQLExpression { return expression } - func qualified(by qualifier: SQLTableQualifier) -> SQLExpressionNot { - return SQLExpressionNot(expression.qualified(by: qualifier)) + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionNot(expression.qualifiedExpression(with: qualifier)) } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 8791b3edc..2badcf7ff 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -65,7 +65,7 @@ extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: - public func qualified(by qualifier: SQLTableQualifier) -> AllColumns { + public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { if self.qualifier != nil { // Never requalify return self @@ -110,8 +110,8 @@ struct SQLAliasedExpression : SQLSelectable { return expression.count(distinct: distinct) } - func qualified(by qualifier: SQLTableQualifier) -> SQLAliasedExpression { - return SQLAliasedExpression(expression.qualified(by: qualifier), alias: alias) + func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + return SQLAliasedExpression(expression.qualifiedExpression(with: qualifier), alias: alias) } func columnCount(_ db: Database) throws -> Int { diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 4f9f4ce35..48dd59720 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -20,7 +20,7 @@ public protocol SQLSelectable { func columnCount(_ db: Database) throws -> Int /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualified(by qualifier: SQLTableQualifier) -> Self + func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable } // MARK: - SQLSelectionLiteral @@ -58,7 +58,7 @@ struct SQLSelectionLiteral : SQLSelectable { fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") } - func qualified(by qualifier: SQLTableQualifier) -> SQLSelectionLiteral { + func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { return self } } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index c45dd7f5e..a24c21c7e 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -87,7 +87,7 @@ extension TableRecord { /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" public static func selectionSQL(alias: String? = nil) -> String { let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName) - let selection = databaseSelection.map { $0.qualified(by: qualifier) } + let selection = databaseSelection.map { $0.qualifiedSelectable(with: qualifier) } var arguments: StatementArguments? = nil return selection .map { $0.resultColumnSQL(&arguments) } @@ -115,7 +115,7 @@ extension TableRecord { public static func numberOfSelectedColumns(_ db: Database) throws -> Int { let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) return try databaseSelection - .map { try $0.qualified(by: qualifier).columnCount(db) } + .map { try $0.qualifiedSelectable(with: qualifier).columnCount(db) } .reduce(0, +) } } From 79c7dd03a56b66c007712cdd2c38c0a273bd7e01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 13:10:15 +0200 Subject: [PATCH 057/348] [Whitespace] --- GRDB/Core/RowAdapter.swift | 7 ------- GRDB/QueryInterface/SQLCollatedExpression.swift | 2 -- GRDB/QueryInterface/SQLExpressible.swift | 6 ------ GRDB/QueryInterface/SQLExpression.swift | 2 -- GRDB/QueryInterface/SQLSelectable+QueryInterface.swift | 5 ----- GRDB/Utils/Utils.swift | 2 -- 6 files changed, 24 deletions(-) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index fdc7775ee..bfbc5be62 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -173,14 +173,12 @@ public protocol RowLayout { extension SelectStatement : RowLayout { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var layoutColumns: [(Int, String)] { return Array(columnNames.enumerated()) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutIndex(ofColumn name: String) -> Int? { return index(ofColumn: name) @@ -255,7 +253,6 @@ public struct EmptyRowAdapter: RowAdapter { public init() { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: []) @@ -280,7 +277,6 @@ public struct ColumnMapping : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutColumns = try mapping @@ -318,7 +314,6 @@ public struct SuffixRowAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns.suffix(from: index)) @@ -349,7 +344,6 @@ public struct RangeRowAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { return LayoutedColumnMapping(layoutColumns: layout.layoutColumns[range]) @@ -427,7 +421,6 @@ public struct ScopeAdapter : RowAdapter { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter { let layoutedAdapter = try base.layoutedAdapter(from: layout) diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 492f625cc..3266580c0 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -51,14 +51,12 @@ public struct SQLCollatedExpression { extension SQLCollatedExpression : SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var reversed: SQLOrderingTerm { return desc } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.orderingTermSQL(&arguments) diff --git a/GRDB/QueryInterface/SQLExpressible.swift b/GRDB/QueryInterface/SQLExpressible.swift index 1991a8a66..9d7aa31db 100644 --- a/GRDB/QueryInterface/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQLExpressible.swift @@ -57,14 +57,12 @@ public protocol SQLSpecificExpressible : SQLExpressible { extension SQLExpressible where Self: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var reversed: SQLOrderingTerm { return SQLOrdering.desc(sqlExpression) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.expressionSQL(&arguments) @@ -76,28 +74,24 @@ extension SQLExpressible where Self: SQLOrderingTerm { extension SQLExpressible where Self: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.expressionSQL(&arguments) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func countedSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.expressionSQL(&arguments) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { return sqlExpression.count(distinct: distinct) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func columnCount(_ db: Database) throws -> Int { return 1 diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index 3aa9d989c..b41be52db 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -103,7 +103,6 @@ extension SQLExpression { extension SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public var sqlExpression: SQLExpression { return self @@ -115,7 +114,6 @@ extension SQLExpression { extension SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { if distinct { diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 2badcf7ff..4245a28c3 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -23,7 +23,6 @@ public struct AllColumns { extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { if let qualifierName = qualifier?.name { @@ -33,7 +32,6 @@ extension AllColumns : SQLSelectable { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func countedSQL(_ arguments: inout StatementArguments?) -> String { guard qualifier == nil else { @@ -44,7 +42,6 @@ extension AllColumns : SQLSelectable { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func count(distinct: Bool) -> SQLCount? { // SELECT DISTINCT * FROM tableName ... @@ -63,7 +60,6 @@ extension AllColumns : SQLSelectable { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { if self.qualifier != nil { @@ -76,7 +72,6 @@ extension AllColumns : SQLSelectable { } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public func columnCount(_ db: Database) throws -> Int { guard let qualifier = qualifier else { diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 26cbb66d7..8766e852c 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -27,7 +27,6 @@ public func databaseQuestionMarks(count: Int) -> String { /// :nodoc: public protocol _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: associatedtype _Wrapped } @@ -39,7 +38,6 @@ public protocol _OptionalProtocol { /// :nodoc: extension Optional : _OptionalProtocol { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// /// :nodoc: public typealias _Wrapped = Wrapped } From 9c6b48980c3231bfce6e27758ffb3134906513f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 13:18:34 +0200 Subject: [PATCH 058/348] Database.isInsideTransaction: add missing dispatch queue check --- GRDB/Core/Database.swift | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ad48f304e..65bdbbc51 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -98,8 +98,6 @@ public final class Database { /// True if the database connection is currently in a transaction. public var isInsideTransaction: Bool { - if isClosed { return false } - // https://sqlite.org/c3ref/get_autocommit.html // // > The sqlite3_get_autocommit() interface returns non-zero or zero if @@ -109,6 +107,12 @@ public final class Database { // > Autocommit mode is on by default. Autocommit mode is disabled by a // > BEGIN statement. Autocommit mode is re-enabled by a COMMIT // > or ROLLBACK. + // + // > If another thread changes the autocommit status of the database + // > connection while this routine is running, then the return value + // > is undefined. + SchedulingWatchdog.preconditionValidQueue(self) + if isClosed { return false } // Support for SerializedDatabasae.deinit return sqlite3_get_autocommit(sqliteConnection) == 0 } From 07a1d4d1b8a5c89ef4727dc18f415368d20e46f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 13:21:56 +0200 Subject: [PATCH 059/348] Database.rollback: add missing dispatch queue check --- GRDB/Core/Database.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 65bdbbc51..25cb95f78 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -728,6 +728,7 @@ extension Database { // The second technique is more robust, because we don't have to guess // which rollback errors should be ignored, and which rollback errors // should be exposed to the library user. + SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit if sqlite3_get_autocommit(sqliteConnection) == 0 { try execute("ROLLBACK TRANSACTION") } From fa68b62be10b857bff008e05c538b0d07d5048e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 13:39:44 +0200 Subject: [PATCH 060/348] Improve Row.description & Row.debugDescription --- GRDB/Core/DatabaseValue.swift | 2 +- GRDB/Core/Row.swift | 65 ++++++++++++++++--- GRDB/Core/RowAdapter.swift | 8 ++- Tests/GRDBTests/DatabaseValueTests.swift | 2 +- Tests/GRDBTests/RowAdapterTests.swift | 38 +++++++++++ .../RowCopiedFromStatementTests.swift | 9 +++ .../RowFromDictionaryLiteralTests.swift | 6 ++ Tests/GRDBTests/RowFromDictionaryTests.swift | 8 +++ Tests/GRDBTests/RowFromStatementTests.swift | 14 ++++ 9 files changed, 139 insertions(+), 13 deletions(-) diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index b19c2b9fc..7f4603cf4 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -371,7 +371,7 @@ extension DatabaseValue { case .string(let string): return String(reflecting: string) case .blob(let data): - return data.description + return "Data(\(data.description))" } } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 4c9678165..5ef3922de 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -6,7 +6,7 @@ import Foundation #endif /// A database row. -public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible { +public final class Row : Equatable, Hashable, RandomAccessCollection, ExpressibleByDictionaryLiteral, CustomStringConvertible, CustomDebugStringConvertible { let impl: RowImpl /// Unless we are producing a row array, we use a single row when iterating @@ -541,11 +541,27 @@ extension Row { return impl.scoped(on: name) } - /// Returns a copy of the row, without any scoped row (if the row was fetched - /// with a row adapter that defines scopes). + /// Returns a copy of the row, without any scopes. + /// + /// This property can turn out useful when you want to test the content of + /// adapted rows, such as rows fetched from joined requests. + /// + /// let row = ... + /// // Failure because row equality tests for row scopes: + /// XCTAssertEqual(row, ["id": 1, "name": "foo"]) + /// // Success: + /// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"]) public var unscoped: Row { return Row(impl: ArrayRowImpl(columns: map { ($0, $1) })) } + + /// Return the raw row fetched from the database. + /// + /// This property can turn out useful when you debug the consumption of + /// adapted rows, such as rows fetched from joined requests. + public var unadapted: Row { + return impl.unadaptedRow + } } /// A cursor of database rows. For example: @@ -874,15 +890,41 @@ extension Row { } } -// CustomStringConvertible +// CustomStringConvertible & CustomDebugStringConvertible extension Row { /// :nodoc: public var description: String { - return "" + return "[" + + map { (column, dbValue) in "\(column):\(dbValue)" }.joined(separator: " ") + + "]" + } + + /// :nodoc: + public var debugDescription: String { + return debugDescription(level: 0) + } + + private func debugDescription(level: Int) -> String { + if level == 0 && self == self.unadapted { + return description + } + let prefix = repeatElement(" ", count: level + 1).joined(separator: "") + var str = "" + if level == 0 { + str = "▿ " + description + let unadapted = self.unadapted + if self != unadapted { + str += "\n" + prefix + "unadapted: " + unadapted.description + } + } else { + str = description + } + for scope in scopeNames.sorted() { + let scopedRow = scoped(on: scope)! + str += "\n" + prefix + "- " + scope + ": " + scopedRow.debugDescription(level: level + 1) + } + + return str } } @@ -928,6 +970,7 @@ extension RowIndex { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } + var unadaptedRow: Row { get } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue func fastValue(atUncheckedIndex index: Int) -> Value func fastValue(atUncheckedIndex index: Int) -> Value? @@ -947,6 +990,10 @@ protocol RowImpl { } extension RowImpl { + var unadaptedRow: Row { + return Row(impl: self) + } + func hasNull(atUncheckedIndex index:Int) -> Bool { return databaseValue(atUncheckedIndex: index).isNull } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index bfbc5be62..68f9bedfe 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -452,7 +452,7 @@ struct ChainedAdapter : RowAdapter { extension Row { /// Creates a row from a base row and a statement adapter convenience init(base: Row, adapter: LayoutedRowAdapter) { - self.init(impl: AdapterRowImpl(base: base, adapter: adapter)) + self.init(impl: AdaptedRowImpl(base: base, adapter: adapter)) } /// Returns self if adapter is nil @@ -464,7 +464,7 @@ extension Row { } } -struct AdapterRowImpl : RowImpl { +struct AdaptedRowImpl : RowImpl { let base: Row let adapter: LayoutedRowAdapter let mapping: LayoutedColumnMapping @@ -475,6 +475,10 @@ struct AdapterRowImpl : RowImpl { self.mapping = adapter.mapping } + var unadaptedRow: Row { + return base.unadapted + } + var count: Int { return mapping.layoutColumns.count } diff --git a/Tests/GRDBTests/DatabaseValueTests.swift b/Tests/GRDBTests/DatabaseValueTests.swift index ecce04100..2db3b009a 100644 --- a/Tests/GRDBTests/DatabaseValueTests.swift +++ b/Tests/GRDBTests/DatabaseValueTests.swift @@ -120,6 +120,6 @@ class DatabaseValueTests: GRDBTestCase { XCTAssertEqual(databaseValue_Int64.description, "1") XCTAssertEqual(databaseValue_Double.description, "100000.1") XCTAssertEqual(databaseValue_String.description, "\"foo\\n\\t\\r\"") - XCTAssertEqual(databaseValue_Data.description, "3 bytes") // may be fragile + XCTAssertEqual(databaseValue_Data.description, "Data(3 bytes)") // may be fragile } } diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index ac079ff3a..5d86741ef 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -712,4 +712,42 @@ class AdapterRowTests : RowTestCase { } } } + + func testDescription() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let adapter = ColumnMapping(["id": "id0", "val": "val0"]) + .addingScopes([ + "a": ColumnMapping(["id": "id1", "val": "val1"]) + .addingScopes([ + "b": ColumnMapping(["id": "id2", "val": "val2"]) + .addingScopes([ + "c": SuffixRowAdapter(fromIndex:4)]), + "a": SuffixRowAdapter(fromIndex:0)]), + "b": ColumnMapping(["id": "id1", "val": "val1"]) + .addingScopes([ + "ba": ColumnMapping(["id": "id2", "val": "val2"])])]) + let row = try Row.fetchOne(db, "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! + + XCTAssertEqual(row.description, "[id:0 val:\"foo0\"]") + XCTAssertEqual(row.debugDescription, """ + ▿ [id:0 val:"foo0"] + unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - a: [id:1 val:"foo1"] + - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - b: [id:2 val:"foo2"] + - c: [id2:2 val2:"foo2"] + - b: [id:1 val:"foo1"] + - ba: [id:2 val:"foo2"] + """) + XCTAssertEqual(row.scoped(on: "a")!.description, "[id:1 val:\"foo1\"]") + XCTAssertEqual(row.scoped(on: "a")!.debugDescription, """ + ▿ [id:1 val:"foo1"] + unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] + - b: [id:2 val:"foo2"] + - c: [id2:2 val2:"foo2"] + """) + } + } } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 10dff1794..8767a074b 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -279,4 +279,13 @@ class RowCopiedFromStatementTests: RowTestCase { XCTAssertEqual(row, copiedRow) } } + + func testDescription() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let row = try Row.fetchOne(db, "SELECT NULL AS \"null\", 1 AS \"int\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"data\"")! + XCTAssertEqual(row.description, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + } + } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index a542768e8..36f72601c 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -227,4 +227,10 @@ class RowFromDictionaryLiteralTests : RowTestCase { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } + + func testDescription() throws { + let row: Row = ["a": 0, "b": 1, "c": 2] + XCTAssertEqual(row.description, "[a:0 b:1 c:2]") + XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]") + } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 79e457852..bfdc2bb76 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -217,4 +217,12 @@ class RowFromDictionaryTests : RowTestCase { let copiedRow = row.copy() XCTAssertEqual(row, copiedRow) } + + func testDescription() throws { + let row = Row(["a": 0, "b": "foo"]) + let variants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] + XCTAssert(variants.contains(row.description)) + let debugVariants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] + XCTAssert(debugVariants.contains(row.debugDescription)) + } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 69ca661e5..556151428 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -367,4 +367,18 @@ class RowFromStatementTests : RowTestCase { XCTAssertTrue(try values.next() == nil) } } + + func testDescription() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try Row.fetchCursor(db, "SELECT NULL AS \"null\", 1 AS \"int\", 1.1 AS \"double\", 'foo' AS \"string\", x'53514C697465' AS \"data\"") + var rowFetched = false + while let row = try rows.next() { + rowFetched = true + XCTAssertEqual(row.description, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") + } + XCTAssertTrue(rowFetched) + } + } } From 26912e746b35943254461a654e0107500fbf657c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 15:49:16 +0200 Subject: [PATCH 061/348] Update documentation for new Row description format --- GRDB/Core/Database+Schema.swift | 2 +- GRDB/Core/Row.swift | 2 +- GRDB/Core/RowAdapter.swift | 12 ++++++------ GRDB/Core/Statement.swift | 2 +- README.md | 32 ++++++++++++++++---------------- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 4c053acb5..7ac80ece1 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -193,7 +193,7 @@ extension Database { var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = [] var previousId: Int? = nil for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") { - // row = + // row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."] let id: Int = row[0] let seq: Int = row[1] let table: String = row[2] diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 5ef3922de..77abae6bc 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -804,7 +804,7 @@ extension Row { /// /// let row: Row = ["foo": 1, "foo": "bar", "baz": nil] /// print(row) - /// // Prints + /// // Prints [foo:1 foo:"bar" baz:NULL] public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) { self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) })) } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 68f9bedfe..014d97f88 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -77,7 +77,7 @@ public struct LayoutedColumnMapping { /// } /// } /// - /// // + /// // [foo:"foo" bar: "bar"] /// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) public init(layoutColumns: S) where S.Iterator.Element == (Int, String) { self.layoutColumns = Array(layoutColumns) @@ -200,7 +200,7 @@ extension SelectStatement : RowLayout { /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// -/// // +/// // [baz:3] /// try Row.fetchOne(db, sql, adapter: adapter) public protocol RowAdapter { @@ -223,7 +223,7 @@ public protocol RowAdapter { /// } /// } /// - /// // + /// // [foo:1] /// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter()) func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter } @@ -264,7 +264,7 @@ public struct EmptyRowAdapter: RowAdapter { /// let adapter = ColumnMapping(["foo": "bar"]) /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz" /// -/// // +/// // [foo:"bar"] /// try Row.fetchOne(db, sql, adapter: adapter) public struct ColumnMapping : RowAdapter { /// A dictionary from mapped column names to column names in a base row. @@ -298,7 +298,7 @@ public struct ColumnMapping : RowAdapter { /// let adapter = SuffixRowAdapter(fromIndex: 2) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// -/// // +/// // [baz:3] /// try Row.fetchOne(db, sql, adapter: adapter) public struct SuffixRowAdapter : RowAdapter { /// The suffix index @@ -325,7 +325,7 @@ public struct SuffixRowAdapter : RowAdapter { /// let adapter = RangeRowAdapter(1..<3) /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux" /// -/// // +/// // [bar:2 baz: 3] /// try Row.fetchOne(db, sql, adapter: adapter) public struct RangeRowAdapter : RowAdapter { /// The range diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index b5bfa0dc1..c84ac6e1e 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -584,7 +584,7 @@ extension UpdateStatement: AuthorizedStatement { } /// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar" /// let row = try Row.fetchOne(db, sql, arguments: [1, 2, "bar"] + ["foo": "foo"])! /// print(row) -/// // Prints +/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"] public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { var values: [DatabaseValue] = [] var namedValues: [String: DatabaseValue] = [:] diff --git a/README.md b/README.md index f4541e5c9..c7db629b2 100644 --- a/README.md +++ b/README.md @@ -1634,14 +1634,14 @@ try db.create(table: "players") { t in t.column("name", .text) } -// +// [type:"table" name:"players" tbl_name:"players" rootpage:2 +// sql:"CREATE TABLE players(id INTEGER PRIMARY KEY, name TEXT)"] for row in try Row.fetchAll(db, "SELECT * FROM sqlite_master") { print(row) } -// -// +// [cid:0 name:"id" type:"INTEGER" notnull:0 dflt_value:NULL pk:1] +// [cid:1 name:"name" type:"TEXT" notnull:0 dflt_value:NULL pk:0] for row in try Row.fetchAll(db, "PRAGMA table_info('players')") { print(row) } @@ -1687,7 +1687,7 @@ To see how row adapters can be used, see [Joined Queries Support](#joined-querie ColumnMapping renames columns. Build one with a dictionary whose keys are adapted column names, and values the column names in the raw row: ```swift -// +// [newName:"Hello"] let adapter = ColumnMapping(["newName": "oldName"]) let row = try Row.fetchOne(db, "SELECT 'Hello' AS oldName", adapter: adapter)! ``` @@ -1697,7 +1697,7 @@ let row = try Row.fetchOne(db, "SELECT 'Hello' AS oldName", adapter: adapter)! `SuffixRowAdapter` hides the first columns in a row: ```swift -// +// [b:1 c:2] let adapter = SuffixRowAdapter(fromIndex: 1) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)! ``` @@ -1707,7 +1707,7 @@ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter `RangeRowAdapter` only exposes a range of columns. ```swift -// +// [b:1] let adapter = RangeRowAdapter(1..<2) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter)! ``` @@ -1739,9 +1739,9 @@ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access with the `Row.scoped(on:)` method. This method returns an optional Row, which is nil if the scope is missing. ```swift -row // -row.scoped(on: "left") // -row.scoped(on: "right") // +row // [a:0 b:1 c:2 d:3] +row.scoped(on: "left") // [a:0 b:1] +row.scoped(on: "right") // [c:2 d:3] row.scoped(on: "missing") // nil ``` @@ -1759,12 +1759,12 @@ let adapter = ScopeAdapter([ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! let leftRow = row.scoped(on: "left")! -leftRow.scoped(on: "left") // -leftRow.scoped(on: "right") // +leftRow.scoped(on: "left") // [a:0] +leftRow.scoped(on: "right") // [b:1] let rightRow = row.scoped(on: "right")! -rightRow.scoped(on: "left") // -rightRow.scoped(on: "right") // +rightRow.scoped(on: "left") // [c:2] +rightRow.scoped(on: "right") // [d:3] ``` Any adapter can be extended with scopes: @@ -1775,8 +1775,8 @@ let adapter = ScopeAdapter(base: baseAdapter, scopes: [ "remainder": SuffixRowAdapter(fromIndex: 2)]) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! -row // -row.scoped(on: "remainder") // +row // [a:0 b:1] +row.scoped(on: "remainder") // [c:2 d:3] ``` From 78e6241d16c0a443f7b61f3bd1c1d2c0699e15d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 17:31:11 +0200 Subject: [PATCH 062/348] DatabaseWriter.write now guarantees that eventual concurrent readers don't see any changes until all changes are executed. DatabasePool.write thus wraps changes in a transaction. --- GRDB/Core/DatabasePool.swift | 32 ++++++++++++++++---------------- GRDB/Core/DatabaseWriter.swift | 9 +++++++++ 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index ade0ad076..fc0879e08 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -422,7 +422,7 @@ extension DatabasePool : DatabaseWriter { // MARK: - Writing in Database /// Synchronously executes an update block in a protected dispatch queue, - /// and returns its result. + /// wrapped inside a transaction, and returns the result of the block. /// /// Eventual concurrent database updates are postponed until the block /// has executed. @@ -431,9 +431,8 @@ extension DatabasePool : DatabaseWriter { /// try db.execute(...) /// } /// - /// To maintain database integrity, and preserve eventual concurrent reads - /// from seeing an inconsistent database state, prefer the - /// writeInTransaction method. + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. /// /// This method is *not* reentrant. /// @@ -441,7 +440,14 @@ extension DatabasePool : DatabaseWriter { /// either .commit or .rollback. /// - throws: The error thrown by the block. public func write(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) + return try writer.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } } /// Synchronously executes a block in a protected dispatch queue, wrapped @@ -459,17 +465,8 @@ extension DatabasePool : DatabaseWriter { /// return .commit /// } /// - /// Eventual concurrent readers do not see partial changes: - /// - /// dbPool.writeInTransaction { db in - /// // Eventually preserve a zero balance - /// try db.execute(db, "INSERT INTO credits ...", arguments: [amount]) - /// try db.execute(db, "INSERT INTO debits ...", arguments: [amount]) - /// } - /// - /// dbPool.read { db in - /// // Here the balance is guaranteed to be zero - /// } + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. /// /// This method is *not* reentrant. /// @@ -500,6 +497,9 @@ extension DatabasePool : DatabaseWriter { /// try db.execute(...) /// } /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index 5c5c1b003..cb8ce5fc0 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -23,6 +23,12 @@ public protocol DatabaseWriter : DatabaseReader { /// Eventual concurrent database updates are postponed until the block /// has executed. /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// The block may, or may not, be wrapped inside a transaction, depending on + /// the concrete DatabaseWriter type. + /// /// This method is *not* reentrant. func write(_ block: (Database) throws -> T) rethrows -> T @@ -32,6 +38,9 @@ public protocol DatabaseWriter : DatabaseReader { /// Eventual concurrent database updates are postponed until the block /// has executed. /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// /// This method is reentrant. It should be avoided because it fosters /// dangerous concurrency practices. func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T From 563a4d5c7197fc21f64c834622d33c9c8ab6e381 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 11 Apr 2018 18:26:07 +0200 Subject: [PATCH 063/348] Introduce DatabaseWriter.writeWithoutTransaction --- GRDB/Core/DatabasePool.swift | 34 +++++++++++++++---- GRDB/Core/DatabaseQueue.swift | 7 ++++ GRDB/Core/DatabaseWriter.swift | 30 ++++++++++++---- GRDB/Record/FetchedRecordsController.swift | 4 +-- .../GRDBTests/CompilationProtocolTests.swift | 1 + .../DatabasePoolSchemaCacheTests.swift | 2 +- 6 files changed, 62 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index fc0879e08..82f964260 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -142,7 +142,7 @@ extension DatabasePool { /// See also setupMemoryManagement(application:) public func releaseMemory() { // TODO: test that this method blocks the current thread until all database accesses are completed. - write { $0.releaseMemory() } + writeWithoutTransaction { $0.releaseMemory() } readerPool.forEach { reader in reader.sync { $0.releaseMemory() } } @@ -373,7 +373,7 @@ extension DatabasePool : DatabaseReader { /// } public func add(function: DatabaseFunction) { functions.update(with: function) - write { $0.add(function: function) } + writeWithoutTransaction { $0.add(function: function) } readerPool.forEach { reader in reader.sync { $0.add(function: function) } } @@ -382,7 +382,7 @@ extension DatabasePool : DatabaseReader { /// Remove an SQL function. public func remove(function: DatabaseFunction) { functions.remove(function) - write { $0.remove(function: function) } + writeWithoutTransaction { $0.remove(function: function) } readerPool.forEach { reader in reader.sync { $0.remove(function: function) } } @@ -401,7 +401,7 @@ extension DatabasePool : DatabaseReader { /// } public func add(collation: DatabaseCollation) { collations.update(with: collation) - write { $0.add(collation: collation) } + writeWithoutTransaction { $0.add(collation: collation) } readerPool.forEach { reader in reader.sync { $0.add(collation: collation) } } @@ -410,7 +410,7 @@ extension DatabasePool : DatabaseReader { /// Remove a collation. public func remove(collation: DatabaseCollation) { collations.remove(collation) - write { $0.remove(collation: collation) } + writeWithoutTransaction { $0.remove(collation: collation) } readerPool.forEach { reader in reader.sync { $0.remove(collation: collation) } } @@ -438,8 +438,8 @@ extension DatabasePool : DatabaseWriter { /// /// - parameters block: A block that executes SQL statements and return /// either .commit or .rollback. - /// - throws: The error thrown by the block. - public func write(_ block: (Database) throws -> T) rethrows -> T { + /// - throws: The error thrown by the block, or by the wrapping transaction. + public func write(_ block: (Database) throws -> T) throws -> T { return try writer.sync { db in var result: T? = nil try db.inTransaction { @@ -450,6 +450,26 @@ extension DatabasePool : DatabaseWriter { } } + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// The block is guaranteed to be executed outside of a transaction. + /// + /// This method is *not* reentrant. + /// + /// - parameters block: A block that executes SQL statements and return + /// either .commit or .rollback. + /// - throws: The error thrown by the block. + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + /// Synchronously executes a block in a protected dispatch queue, wrapped /// inside a transaction. /// diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 6d69228f3..4ebf2d88d 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -294,6 +294,13 @@ extension DatabaseQueue : DatabaseWriter { return try inDatabase(block) } + /// Alias for `inDatabase`. See `DatabaseWriter.writeWithoutTransaction`. + /// + /// :nodoc: + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try inDatabase(block) + } + /// Synchronously executes *block*. /// /// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index cb8ce5fc0..a9d308d30 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -26,11 +26,24 @@ public protocol DatabaseWriter : DatabaseReader { /// Eventual concurrent reads are guaranteed not to see any changes /// performed in the block until they are all saved in the database. /// - /// The block may, or may not, be wrapped inside a transaction, depending on - /// the concrete DatabaseWriter type. + /// The block may, or may not, be wrapped inside a transaction. /// /// This method is *not* reentrant. - func write(_ block: (Database) throws -> T) rethrows -> T + func write(_ block: (Database) throws -> T) throws -> T + + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// The block is guaranteed to be executed outside of a transaction. + /// + /// This method is *not* reentrant. + func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T /// Synchronously executes a block that takes a database connection, and /// returns its result. @@ -82,12 +95,12 @@ extension DatabaseWriter { /// the observer lifetime (observation lasts until observer /// is deallocated). public func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent = .observerLifetime) { - write { $0.add(transactionObserver: transactionObserver, extent: extent) } + writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) } } /// Remove a transaction observer. public func remove(transactionObserver: TransactionObserver) { - write { $0.remove(transactionObserver: transactionObserver) } + writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) } } } @@ -128,9 +141,14 @@ public final class AnyDatabaseWriter : DatabaseWriter { // MARK: - Writing in Database /// :nodoc: - public func write(_ block: (Database) throws -> T) rethrows -> T { + public func write(_ block: (Database) throws -> T) throws -> T { return try base.write(block) } + + /// :nodoc: + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try base.writeWithoutTransaction(block) + } /// :nodoc: public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 0ab45362d..38cbb0118 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -182,7 +182,7 @@ public final class FetchedRecordsController { // Replace observer so that it tracks a new set of columns, // and notify eventual changes let initialItems = fetchedItems - databaseWriter.write { db in + databaseWriter.writeWithoutTransaction { db in let observer = FetchedRecordsObserver(region: region, fetchAndNotifyChanges: fetchAndNotifyChanges) self.observer = observer observer.items = initialItems @@ -293,7 +293,7 @@ public final class FetchedRecordsController { #endif let initialItems = fetchedItems - databaseWriter.write { db in + databaseWriter.writeWithoutTransaction { db in let fetchAndNotifyChanges = makeFetchAndNotifyChangesFunction( controller: self, fetchAlongside: fetchAlongside, diff --git a/Tests/GRDBTests/CompilationProtocolTests.swift b/Tests/GRDBTests/CompilationProtocolTests.swift index 5ee1b405f..1d999c64f 100644 --- a/Tests/GRDBTests/CompilationProtocolTests.swift +++ b/Tests/GRDBTests/CompilationProtocolTests.swift @@ -77,6 +77,7 @@ private class UserDatabaseWriter : DatabaseWriter { func add(collation: DatabaseCollation) { } func remove(collation: DatabaseCollation) { } func write(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } + func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { preconditionFailure() } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() } } diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index 903de8132..ba61cdd02 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -17,7 +17,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { try db.execute("CREATE INDEX foobar ON items(foo, bar)") } - dbPool.write { db in + try dbPool.write { db in // Assert that the writer cache is empty XCTAssertTrue(db.schemaCache.primaryKey("items") == nil) XCTAssertTrue(db.schemaCache.columns(in: "items") == nil) From bd2f17ee10d91aa6c77dfb743aec9b854d28f6b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 07:58:01 +0200 Subject: [PATCH 064/348] Fixes needed by DatabasePool/Writer.writeWithoutTransaction --- GRDB/Core/DatabasePool.swift | 18 +++++++++--------- GRDB/FTS/FTS5CustomTokenizer.swift | 2 +- GRDB/Migration/DatabaseMigrator.swift | 4 ++-- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 82f964260..0f65e3f98 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -119,7 +119,7 @@ extension DatabasePool { /// /// - parameter kind: The checkpoint mode (default passive) public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { - try write { db in + try writer.sync { db in // TODO: read https://www.sqlite.org/c3ref/wal_checkpoint_v2.html and // check whether we need a busy handler on writer and/or readers // when kind is not .Passive. @@ -142,7 +142,7 @@ extension DatabasePool { /// See also setupMemoryManagement(application:) public func releaseMemory() { // TODO: test that this method blocks the current thread until all database accesses are completed. - writeWithoutTransaction { $0.releaseMemory() } + writer.sync { $0.releaseMemory() } readerPool.forEach { reader in reader.sync { $0.releaseMemory() } } @@ -201,7 +201,7 @@ extension DatabasePool { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { try readerPool.clear(andThen: { - try write { try $0.change(passphrase: passphrase) } + try writer.sync { try $0.change(passphrase: passphrase) } readerConfig.passphrase = passphrase }) } @@ -373,7 +373,7 @@ extension DatabasePool : DatabaseReader { /// } public func add(function: DatabaseFunction) { functions.update(with: function) - writeWithoutTransaction { $0.add(function: function) } + writer.sync { $0.add(function: function) } readerPool.forEach { reader in reader.sync { $0.add(function: function) } } @@ -382,7 +382,7 @@ extension DatabasePool : DatabaseReader { /// Remove an SQL function. public func remove(function: DatabaseFunction) { functions.remove(function) - writeWithoutTransaction { $0.remove(function: function) } + writer.sync { $0.remove(function: function) } readerPool.forEach { reader in reader.sync { $0.remove(function: function) } } @@ -401,7 +401,7 @@ extension DatabasePool : DatabaseReader { /// } public func add(collation: DatabaseCollation) { collations.update(with: collation) - writeWithoutTransaction { $0.add(collation: collation) } + writer.sync { $0.add(collation: collation) } readerPool.forEach { reader in reader.sync { $0.add(collation: collation) } } @@ -410,7 +410,7 @@ extension DatabasePool : DatabaseReader { /// Remove a collation. public func remove(collation: DatabaseCollation) { collations.remove(collation) - writeWithoutTransaction { $0.remove(collation: collation) } + writer.sync { $0.remove(collation: collation) } readerPool.forEach { reader in reader.sync { $0.remove(collation: collation) } } @@ -500,7 +500,7 @@ extension DatabasePool : DatabaseWriter { /// - throws: The error thrown by the block, or any error establishing the /// transaction. public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try write { db in + try writer.sync { db in try db.inTransaction(kind) { try block(db) } @@ -601,7 +601,7 @@ extension DatabasePool : DatabaseWriter { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") + GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction. If this error is raised from a DatabasePool.write block, use DatabasePool.writeWithoutTransaction instead (and use transactions when needed).") } // The semaphore that blocks the writing dispatch queue until snapshot diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index 883f1fbc0..eea47f9bb 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -160,7 +160,7 @@ /// class MyTokenizer : FTS5CustomTokenizer { ... } /// dbPool.add(tokenizer: MyTokenizer.self) public func add(tokenizer: Tokenizer.Type) { - write { db in + writeWithoutTransaction { db in db.add(tokenizer: Tokenizer.self) } } diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index d9390a6b5..d3bd3af3c 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -125,7 +125,7 @@ public struct DatabaseMigrator { /// migrations should apply. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter) throws { - try writer.write { db in + try writer.writeWithoutTransaction { db in try setupMigrations(db) try runMigrations(db) } @@ -140,7 +140,7 @@ public struct DatabaseMigrator { /// - targetIdentifier: The identifier of a registered migration. /// - throws: An eventual error thrown by the registered migration blocks. public func migrate(_ writer: DatabaseWriter, upTo targetIdentifier: String) throws { - try writer.write { db in + try writer.writeWithoutTransaction { db in try setupMigrations(db) try runMigrations(db, upTo: targetIdentifier) } From bc244802c0508e228e668c866384c56bd806f321 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 07:58:23 +0200 Subject: [PATCH 065/348] Update tests for DatabasePool/Writer.writeWithoutTransaction --- .../DatabasePoolConcurrencyTests.swift | 26 +++++++++---------- .../DatabasePoolSchemaCacheTests.swift | 2 +- Tests/GRDBTests/DatabaseSnapshotTests.swift | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 6cfaf1850..4b99cdc7b 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -256,7 +256,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // dbPool.read // throws let block1 = { () in - try! dbPool.write { db in + try! dbPool.writeWithoutTransaction { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") s1.signal() @@ -369,7 +369,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } } catch { @@ -419,7 +419,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() @@ -468,7 +468,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in do { _ = s1.wait(timeout: .distantFuture) - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s2.signal() _ = s3.wait(timeout: .distantFuture) @@ -515,7 +515,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() @@ -556,7 +556,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in do { - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -686,7 +686,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } } catch { @@ -736,7 +736,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("DELETE FROM items") } try dbPool.checkpoint() @@ -780,7 +780,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { _ = s1.wait(timeout: .distantFuture) defer { s2.signal() } - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("INSERT INTO items (id) VALUES (NULL)") } try dbPool.checkpoint() @@ -797,7 +797,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromCurrentStateOpensATransaction() throws { let dbPool = try makeDatabasePool() let s = DispatchSemaphore(value: 0) - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try dbPool.readFromCurrentState { db in XCTAssertTrue(db.isInsideTransaction) do { @@ -820,7 +820,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } // Writer Reader - // dbPool.write { + // dbPool.writeWithoutTransaction { // > // dbPool.readFromCurrentState { // < @@ -833,7 +833,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // } var i: Int! = nil - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try dbPool.readFromCurrentState { db in _ = s1.wait(timeout: .distantFuture) i = try! Int.fetchOne(db, "SELECT COUNT(*) FROM persons")! @@ -849,7 +849,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromCurrentStateError() throws { dbConfiguration.trace = { print($0) } let dbPool = try makeDatabasePool() - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.execute("PRAGMA locking_mode=EXCLUSIVE") try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") do { diff --git a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift index ba61cdd02..677cefe89 100644 --- a/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabasePoolSchemaCacheTests.swift @@ -148,7 +148,7 @@ class DatabasePoolSchemaCacheTests : GRDBTestCase { // table exists: false let block1 = { () in - try! dbPool.write { db in + try! dbPool.writeWithoutTransaction { db in try db.execute("CREATE TABLE foo(id INTEGER PRIMARY KEY)") // warm cache _ = try db.primaryKey("foo") diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index e988626f9..a6fe799e9 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -25,7 +25,7 @@ class DatabaseSnapshotTests: GRDBTestCase { func testSnapshotSeesLatestTransaction() throws { let dbPool = try makeDatabasePool() - try dbPool.write { db in + try dbPool.writeWithoutTransaction { db in try db.create(table: "t") { $0.column("id", .integer).primaryKey() } try db.execute("INSERT INTO t DEFAULT VALUES") let snapshot = try dbPool.makeSnapshot() From 20d2c74f8778d83e1d5795ea63bc5ddd929daa5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 12:02:25 +0200 Subject: [PATCH 066/348] Update documentation for DatabasePool.writeWithoutTransaction --- README.md | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index c7db629b2..3f1ebe47c 100644 --- a/README.md +++ b/README.md @@ -433,11 +433,11 @@ Database pools allow several threads to access the database at the same time: Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). -- Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. - - Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called "snapshot isolation". - - To provide `read` closures an immutable view of the last executed writing block *as a whole*, use `writeInTransaction` instead of `write`. + +- Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. + +- The `write` and `writeInTransaction` methods always run your database statements in a transaction. There is also a `writeWithoutTransaction` method that allows you to precisely control database transactions, at the cost of concurrency subtleties. See the [Concurrency](#concurrency) chapter. - Database pools can take [snapshots](#database-snapshots) of the database. @@ -6307,9 +6307,15 @@ Those guarantees hold as long as you follow three rules: On that last example, see [Advanced DatabasePool](#advanced-databasepool) if you look after extra performance. -- :point_up: **Rule 3**: When you perform several modifications of the database that temporarily put the database in an inconsistent state, group those modifications within a [transaction](#transactions-and-savepoints): +- :point_up: **Rule 3**: When you perform several modifications of the database that temporarily put the database in an inconsistent state, make sure those modifications are grouped within a [transaction](#transactions-and-savepoints). ```swift + // SAFE CONCURRENCY + try dbPool.write { db in // or dbQueue.inDatabase { ... } + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + } + // SAFE CONCURRENCY try dbPool.writeInTransaction { db in // or dbQueue.inTransaction { ... } try Credit(destinationAccout, amount).insert(db) @@ -6318,8 +6324,9 @@ Those guarantees hold as long as you follow three rules: } // UNSAFE CONCURRENCY - try dbPool.write { db in // or dbQueue.inDatabase { ... } + try dbPool.writeWithoutTransaction { db in try Credit(destinationAccout, amount).insert(db) + // <- Concurrent dbPool.read sees a partial db update here try Debit(sourceAccount, amount).insert(db) } ``` @@ -6378,14 +6385,15 @@ try dbPool.read { db in } ``` -The correct solution is the `readFromCurrentState` method, which must be called from within a write block: +The correct solution is the `readFromCurrentState` method, which must be called from within a write block, outside of any transaction: ```swift // CORRECT -try dbPool.write { db in +try dbPool.writeWithoutTransaction { db in // Increment the number of players try Player(...).insert(db) + // <- not in a transaction here try dbPool.readFromCurrentState { db // Read the number of players. The writer queue has been unlocked :-) let count = try Player.fetchCount(db) @@ -6398,7 +6406,7 @@ try dbPool.write { db in The closure can run concurrently with eventual updates performed after `readFromCurrentState`: those updates won't be visible from within the closure. In the example below, the number of players is guaranteed to be non-zero, even though it is fetched concurrently with the player deletion: ```swift -try dbPool.write { db in +try dbPool.writeWithoutTransaction { db in // Increment the number of players try Player(...).insert(db) @@ -6443,11 +6451,12 @@ let playerCount = try snapshot.read { db in } ``` -When you want to control the latest committed changes seen by a snapshot, create it from the pool's writer protected dispatch queue: +When you want to control the latest committed changes seen by a snapshot, create it from the pool's writer protected dispatch queue, outside of any transaction: ```swift -let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in +let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in try Player.deleteAll() + // <- not in a transaction here return dbPool.makeSnapshot() } // <- Other threads may modify the database here From 5df4e713b656895b69e92c80a2f974b647748816 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 12:39:29 +0200 Subject: [PATCH 067/348] GRDB3 TODO --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index f95a59be9..81a16f481 100644 --- a/TODO.md +++ b/TODO.md @@ -21,6 +21,8 @@ GRDB 3.0 - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] HiddenColumnsAdapter +- [ ] If possible: Have Record adopt Codable +- [ ] Not sure: Have DatabaseQueue wrap writes in a transaction by default Not sure From 1a5f432ee1eacda153c70a43412dfb4ee58f51b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 13:59:10 +0200 Subject: [PATCH 068/348] Update documentation for DatabasePool.writeWithoutTransaction --- README.md | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 93 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3f1ebe47c..ba262148c 100644 --- a/README.md +++ b/README.md @@ -1265,9 +1265,29 @@ Grape.fromDatabaseValue(row[0]) // nil ## Transactions and Savepoints -The `DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` methods open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed: +- [Transactions and Safety](#transactions-and-safety) +- [Explicit Transactions](#explicit transactions) +- [Savepoints](#savepoints) +- [Transaction Kinds](#transaction kinds) + + +### Transactions and Safety + +**Transactions** are a fundamental concept of SQLite that guarantee [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. + +These are all important words for a database expert, but not all developers know them very well. That's why GRDB will sometimes open transactions for you, automatically, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic. See the [list of database access methods](#list-of-database-access-methods) for an overview. + +**Yet some users need to control exactly when transactions take place.** This is an advanced use case, described below. + + +### Explicit Transactions + +`DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed: ```swift +// BEGIN TRANSACTION +// INSERT INTO wines (...) +// COMMIT try dbQueue.inTransaction { db in let wine = Wine(color: .red, name: "Pomerol") try wine.insert(db) @@ -1280,17 +1300,16 @@ If an error is thrown within the transaction body, the transaction is rollbacked If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements: ```swift -try dbQueue.inDatabase { db in // or dbPool.write { db in - ... +dbPool.writeWithoutTransaction { db in // or dbQueue.inDatabase { ... } try db.inTransaction { ... return .commit } - ... + try db.beginTransaction() ... try db.commit() - ... + try db.execute("BEGIN TRANSACTION") ... try db.execute("COMMIT") @@ -6205,6 +6224,7 @@ You can catch those errors and wait for [UIApplicationDelegate.applicationProtec - [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols) - [Unsafe Concurrency APIs](#unsafe-concurrency-apis) - [Dealing with External Connections](#dealing-with-external-connections) +- [List of Database Access Methods](#list-of-database-access-methods) ### Guarantees and Rules @@ -6576,6 +6596,74 @@ If you absolutely need multiple connections, then: - [Ask questions](https://github.com/groue/GRDB.swift/issues) +### List of Database Access Methods + +This is the list of database access methods: + +- [DatabaseQueue](#databasequeue-methods) +- [DatabasePool](#databasepool-methods) +- [DatabaseSnapshot](#databasesnapshot-methods) +- [DatabaseReader Protocol](#databasereader-protocol-methods) +- [DatabaseWriter Protocol](#databasewriter-protocol-methods) + + +#### DatabaseQueue Methods + +See [DatabaseQueue](#database-queues) + +| Method | Opens a Transaction | Notes | +| ------ | ------------------- | ----- | +| `read` | NO | Guaranteed read-only access from SQLite 3.8.0 (iOS 8.2+, macOS 10.10+). | +| `inDatabase` | NO | | +| `inTransaction` | YES | | + + +#### DatabasePool Methods + +See [DatabasePool](#database-pools) + +| Method | Opens a Transaction | Notes | +| ------ | ------------------- | ----- | +| `write` | YES | | +| `writeInTransaction` | YES | | +| `writeWithoutTransaction` | NO | | +| `read` | YES | | +| `readFromCurrentState` | YES | Must be executed from a writing block. Can't be executed from inside a transaction. | +| `makeSnapshot` | YES | Can't be executed from inside a transaction. | + + +#### DatabaseSnapshot Methods + +See [DatabaseSnapshot](#database-snapshots) + +| Method | Opens a Transaction | Notes | +| ------ | ------------------- | ----- | +| `read` | YES | | + + +#### DatabaseReader Protocol Methods + +See [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) + +| Method | Notes | +| ------ | ----- | +| `read` | | +| `unsafeRead` | | +| `unsafeReentrantRead` | | + + +#### DatabaseWriter Protocol Methods + +See [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) + +| Method | Notes | +| ------ | ----- | +| `write` | | +| `writeWithoutTransaction` | | +| `unsafeReentrantWrite` | | +| `readFromCurrentState` | Must be executed from a writing block. Can't be executed from inside a transaction. | + + ## Performance GRDB is a reasonably fast library, and can deliver quite efficient SQLite access. See [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for an overview. From 2ac2a148c6d4e4e8039b3078f416b21ca49d91bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 14:00:19 +0200 Subject: [PATCH 069/348] Typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ba262148c..a1dda8763 100644 --- a/README.md +++ b/README.md @@ -1266,9 +1266,9 @@ Grape.fromDatabaseValue(row[0]) // nil ## Transactions and Savepoints - [Transactions and Safety](#transactions-and-safety) -- [Explicit Transactions](#explicit transactions) +- [Explicit Transactions](#explicit-transactions) - [Savepoints](#savepoints) -- [Transaction Kinds](#transaction kinds) +- [Transaction Kinds](#transaction-kinds) ### Transactions and Safety From 1275ebc2b15e63e90dbab5c9a30d840a9aa349d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 14:02:31 +0200 Subject: [PATCH 070/348] Layout --- README.md | 20 +++++--------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index a1dda8763..6adb6168a 100644 --- a/README.md +++ b/README.md @@ -6607,9 +6607,7 @@ This is the list of database access methods: - [DatabaseWriter Protocol](#databasewriter-protocol-methods) -#### DatabaseQueue Methods - -See [DatabaseQueue](#database-queues) +#### [DatabaseQueue](#database-queues) Methods | Method | Opens a Transaction | Notes | | ------ | ------------------- | ----- | @@ -6618,9 +6616,7 @@ See [DatabaseQueue](#database-queues) | `inTransaction` | YES | | -#### DatabasePool Methods - -See [DatabasePool](#database-pools) +#### [DatabasePool](#database-pools) Methods | Method | Opens a Transaction | Notes | | ------ | ------------------- | ----- | @@ -6632,18 +6628,14 @@ See [DatabasePool](#database-pools) | `makeSnapshot` | YES | Can't be executed from inside a transaction. | -#### DatabaseSnapshot Methods - -See [DatabaseSnapshot](#database-snapshots) +#### [DatabaseSnapshot](#database-snapshots) Methods | Method | Opens a Transaction | Notes | | ------ | ------------------- | ----- | | `read` | YES | | -#### DatabaseReader Protocol Methods - -See [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) +#### [DatabaseReader Protocol](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) Methods | Method | Notes | | ------ | ----- | @@ -6652,9 +6644,7 @@ See [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/Datab | `unsafeReentrantRead` | | -#### DatabaseWriter Protocol Methods - -See [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) +#### [DatabaseWriter Protocol](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) Methods | Method | Notes | | ------ | ----- | From 02927106ca7f1cc2eef80e6f321cdd2d7db160ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 14:06:13 +0200 Subject: [PATCH 071/348] It looks like documentation wants that DatabaseQueue automatically opens transactions as well... --- README.md | 70 ++++++++----------------------------------------------- 1 file changed, 10 insertions(+), 60 deletions(-) diff --git a/README.md b/README.md index 6adb6168a..ed37217a8 100644 --- a/README.md +++ b/README.md @@ -1275,7 +1275,16 @@ Grape.fromDatabaseValue(row[0]) // nil **Transactions** are a fundamental concept of SQLite that guarantee [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. -These are all important words for a database expert, but not all developers know them very well. That's why GRDB will sometimes open transactions for you, automatically, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic. See the [list of database access methods](#list-of-database-access-methods) for an overview. +These are all important words for a database expert, but not all developers know them very well. That's why GRDB will generally open transactions for you, automatically, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic: + +```swift +// BEGIN TRANSACTION +// INSERT INTO players ... +// COMMIT +try dbPool.write { db in + try Player(...).insert(db) +} +``` **Yet some users need to control exactly when transactions take place.** This is an advanced use case, described below. @@ -6224,7 +6233,6 @@ You can catch those errors and wait for [UIApplicationDelegate.applicationProtec - [DatabaseWriter and DatabaseReader Protocols](#databasewriter-and-databasereader-protocols) - [Unsafe Concurrency APIs](#unsafe-concurrency-apis) - [Dealing with External Connections](#dealing-with-external-connections) -- [List of Database Access Methods](#list-of-database-access-methods) ### Guarantees and Rules @@ -6596,64 +6604,6 @@ If you absolutely need multiple connections, then: - [Ask questions](https://github.com/groue/GRDB.swift/issues) -### List of Database Access Methods - -This is the list of database access methods: - -- [DatabaseQueue](#databasequeue-methods) -- [DatabasePool](#databasepool-methods) -- [DatabaseSnapshot](#databasesnapshot-methods) -- [DatabaseReader Protocol](#databasereader-protocol-methods) -- [DatabaseWriter Protocol](#databasewriter-protocol-methods) - - -#### [DatabaseQueue](#database-queues) Methods - -| Method | Opens a Transaction | Notes | -| ------ | ------------------- | ----- | -| `read` | NO | Guaranteed read-only access from SQLite 3.8.0 (iOS 8.2+, macOS 10.10+). | -| `inDatabase` | NO | | -| `inTransaction` | YES | | - - -#### [DatabasePool](#database-pools) Methods - -| Method | Opens a Transaction | Notes | -| ------ | ------------------- | ----- | -| `write` | YES | | -| `writeInTransaction` | YES | | -| `writeWithoutTransaction` | NO | | -| `read` | YES | | -| `readFromCurrentState` | YES | Must be executed from a writing block. Can't be executed from inside a transaction. | -| `makeSnapshot` | YES | Can't be executed from inside a transaction. | - - -#### [DatabaseSnapshot](#database-snapshots) Methods - -| Method | Opens a Transaction | Notes | -| ------ | ------------------- | ----- | -| `read` | YES | | - - -#### [DatabaseReader Protocol](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) Methods - -| Method | Notes | -| ------ | ----- | -| `read` | | -| `unsafeRead` | | -| `unsafeReentrantRead` | | - - -#### [DatabaseWriter Protocol](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) Methods - -| Method | Notes | -| ------ | ----- | -| `write` | | -| `writeWithoutTransaction` | | -| `unsafeReentrantWrite` | | -| `readFromCurrentState` | Must be executed from a writing block. Can't be executed from inside a transaction. | - - ## Performance GRDB is a reasonably fast library, and can deliver quite efficient SQLite access. See [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for an overview. From cc136922e557ddbb03cde0875a9575cfc1028f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 12 Apr 2018 14:07:38 +0200 Subject: [PATCH 072/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ed37217a8..a433ec811 100644 --- a/README.md +++ b/README.md @@ -1309,7 +1309,7 @@ If an error is thrown within the transaction body, the transaction is rollbacked If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements: ```swift -dbPool.writeWithoutTransaction { db in // or dbQueue.inDatabase { ... } +try dbPool.writeWithoutTransaction { db in // or dbQueue.inDatabase { ... } try db.inTransaction { ... return .commit From 267371ba90d7a0a660cae1bdbb987336e3d55a05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Apr 2018 08:20:17 +0200 Subject: [PATCH 073/348] Tests that DatabasePool.write opens a transaction --- .../DatabasePoolConcurrencyTests.swift | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 4b99cdc7b..069ed0c99 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -229,6 +229,31 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } + func testWriteOpensATransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.write { db in + XCTAssertTrue(db.isInsideTransaction) + do { + try db.execute("BEGIN DEFERRED TRANSACTION") + XCTFail("Expected error") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message!, "cannot start a transaction within a transaction") + XCTAssertEqual(error.sql!, "BEGIN DEFERRED TRANSACTION") + XCTAssertEqual(error.description, "SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: cannot start a transaction within a transaction") + } + } + } + + func testWriteWithoutTransactionDoesNotOpenATransaction() throws { + let dbPool = try makeDatabasePool() + try dbPool.writeWithoutTransaction { db in + XCTAssertFalse(db.isInsideTransaction) + try db.beginTransaction() + try db.commit() + } + } + func testReadOpensATransaction() throws { let dbPool = try makeDatabasePool() try dbPool.read { db in From d78479e4af45cb78885f60ded0e9f97d12507417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Apr 2018 08:56:03 +0200 Subject: [PATCH 074/348] [WIP] DatabaseQueue.inDatabase runs inside a transaction --- GRDB/Core/DatabaseQueue.swift | 39 +++++++++++-------- ...abaseAfterNextTransactionCommitTests.swift | 4 +- Tests/GRDBTests/DatabaseErrorTests.swift | 2 +- .../DatabaseQueueConcurrencyTests.swift | 2 +- Tests/GRDBTests/DatabaseSavepointTests.swift | 28 ++++++------- .../FetchedRecordsControllerTests.swift | 2 +- ...RecordPersistenceConflictPolicyTests.swift | 2 +- Tests/GRDBTests/SelectStatementTests.swift | 2 +- .../TransactionObserverSavepointsTests.swift | 12 +++--- 9 files changed, 49 insertions(+), 44 deletions(-) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 4ebf2d88d..42a083368 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -84,7 +84,14 @@ extension DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + return try serializedDatabase.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } } /// Synchronously executes a block in a protected dispatch queue, wrapped @@ -110,7 +117,7 @@ extension DatabaseQueue { /// .commit or .rollback. /// - throws: The error thrown by the block. public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try inDatabase { db in + try serializedDatabase.sync { db in try db.inTransaction(kind) { try block(db) } @@ -128,7 +135,7 @@ extension DatabaseQueue { /// /// See also setupMemoryManagement(application:) public func releaseMemory() { - inDatabase { $0.releaseMemory() } + serializedDatabase.sync { $0.releaseMemory() } } #if os(iOS) @@ -181,7 +188,7 @@ extension DatabaseQueue { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { - try inDatabase { try $0.change(passphrase: passphrase) } + try serializedDatabase.sync { try $0.change(passphrase: passphrase) } } } #endif @@ -209,21 +216,19 @@ extension DatabaseQueue : DatabaseReader { // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) #if GRDBCUSTOMSQLITE || GRDBCIPHER - return try inDatabase { try readOnly($0, block) } + return try serializedDatabase.sync { try readOnly($0, block) } #else if #available(iOS 8.2, OSX 10.10, *) { - return try inDatabase { try readOnly($0, block) } + return try serializedDatabase.sync { try readOnly($0, block) } } else { - return try inDatabase(block) + return try serializedDatabase.sync(block) } #endif } - /// Alias for `inDatabase`. See `DatabaseReader.unsafeRead`. - /// /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) + return try serializedDatabase.sync(block) } /// Synchronously executes a block in a protected dispatch queue, and @@ -256,12 +261,12 @@ extension DatabaseQueue : DatabaseReader { /// try Int.fetchOne(db, "SELECT succ(1)") // 2 /// } public func add(function: DatabaseFunction) { - inDatabase { $0.add(function: function) } + serializedDatabase.sync { $0.add(function: function) } } /// Remove an SQL function. public func remove(function: DatabaseFunction) { - inDatabase { $0.remove(function: function) } + serializedDatabase.sync { $0.remove(function: function) } } // MARK: - Collations @@ -276,12 +281,12 @@ extension DatabaseQueue : DatabaseReader { /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { - inDatabase { $0.add(collation: collation) } + serializedDatabase.sync { $0.add(collation: collation) } } /// Remove a collation. public func remove(collation: DatabaseCollation) { - inDatabase { $0.remove(collation: collation) } + serializedDatabase.sync { $0.remove(collation: collation) } } } @@ -298,7 +303,7 @@ extension DatabaseQueue : DatabaseWriter { /// /// :nodoc: public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) + return try serializedDatabase.sync(block) } /// Synchronously executes *block*. @@ -355,7 +360,7 @@ private func readOnly(_ db: Database, _ block: (Database) throws -> T) rethro } // Assume those pragmas never fail - try! db.execute("PRAGMA query_only = 1") - defer { try! db.execute("PRAGMA query_only = 0") } + try! db.internalCachedUpdateStatement("PRAGMA query_only = 1").execute() + defer { try! db.internalCachedUpdateStatement("PRAGMA query_only = 0").execute() } return try block(db) } diff --git a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift index a1bf82a11..c663af6fd 100644 --- a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift +++ b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift @@ -47,7 +47,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { class Witness { } let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in var transactionCount = 0 weak var deallocationWitness: Witness? = nil do { @@ -89,7 +89,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { class Witness { } let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in var transactionCount = 0 try db.execute(startSQL) diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 45fd6b4f6..986cfa109 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -40,7 +40,7 @@ class DatabaseErrorTests: GRDBTestCase { func testDatabaseErrorInTopLevelSavepoint() throws { let dbQueue = try makeDatabaseQueue() do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) diff --git a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift index 3ea611a80..cb3829448 100644 --- a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift @@ -343,7 +343,7 @@ class ConcurrencyTests: GRDBTestCase { var rows1: [Row]? var rows2: [Row]? queue.async(group: group) { - try! dbQueue2.inDatabase { db in + try! dbQueue2.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) rows1 = try Row.fetchAll(db, "SELECT * FROM stuffs") s2.signal() diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index b86fba0cb..64e4dbaa0 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -59,7 +59,7 @@ class DatabaseSavepointTests: GRDBTestCase { func testIsInsideTransaction() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in XCTAssertFalse(db.isInsideTransaction) try db.inTransaction { XCTAssertTrue(db.isInsideTransaction) @@ -91,7 +91,7 @@ class DatabaseSavepointTests: GRDBTestCase { func testIsInsideTransactionWithImplicitRollback() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(table: "test") { t in t.column("value", .integer).unique() } @@ -112,7 +112,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -143,7 +143,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -173,7 +173,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -210,7 +210,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -247,7 +247,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -285,7 +285,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -329,7 +329,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -359,7 +359,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -389,7 +389,7 @@ class DatabaseSavepointTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -426,7 +426,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -463,7 +463,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) @@ -501,7 +501,7 @@ class DatabaseSavepointTests: GRDBTestCase { observer.reset() sqlQueries.removeAll() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { XCTAssertTrue(db.isInsideTransaction) diff --git a/Tests/GRDBTests/FetchedRecordsControllerTests.swift b/Tests/GRDBTests/FetchedRecordsControllerTests.swift index ad7da48d3..867f5594c 100644 --- a/Tests/GRDBTests/FetchedRecordsControllerTests.swift +++ b/Tests/GRDBTests/FetchedRecordsControllerTests.swift @@ -897,7 +897,7 @@ class FetchedRecordsControllerTests: GRDBTestCase { }) try specificController.performFetch() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [1, "Arthur"]) try db.execute("INSERT INTO persons (id, name) VALUES (?, ?)", arguments: [2, "Barbara"]) try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1]) diff --git a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift index b4f022efe..02deef3a3 100644 --- a/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordPersistenceConflictPolicyTests.swift @@ -189,7 +189,7 @@ class MutablePersistableRecordPersistenceConflictPolicyTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(table: "records") { t in t.column("id", .integer).primaryKey() t.column("email", .text).unique() diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index 52dcf4429..d48eecad1 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -130,7 +130,7 @@ class SelectStatementTests : GRDBTestCase { func testRegion() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in class Observer: TransactionObserver { private var didChange = false var triggered = false diff --git a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift index f57a847b3..66cfdd935 100644 --- a/Tests/GRDBTests/TransactionObserverSavepointsTests.swift +++ b/Tests/GRDBTests/TransactionObserverSavepointsTests.swift @@ -80,7 +80,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("SAVEPOINT sp1") @@ -112,7 +112,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("BEGIN TRANSACTION") @@ -143,7 +143,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -191,7 +191,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -234,7 +234,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") @@ -278,7 +278,7 @@ class TransactionObserverSavepointsTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)") try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)") From ea3f22c8a48b7364ce54de4c9be48ef189656266 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 13 Apr 2018 18:07:24 +0200 Subject: [PATCH 075/348] Fix tests that were failing now that DatabaseQueue.inDatabase runs inside a transaction --- .../DatabasePoolConcurrencyTests.swift | 26 +++---- Tests/GRDBTests/DatabaseQueueTests.swift | 4 +- Tests/GRDBTests/DatabaseTests.swift | 2 +- Tests/GRDBTests/FTS4TableBuilderTests.swift | 2 +- .../GRDBTests/TransactionObserverTests.swift | 44 +++++------ .../GRDBTests/TruncateOptimizationTests.swift | 76 +++++++++---------- 6 files changed, 77 insertions(+), 77 deletions(-) diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 069ed0c99..a582a9e5c 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -31,7 +31,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -42,7 +42,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -56,7 +56,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("INSERT INTO moves VALUES (1)") s2.signal() @@ -93,7 +93,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -104,7 +104,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") s2.signal() @@ -119,7 +119,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -158,7 +158,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = wal") XCTAssertEqual(journalMode, "wal") try db.create(table: "moves") { $0.column("value", .integer) } @@ -169,7 +169,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block1 = { () in let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") s0.signal() // Avoid "database is locked" error: don't open the two databases at the same time - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in try db.execute("BEGIN DEFERRED TRANSACTION") s1.signal() _ = s2.wait(timeout: .distantFuture) @@ -183,7 +183,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { let block2 = { () in _ = s0.wait(timeout: .distantFuture) // Avoid "database is locked" error: don't open the two databases at the same time let dbQueue = try! self.makeDatabaseQueue(filename: "test.sqlite") - try! dbQueue.inDatabase { db in + try! dbQueue.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) try db.execute("BEGIN DEFERRED TRANSACTION") try db.execute("INSERT INTO moves VALUES (1)") @@ -215,7 +215,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { func testReadFromPreviousNonWALDatabase() throws { do { let dbQueue = try makeDatabaseQueue(filename: "test.sqlite") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE items (id INTEGER PRIMARY KEY)") try db.execute("INSERT INTO items (id) VALUES (NULL)") } @@ -904,11 +904,11 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try db.execute("INSERT INTO t DEFAULT VALUES") } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction(.deferred) } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) } @@ -916,7 +916,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try db.execute("INSERT INTO t DEFAULT VALUES") } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 1) try db.rollback() try XCTAssertEqual(Int.fetchOne(db, "SELECT COUNT(*) FROM t")!, 2) diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 23fe4f7dc..93ad7ef8e 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -95,11 +95,11 @@ class DatabaseQueueTests: GRDBTestCase { dbConfiguration.allowsUnsafeTransactions = true let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction() } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.commit() } } diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 28e47ebf9..91369b7f6 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -302,7 +302,7 @@ class DatabaseTests : GRDBTestCase { func testExplicitTransactionManagement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.beginTransaction() XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") try db.rollback() diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index c20ffe114..0dfa34dce 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -177,7 +177,7 @@ class FTS4TableBuilderTests: GRDBTestCase { func testFTS4Options() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.create(virtualTable: "documents", using: FTS4()) { t in t.content = "" t.compress = "zip" diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 07db51c5a..2631b1bc4 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -224,7 +224,7 @@ class TransactionObserverTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let observer = Observer() dbQueue.add(transactionObserver: observer, extent: extent) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -246,7 +246,7 @@ class TransactionObserverTests: GRDBTestCase { for extent in extents { let dbQueue = try makeDatabaseQueue() let observer = Observer() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) db.add(transactionObserver: observer, extent: extent) try db.execute(endSQL) @@ -271,7 +271,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() weakObserver = observer dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -310,7 +310,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() weakObserver = observer dbQueue.add(transactionObserver: observer, extent: .observerLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -351,7 +351,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer, extent: .nextTransaction) } if let observer = weakObserver { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -376,7 +376,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer, extent: .nextTransaction) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -418,7 +418,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: witness) dbQueue.add(transactionObserver: observer, extent: .nextTransaction) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -484,7 +484,7 @@ class TransactionObserverTests: GRDBTestCase { } if let observer = weakObserver { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -546,7 +546,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer3, extent: extent) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute(startSQL) try db.execute(endSQL) } @@ -595,7 +595,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -626,7 +626,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) artist.name = "Vincent Fournier" @@ -662,7 +662,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) @@ -694,7 +694,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") try artist.save(db) let artwork1 = Artwork(id: nil, artistId: artist.id, title: "Cloud") @@ -761,7 +761,7 @@ class TransactionObserverTests: GRDBTestCase { let artist = Artist(id: nil, name: "Gerhard Richter") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in observer.resetCounts() try artist.save(db) #if SQLITE_ENABLE_PREUPDATE_HOOK @@ -784,7 +784,7 @@ class TransactionObserverTests: GRDBTestCase { let artwork1 = Artwork(id: nil, artistId: nil, title: "Cloud") let artwork2 = Artwork(id: nil, artistId: nil, title: "Ema (Nude on a Staircase)") - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try artist.save(db) artwork1.artistId = artist.id artwork2.artistId = artist.id @@ -1116,7 +1116,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try Artwork(id: nil, artistId: nil, title: "meh").save(db) XCTFail("Expected Error") @@ -1190,7 +1190,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) observer.commitError = NSError(domain: "foo", code: 0, userInfo: nil) - dbQueue.inDatabase { db in + dbQueue.writeWithoutTransaction { db in do { try Artist(id: nil, name: "Gerhard Richter").save(db) XCTFail("Expected Error") @@ -1246,7 +1246,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) do { - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in do { try Artwork(id: nil, artistId: nil, title: "meh").save(db) XCTFail("Expected Error") @@ -1329,7 +1329,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try MinimalRowID.setup(inDatabase: db) let record = MinimalRowID() @@ -1357,7 +1357,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer1) dbQueue.add(transactionObserver: observer2) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -1410,7 +1410,7 @@ class TransactionObserverTests: GRDBTestCase { let observer = Observer() dbQueue.add(transactionObserver: observer) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in let artist = Artist(id: nil, name: "Gerhard Richter") // @@ -1690,7 +1690,7 @@ class TransactionObserverTests: GRDBTestCase { } } - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in // Don't ignore anything do { observer.resetCounts() diff --git a/Tests/GRDBTests/TruncateOptimizationTests.swift b/Tests/GRDBTests/TruncateOptimizationTests.swift index 6334d3044..7617539f0 100644 --- a/Tests/GRDBTests/TruncateOptimizationTests.swift +++ b/Tests/GRDBTests/TruncateOptimizationTests.swift @@ -75,7 +75,7 @@ class TruncateOptimizationTests: GRDBTestCase { let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") @@ -100,7 +100,7 @@ class TruncateOptimizationTests: GRDBTestCase { let observer = DeletionObserver { deletionEvents.append($0) } dbQueue.add(transactionObserver: observer, extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") let deleteStatement = try db.makeUpdateStatement("DELETE FROM t") @@ -121,7 +121,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -133,7 +133,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -144,7 +144,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -157,7 +157,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -169,7 +169,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -181,7 +181,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -192,7 +192,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -205,7 +205,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -217,7 +217,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -229,7 +229,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropVirtualTable() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -240,7 +240,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -253,7 +253,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropVirtualTableWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE VIRTUAL TABLE t USING fts3(a)") try db.execute("INSERT INTO t VALUES (NULL)") try XCTAssertTrue(db.tableExists("t")) @@ -265,7 +265,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropView() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -278,7 +278,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -290,7 +290,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -304,7 +304,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -317,7 +317,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -330,7 +330,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryView() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -342,7 +342,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -356,7 +356,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY VIEW v AS SELECT * FROM t") try db.execute("INSERT INTO t VALUES (NULL)") @@ -369,7 +369,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropIndex() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -381,7 +381,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -392,7 +392,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -406,7 +406,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -419,7 +419,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -431,7 +431,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryIndex() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try XCTAssertFalse(db.indexes(on: "t").isEmpty) @@ -442,7 +442,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -456,7 +456,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryIndexViewWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TEMPORARY TABLE t(a)") try db.execute("CREATE INDEX i ON t(a)") try db.execute("INSERT INTO t VALUES (1)") @@ -469,7 +469,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTrigger() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -481,7 +481,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -492,7 +492,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -505,7 +505,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -517,7 +517,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -529,7 +529,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTrigger() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -540,7 +540,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) @@ -553,7 +553,7 @@ class TruncateOptimizationTests: GRDBTestCase { func testObservedDropTemporaryTriggerWithPreparedStatement() throws { let dbQueue = try makeDatabaseQueue() dbQueue.add(transactionObserver: UniversalObserver(), extent: .databaseLifetime) - try dbQueue.inDatabase { db in + try dbQueue.writeWithoutTransaction { db in try db.execute("CREATE TABLE t(a)") try db.execute("CREATE TEMPORARY TRIGGER r INSERT ON t BEGIN DELETE FROM t; END") try XCTAssertTrue(db.triggerExists("r")) From a46505e9073bcdb45caac3d45b232db1064c9de7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 14:30:12 +0200 Subject: [PATCH 076/348] Cleanup --- GRDB/Core/Database.swift | 27 ++- GRDB/Core/DatabasePool.swift | 386 +++++++++++++++++----------------- GRDB/Core/DatabaseQueue.swift | 302 +++++++++++++------------- 3 files changed, 364 insertions(+), 351 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 25cb95f78..ef87817d6 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -150,7 +150,9 @@ public final class Database { lazy var observationBroker = DatabaseObservationBroker(self) /// The list of compile options used when building SQLite - static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) } + static let sqliteCompileOptions: Set = DatabaseQueue().inDatabase { + try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS")) + } // MARK: - Private properties @@ -527,6 +529,25 @@ extension Database { } } +extension Database { + + // MARK: - Read-Only Access + + /// Grants read-only access, starting SQLite 3.8.0 + func readOnly(_ block: () throws -> T) rethrows -> T { + if configuration.readonly { + return try block() + } + + // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 + // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) + // Assume those pragmas never fail + try! execute("PRAGMA query_only = 1") + defer { try! execute("PRAGMA query_only = 0") } + return try block() + } +} + extension Database { // MARK: - Transactions & Savepoint @@ -548,7 +569,7 @@ extension Database { /// - parameters: /// - kind: The transaction type (default nil). If nil, the transaction /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. /// - block: A block that executes SQL statements and return either /// .commit or .rollback. @@ -679,7 +700,7 @@ extension Database { /// /// - parameter kind: The transaction type (default nil). If nil, the /// transaction type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html /// for more information. /// - throws: The error thrown by the block. public func beginTransaction(_ kind: TransactionKind? = nil) throws { diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 0f65e3f98..5d650d89a 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -9,7 +9,7 @@ import Foundation #endif /// A DatabasePool grants concurrent accesses to an SQLite database. -public final class DatabasePool { +public final class DatabasePool: DatabaseWriter { private let writer: SerializedDatabase private var readerConfig: Configuration private var readerPool: Pool! @@ -315,8 +315,8 @@ extension DatabasePool : DatabaseReader { /// while let row = try rows.next() { ... } /// } /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block, or any DatabaseError that would @@ -335,199 +335,6 @@ extension DatabasePool : DatabaseReader { } } - /// Returns a reader that can be used from the current dispatch queue, - /// if any. - private var currentReader: SerializedDatabase? { - var readers: [SerializedDatabase] = [] - readerPool.forEach { reader in - // We can't check for reader.onValidQueue here because - // Pool.forEach() runs its closure argument in some arbitrary - // dispatch queue. We thus extract the reader so that we can query - // it below. - readers.append(reader) - } - - // Now the readers array contains some readers. The pool readers may - // already be different, because some other thread may have started - // a new read, for example. - // - // This doesn't matter: the reader we are looking for is already on - // its own dispatch queue. If it exists, is still in use, thus still - // in the pool, and thus still relevant for our check: - return readers.first { $0.onValidQueue } - } - - // MARK: - Functions - - /// Add or redefine an SQL function. - /// - /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in - /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { - /// return nil - /// } - /// return int + 1 - /// } - /// dbPool.add(function: fn) - /// try dbPool.read { db in - /// try Int.fetchOne(db, "SELECT succ(1)") // 2 - /// } - public func add(function: DatabaseFunction) { - functions.update(with: function) - writer.sync { $0.add(function: function) } - readerPool.forEach { reader in - reader.sync { $0.add(function: function) } - } - } - - /// Remove an SQL function. - public func remove(function: DatabaseFunction) { - functions.remove(function) - writer.sync { $0.remove(function: function) } - readerPool.forEach { reader in - reader.sync { $0.remove(function: function) } - } - } - - // MARK: - Collations - - /// Add or redefine a collation. - /// - /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in - /// return (string1 as NSString).localizedStandardCompare(string2) - /// } - /// dbPool.add(collation: collation) - /// try dbPool.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") - /// } - public func add(collation: DatabaseCollation) { - collations.update(with: collation) - writer.sync { $0.add(collation: collation) } - readerPool.forEach { reader in - reader.sync { $0.add(collation: collation) } - } - } - - /// Remove a collation. - public func remove(collation: DatabaseCollation) { - collations.remove(collation) - writer.sync { $0.remove(collation: collation) } - readerPool.forEach { reader in - reader.sync { $0.remove(collation: collation) } - } - } -} - -extension DatabasePool : DatabaseWriter { - - // MARK: - Writing in Database - - /// Synchronously executes an update block in a protected dispatch queue, - /// wrapped inside a transaction, and returns the result of the block. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// try dbPool.write { db in - /// try db.execute(...) - /// } - /// - /// Eventual concurrent reads are guaranteed not to see any changes - /// performed in the block until they are all saved in the database. - /// - /// This method is *not* reentrant. - /// - /// - parameters block: A block that executes SQL statements and return - /// either .commit or .rollback. - /// - throws: The error thrown by the block, or by the wrapping transaction. - public func write(_ block: (Database) throws -> T) throws -> T { - return try writer.sync { db in - var result: T? = nil - try db.inTransaction { - result = try block(db) - return .commit - } - return result! - } - } - - /// Synchronously executes a block that takes a database connection, and - /// returns its result. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - /// - /// The block is guaranteed to be executed outside of a transaction. - /// - /// This method is *not* reentrant. - /// - /// - parameters block: A block that executes SQL statements and return - /// either .commit or .rollback. - /// - throws: The error thrown by the block. - public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try writer.sync(block) - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is - /// also rollbacked, but no error is thrown. - /// - /// try dbPool.writeInTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// Eventual concurrent reads are guaranteed not to see any changes - /// performed in the block until they are all saved in the database. - /// - /// This method is *not* reentrant. - /// - /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html - /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block, or any error establishing the - /// transaction. - public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try writer.sync { db in - try db.inTransaction(kind) { - try block(db) - } - } - } - - /// Synchronously executes an update block in a protected dispatch queue, - /// and returns its result. - /// - /// Eventual concurrent database updates are postponed until the block - /// has executed. - /// - /// try dbPool.unsafeReentrantWrite { db in - /// try db.execute(...) - /// } - /// - /// Eventual concurrent reads may see changes performed in the block before - /// the block completes. - /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try writer.reentrantSync(block) - } - - // MARK: - Reading from Database - /// Asynchronously executes a read-only block in a protected dispatch queue, /// wrapped in a deferred transaction. /// @@ -635,6 +442,193 @@ extension DatabasePool : DatabaseWriter { throw readError } } + + /// Returns a reader that can be used from the current dispatch queue, + /// if any. + private var currentReader: SerializedDatabase? { + var readers: [SerializedDatabase] = [] + readerPool.forEach { reader in + // We can't check for reader.onValidQueue here because + // Pool.forEach() runs its closure argument in some arbitrary + // dispatch queue. We thus extract the reader so that we can query + // it below. + readers.append(reader) + } + + // Now the readers array contains some readers. The pool readers may + // already be different, because some other thread may have started + // a new read, for example. + // + // This doesn't matter: the reader we are looking for is already on + // its own dispatch queue. If it exists, is still in use, thus still + // in the pool, and thus still relevant for our check: + return readers.first { $0.onValidQueue } + } + + // MARK: - Writing in Database + + /// Synchronously executes an update block in a protected dispatch queue, + /// wrapped inside a transaction, and returns the result of the block. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// try dbPool.write { db in + /// try db.execute(...) + /// } + /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// This method is *not* reentrant. + /// + /// - parameters block: A block that executes SQL statements. + /// - throws: The error thrown by the block, or by the wrapping transaction. + public func write(_ block: (Database) throws -> T) throws -> T { + return try writer.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } + } + + /// Synchronously executes a block that takes a database connection, and + /// returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// The block is guaranteed to be executed outside of a transaction. + /// + /// This method is *not* reentrant. + /// + /// - parameters block: A block that executes SQL statements and return + /// either .commit or .rollback. + /// - throws: The error thrown by the block. + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try writer.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. If the block returns .rollback, the transaction is + /// also rollbacked, but no error is thrown. + /// + /// try dbPool.writeInTransaction { db in + /// db.execute(...) + /// return .commit + /// } + /// + /// Eventual concurrent reads are guaranteed not to see any changes + /// performed in the block until they are all saved in the database. + /// + /// This method is *not* reentrant. + /// + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is configuration.defaultTransactionKind, which itself + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - block: A block that executes SQL statements and return either + /// .commit or .rollback. + /// - throws: The error thrown by the block, or any error establishing the + /// transaction. + public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + try writer.sync { db in + try db.inTransaction(kind) { + try block(db) + } + } + } + + /// Synchronously executes an update block in a protected dispatch queue, + /// and returns its result. + /// + /// Eventual concurrent database updates are postponed until the block + /// has executed. + /// + /// try dbPool.unsafeReentrantWrite { db in + /// try db.execute(...) + /// } + /// + /// Eventual concurrent reads may see changes performed in the block before + /// the block completes. + /// + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. + public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { + return try writer.reentrantSync(block) + } + + // MARK: - Functions + + /// Add or redefine an SQL function. + /// + /// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in + /// guard let int = Int.fromDatabaseValue(dbValues[0]) else { + /// return nil + /// } + /// return int + 1 + /// } + /// dbPool.add(function: fn) + /// try dbPool.read { db in + /// try Int.fetchOne(db, "SELECT succ(1)") // 2 + /// } + public func add(function: DatabaseFunction) { + functions.update(with: function) + writer.sync { $0.add(function: function) } + readerPool.forEach { reader in + reader.sync { $0.add(function: function) } + } + } + + /// Remove an SQL function. + public func remove(function: DatabaseFunction) { + functions.remove(function) + writer.sync { $0.remove(function: function) } + readerPool.forEach { reader in + reader.sync { $0.remove(function: function) } + } + } + + // MARK: - Collations + + /// Add or redefine a collation. + /// + /// let collation = DatabaseCollation("localized_standard") { (string1, string2) in + /// return (string1 as NSString).localizedStandardCompare(string2) + /// } + /// dbPool.add(collation: collation) + /// try dbPool.write { db in + /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// } + public func add(collation: DatabaseCollation) { + collations.update(with: collation) + writer.sync { $0.add(collation: collation) } + readerPool.forEach { reader in + reader.sync { $0.add(collation: collation) } + } + } + + /// Remove a collation. + public func remove(collation: DatabaseCollation) { + collations.remove(collation) + writer.sync { $0.remove(collation: collation) } + readerPool.forEach { reader in + reader.sync { $0.remove(collation: collation) } + } + } } extension DatabasePool { diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index 42a083368..e7c4194b1 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -5,7 +5,7 @@ import UIKit #endif /// A DatabaseQueue serializes access to an SQLite database. -public final class DatabaseQueue { +public final class DatabaseQueue: DatabaseWriter { private var serializedDatabase: SerializedDatabase #if os(iOS) private weak var application: UIApplication? @@ -68,63 +68,6 @@ public final class DatabaseQueue { #endif } -extension DatabaseQueue { - - // MARK: - Database Access - - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// let players = try dbQueue.inDatabase { db in - /// try Player.fetchAll(...) - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameter block: A block that accesses the database. - /// - throws: The error thrown by the block. - public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync { db in - var result: T? = nil - try db.inTransaction { - result = try block(db) - return .commit - } - return result! - } - } - - /// Synchronously executes a block in a protected dispatch queue, wrapped - /// inside a transaction. - /// - /// If the block throws an error, the transaction is rollbacked and the - /// error is rethrown. If the block returns .rollback, the transaction is - /// also rollbacked, but no error is thrown. - /// - /// try dbQueue.inTransaction { db in - /// db.execute(...) - /// return .commit - /// } - /// - /// This method is *not* reentrant. - /// - /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is configuration.defaultTransactionKind, which itself - /// defaults to .immediate. See https://www.sqlite.org/lang_transaction.html - /// for more information. - /// - block: A block that executes SQL statements and return either - /// .commit or .rollback. - /// - throws: The error thrown by the block. - public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try serializedDatabase.sync { db in - try db.inTransaction(kind) { - try block(db) - } - } - } -} - extension DatabaseQueue { // MARK: - Memory management @@ -193,7 +136,7 @@ extension DatabaseQueue { } #endif -extension DatabaseQueue : DatabaseReader { +extension DatabaseQueue { // MARK: - Reading from Database @@ -201,31 +144,35 @@ extension DatabaseQueue : DatabaseReader { /// and returns its result. /// /// let players = try dbQueue.read { db in - /// try Player.fetchAll(...) + /// try Player.fetchAll(db) /// } /// /// This method is *not* reentrant. /// - /// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and - /// SQLCipher, attempts to write in the database throw a DatabaseError whose - /// resultCode is `SQLITE_READONLY`. + /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and + /// SQLCipher), attempts to write in the database from this meethod throw a + /// DatabaseError of resultCode `SQLITE_READONLY`. /// /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - return try serializedDatabase.sync { try readOnly($0, block) } - #else - if #available(iOS 8.2, OSX 10.10, *) { - return try serializedDatabase.sync { try readOnly($0, block) } - } else { - return try serializedDatabase.sync(block) - } - #endif + return try serializedDatabase.sync { db in + try db.readOnly { try block(db) } + } } + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// let players = try dbQueue.unsafeRead { db in + /// try Player.fetchAll(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + /// /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { return try serializedDatabase.sync(block) @@ -234,18 +181,143 @@ extension DatabaseQueue : DatabaseReader { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// try dbQueue.unsafeReentrantRead { db in - /// try db.execute(...) + /// let players = try dbQueue.unsafeReentrantRead { db in + /// try Player.fetchAll(db) /// } /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. /// /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { return try serializedDatabase.reentrantSync(block) } + /// Synchronously executes *block*. + /// + /// This method must be called from the protected database dispatch queue, + /// outside of a transaction. You'll get a fatal error otherwise. + /// + /// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and + /// SQLCipher), attempts to write in the database from this meethod throw a + /// DatabaseError of resultCode `SQLITE_READONLY`. + /// + /// See `DatabaseWriter.readFromCurrentState`. + /// + /// :nodoc: + public func readFromCurrentState(_ block: @escaping (Database) -> Void) { + // Check that we're on the correct queue... + serializedDatabase.execute { db in + // ... and that no transaction is opened. + GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") + db.readOnly { block(db) } + } + } + + // MARK: - Writing in Database + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. + /// + /// try dbQueue.write { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that executes SQL statements. + /// - throws: An eventual database error, or the error thrown by the block. + public func write(_ block: (Database) throws -> T) rethrows -> T { + return try serializedDatabase.sync { db in + var result: T? = nil + try db.inTransaction { + result = try block(db) + return .commit + } + return result! + } + } + + /// Synchronously executes a block in a protected dispatch queue, wrapped + /// inside a transaction. + /// + /// If the block throws an error, the transaction is rollbacked and the + /// error is rethrown. If the block returns .rollback, the transaction is + /// also rollbacked, but no error is thrown. + /// + /// try dbQueue.inTransaction { db in + /// try Player(...).insert(db) + /// return .commit + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameters: + /// - kind: The transaction type (default nil). If nil, the transaction + /// type is configuration.defaultTransactionKind, which itself + /// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html + /// for more information. + /// - block: A block that executes SQL statements and return either + /// .commit or .rollback. + /// - throws: The error thrown by the block. + public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { + try serializedDatabase.sync { db in + try db.inTransaction(kind) { + try block(db) + } + } + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// let players = try dbQueue.writeWithoutTransaction { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + /// + /// :nodoc: + public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { + return try serializedDatabase.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// // INSERT INTO players ... + /// let players = try dbQueue.inDatabase { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is *not* reentrant. + /// + /// - parameter block: A block that accesses the database. + /// - throws: The error thrown by the block. + public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { + return try serializedDatabase.sync(block) + } + + /// Synchronously executes a block in a protected dispatch queue, and + /// returns its result. + /// + /// // INSERT INTO players ... + /// try dbQueue.unsafeReentrantWrite { db in + /// try Player(...).insert(db) + /// } + /// + /// This method is reentrant. It is unsafe because it fosters dangerous + /// concurrency practices. + public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { + return try serializedDatabase.reentrantSync(block) + } + // MARK: - Functions /// Add or redefine an SQL function. @@ -290,77 +362,3 @@ extension DatabaseQueue : DatabaseReader { } } -extension DatabaseQueue : DatabaseWriter { - - /// Alias for `inDatabase`. See `DatabaseWriter.write`. - /// - /// :nodoc: - public func write(_ block: (Database) throws -> T) rethrows -> T { - return try inDatabase(block) - } - - /// Alias for `inDatabase`. See `DatabaseWriter.writeWithoutTransaction`. - /// - /// :nodoc: - public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) - } - - /// Synchronously executes *block*. - /// - /// Starting iOS 8.2, OSX 10.10, and with custom SQLite builds and - /// SQLCipher, attempts to write in the database throw a DatabaseError whose - /// resultCode is `SQLITE_READONLY`. - /// - /// This method must be called from the protected database dispatch queue, - /// outside of a transaction. You'll get a fatal error otherwise. - /// - /// See `DatabaseWriter.readFromCurrentState`. - /// - /// :nodoc: - public func readFromCurrentState(_ block: @escaping (Database) -> Void) { - // Check that we're on the correct queue... - serializedDatabase.execute { db in - // ... and that no transaction is opened. - GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") - - // query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0 - // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) - #if GRDBCUSTOMSQLITE || GRDBCIPHER - readOnly(db, block) - #else - if #available(iOS 8.2, OSX 10.10, *) { - readOnly(db, block) - } else { - block(db) - } - #endif - } - } - - // MARK: - Unsafe Database Access - - /// Synchronously executes a block in a protected dispatch queue, and - /// returns its result. - /// - /// try dbQueue.unsafeReentrantWrite { db in - /// try db.execute(...) - /// } - /// - /// This method is reentrant. It should be avoided because it fosters - /// dangerous concurrency practices. - public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.reentrantSync(block) - } -} - -private func readOnly(_ db: Database, _ block: (Database) throws -> T) rethrows -> T { - guard !db.configuration.readonly else { - return try block(db) - } - - // Assume those pragmas never fail - try! db.internalCachedUpdateStatement("PRAGMA query_only = 1").execute() - defer { try! db.internalCachedUpdateStatement("PRAGMA query_only = 0").execute() } - return try block(db) -} From c97c260613cf3d3da00113b91a2c9f15e1f88785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 17:15:13 +0200 Subject: [PATCH 077/348] Update documentation about transactions --- README.md | 338 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 204 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index a433ec811..b2db51fc7 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") [Execute SQL statements](#executing-updates): ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute(""" CREATE TABLE places ( id INTEGER PRIMARY KEY, @@ -110,7 +110,7 @@ try dbQueue.inDatabase { db in [Fetch database rows and values](#fetch-queries): ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in let rows = try Row.fetchCursor(db, "SELECT * FROM places") while let row = try rows.next() { let title: String = row["title"] @@ -125,7 +125,7 @@ try dbQueue.inDatabase { db in } // Extraction -let placeCount = try dbQueue.inDatabase { db in +let placeCount = try dbQueue.read { db in try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! } ``` @@ -143,7 +143,7 @@ struct Place { // snip: turn Place into a "record" by adopting the protocols that // provide fetching and persistence methods. -try dbQueue.inDatabase { db in +try dbQueue.write { db in var berlin = Place( id: nil, title: "Berlin", @@ -164,7 +164,7 @@ try dbQueue.inDatabase { db in Avoid SQL with the [query interface](#the-query-interface): ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.create(table: "places") { t in t.column("id", .integer).primaryKey() t.column("title", .text).notNull() @@ -309,7 +309,7 @@ let dbPool = try DatabasePool(path: "/path/to/database.sqlite") The differences are: - Database pools allow concurrent database accesses (this can improve the performance of multithreaded applications). -- Unless read-only, database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html). +- Database pools open your SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) (unless read-only). - Database queues support [in-memory databases](https://www.sqlite.org/inmemorydb.html). **If you are not sure, choose DatabaseQueue.** You will always be able to switch to DatabasePool later. @@ -331,32 +331,26 @@ let inMemoryDBQueue = DatabaseQueue() SQLite creates the database file if it does not already exist. The connection is closed when the database queue gets deallocated. - -**A database queue can be used from any thread.** The `inDatabase` and `inTransaction` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely serialize the database accesses: +**A database queue can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: ```swift -// Execute database statements: -try dbQueue.inDatabase { db in +// Modify the database: +try dbQueue.write { db in try db.create(table: "places") { ... } try Place(...).insert(db) } -// Wrap database statements in a transaction: -try dbQueue.inTransaction { db in - if let place = try Place.fetchOne(db, key: 1) { - try place.delete(db) - } - return .commit -} - // Read values: -try dbQueue.inDatabase { db in +try dbQueue.read { db in let places = try Place.fetchAll(db) let placeCount = try Place.fetchCount(db) } +``` -// Extract a value from the database: -let placeCount = try dbQueue.inDatabase { db in +Database access methods can return values, for easy extraction of database values: + +```swift +let placeCount = try dbQueue.read { db in try Place.fetchCount(db) } ``` @@ -365,6 +359,12 @@ let placeCount = try dbQueue.inDatabase { db in See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift) for a sample code that sets up a database queue on iOS. +> :muscle: **Note to database experts**: The `write` and `read` database access methods generally help enforcing the [GRDB concurrency guarantees](#concurrency), and are highly recommended, even for skilled developers, because they lift most of the mental burden related to explicit SQLite transactions: +> +> `DatabaseQueue.write` wraps your database statements in a transaction, and rollbacks on the first unhandled error. `DatabaseQueue.read` enforces read-only access. +> +> When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). + ### DatabaseQueue Configuration @@ -384,9 +384,7 @@ See [Configuration](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configur ## Database Pools -**A Database Pool allows concurrent database accesses.** - -When more efficient than [database queues](#database-queues), database pools also inherit the subtleties of SQLite's [WAL mode](https://www.sqlite.org/wal.html). If you don't feel comfortable with improving your SQLite skills, use a [database queue](#database-queues) instead. +**A database pool allows concurrent database accesses.** ```swift import GRDB @@ -397,55 +395,54 @@ SQLite creates the database file if it does not already exist. The connection is > :point_up: **Note**: unless read-only, a database pool opens your database in the SQLite "WAL mode". The WAL mode does not fit all situations. Please have a look at https://www.sqlite.org/wal.html. - -**A database pool can be used from any thread.** The `read`, `write` and `writeInTransaction` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue. They safely isolate the database accesses: +**A database pool can be used from any thread.** The `write` and `read` methods are synchronous, and block the current thread until your database statements are executed in a protected dispatch queue: ```swift -// Execute database statements: +// Modify the database: try dbPool.write { db in try db.create(table: "places") { ... } try Place(...).insert(db) } -// Wrap database statements in a transaction: -try dbPool.writeInTransaction { db in - if let place = try Place.fetchOne(db, key: 1) { - try place.delete(db) - } - return .commit -} - // Read values: try dbPool.read { db in let places = try Place.fetchAll(db) let placeCount = try Place.fetchCount(db) } +``` -// Extract a value from the database: +Database access methods can return values, for easy extraction of database values: + +```swift let placeCount = try dbPool.read { db in try Place.fetchCount(db) } ``` -Database pools allow several threads to access the database at the same time: +**A database pool needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. + +For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool. + + +### Database Pool Concurrency + +Unlike [database queues](#database-queues), pools allow several threads to access the database at the same time: - When you don't need to modify the database, prefer the `read` method, because several threads can perform reads in parallel. Reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured](#databasepool-configuration). -- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called "snapshot isolation". +- Reads are guaranteed an immutable view of the last committed state of the database, regardless of concurrent writes. This kind of isolation is called [snapshot isolation](https://sqlite.org/isolation.html). - Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. -- The `write` and `writeInTransaction` methods always run your database statements in a transaction. There is also a `writeWithoutTransaction` method that allows you to precisely control database transactions, at the cost of concurrency subtleties. See the [Concurrency](#concurrency) chapter. +- The `write` method wraps your database statements in a transaction, and rollbacks on the first unhandled error. + + When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints) for more information. - Database pools can take [snapshots](#database-snapshots) of the database. -See [Differences between Database Queues and Pools](#differences-between-database-queues-and-pools) before you decide to use a database pool. When you're sure, see [Advanced DatabasePool](#advanced-databasepool) for more DatabasePool hotness. - -**A database pool needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. - -For a sample code that sets up a database pool on iOS, see [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift), and replace DatabaseQueue with DatabasePool. +See the [Concurrency](#concurrency) chapter for more details about database pools, and advanced use cases. ### DatabasePool Configuration @@ -502,7 +499,7 @@ Once granted with a [database connection](#database-connections), the `execute` For example: ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute(""" CREATE TABLE players ( id INTEGER PRIMARY KEY, @@ -551,7 +548,7 @@ let playerId = player.id **Rows** are the raw results of SQL queries: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in if let row = try Row.fetchOne(db, "SELECT * FROM wines WHERE id = ?", arguments: [1]) { let name: String = row["name"] let color: Color = row["color"] @@ -564,7 +561,7 @@ try dbQueue.inDatabase { db in **Values** are the Bool, Int, String, Date, Swift enums, etc. stored in row columns: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in let urls = try URL.fetchCursor(db, "SELECT url FROM wines") while let url = try urls.next() { print(url) @@ -576,7 +573,7 @@ try dbQueue.inDatabase { db in **Records** are your application objects that can initialize themselves from rows: ```swift -let wines = try dbQueue.inDatabase { db in +let wines = try dbQueue.read { db in try Wine.fetchAll(db, "SELECT * FROM wines") } ``` @@ -623,7 +620,7 @@ try Row.fetchOne(...) // Row? The `fetchAll()` method returns a regular Swift array, that you iterate like all other arrays: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // [Player] let players = try Player.fetchAll(db, "SELECT ...") for player in players { @@ -635,7 +632,7 @@ try dbQueue.inDatabase { db in Unlike arrays, cursors returned by `fetchCursor()` load their results step after step: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // Cursor of Player let players = try Player.fetchCursor(db, "SELECT ...") while let player = try players.next() { @@ -650,10 +647,10 @@ Both arrays and cursors can iterate over database results. How do you choose one ```swift // Wrong - let cursor = try dbQueue.inDatabase { try Player.fetchCursor($0, ...) } + let cursor = try dbQueue.read { try Player.fetchCursor($0, ...) } // OK - let array = try dbQueue.inDatabase { try Player.fetchAll($0, ...) } + let array = try dbQueue.read { try Player.fetchAll($0, ...) } ``` - **Cursors can be iterated only one time.** Arrays can be iterated many times. @@ -718,7 +715,7 @@ let hosts = try Set(cursor) // Set Fetch **cursors** of rows, **arrays**, or **single** rows (see [fetching methods](#fetching-methods)): ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Row.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Row try Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] try Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? @@ -731,7 +728,7 @@ try dbQueue.inDatabase { db in } } -let rows = try dbQueue.inDatabase { db in +let rows = try dbQueue.read { db in try Row.fetchAll(db, "SELECT * FROM players") } ``` @@ -978,7 +975,7 @@ See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://develo Instead of rows, you can directly fetch **[values](#values)**. Like rows, fetch them as **cursors**, **arrays**, or **single** values (see [fetching methods](#fetching-methods)). Values are extracted from the leftmost column of the SQL queries: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Int.fetchCursor(db, "SELECT ...", arguments: ...) // A Cursor of Int try Int.fetchAll(db, "SELECT ...", arguments: ...) // [Int] try Int.fetchOne(db, "SELECT ...", arguments: ...) // Int? @@ -988,7 +985,7 @@ try dbQueue.inDatabase { db in try Optional.fetchAll(db, "SELECT ...", arguments: ...) // [Int?] } -let playerCount = try dbQueue.inDatabase { db in +let playerCount = try dbQueue.read { db in try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! } ``` @@ -1273,11 +1270,18 @@ Grape.fromDatabaseValue(row[0]) // nil ### Transactions and Safety -**Transactions** are a fundamental concept of SQLite that guarantee [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. +**A transaction** is a fundamental tool of SQLite that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. -These are all important words for a database expert, but not all developers know them very well. That's why GRDB will generally open transactions for you, automatically, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic: +GRDB generally opens transactions for you, as a way to enforce its [concurrency guarantees](#concurrency), and provide maximal security for both your application data and application logic: ```swift +// BEGIN TRANSACTION +// INSERT INTO players ... +// COMMIT +try dbQueue.write { db in + try Player(...).insert(db) +} + // BEGIN TRANSACTION // INSERT INTO players ... // COMMIT @@ -1286,35 +1290,64 @@ try dbPool.write { db in } ``` -**Yet some users need to control exactly when transactions take place.** This is an advanced use case, described below. +Yet you may need to exactly control when transactions take place: ### Explicit Transactions -`DatabaseQueue.inTransaction()` and `DatabasePool.writeInTransaction()` open an SQLite transaction and run their closure argument in a protected dispatch queue. They block the current thread until your database statements are executed: +`DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: + +```swift +// INSERT INTO players (...) +try dbQueue.inDatabase { db in + try Player(...).insert(db) +} + +// INSERT INTO players (...) +try dbPool.writeWithoutTransaction { db in + try Player(...).insert(db) +} +``` + +> :warning: **Warning**: it is dangerous to write in a database pool outside of a transaction, because concurrent reads may see an inconsistent state of the database: +> +> ```swift +> // UNSAFE CONCURRENCY +> try dbPool.writeWithoutTransaction { db in +> try Credit(destinationAccout, amount).insert(db) +> // <- Concurrent dbPool.read sees a partial db update here +> try Debit(sourceAccount, amount).insert(db) +> } +> ``` + +To open explicit transactions, use one of the `Database.inTransaction`, `DatabaseQueue.inTransaction`, or `DatabasePool.writeInTransaction` methods: ```swift // BEGIN TRANSACTION -// INSERT INTO wines (...) +// INSERT INTO players ... // COMMIT -try dbQueue.inTransaction { db in - let wine = Wine(color: .red, name: "Pomerol") - try wine.insert(db) +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try db.inTransaction { + try Player(...).insert(db) + return .commit + } +} + +// BEGIN TRANSACTION +// INSERT INTO players (...) +// COMMIT +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try Player(...).insert(db) return .commit } ``` -If an error is thrown within the transaction body, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` from your closure, the transaction is also rollbacked, but no error is thrown. +If an error is thrown from the transaction block, the transaction is rollbacked and the error is rethrown by the `inTransaction` method. If you return `.rollback` instead of `.commit`, the transaction is also rollbacked, but no error is thrown. -If you want to insert a transaction between other database statements, you can use the Database.inTransaction() function, or even raw SQL statements: +You can also perform manual transaction management: ```swift -try dbPool.writeWithoutTransaction { db in // or dbQueue.inDatabase { ... } - try db.inTransaction { - ... - return .commit - } - +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.beginTransaction() ... try db.commit() @@ -1325,7 +1358,17 @@ try dbPool.writeWithoutTransaction { db in // or dbQueue.inDatabase { ... } } ``` -You can ask a database if a transaction is currently opened: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) configuration flag: + +```swift +// fatal error: A transaction has been left opened at the end of a database access +try dbQueue.inDatabase { db in + try db.execute("BEGIN TRANSACTION") + // <- no commit or rollback +} +``` + +You can ask if a transaction is currently opened: ```swift func myCriticalMethod(_ db: Database) throws { @@ -1334,7 +1377,7 @@ func myCriticalMethod(_ db: Database) throws { } ``` -Yet, you have a better option than checking for transactions: critical sections of your application should use savepoints, described below: +Yet, you have a better option than checking for transactions: critical database sections should use savepoints, described below: ```swift func myCriticalMethod(_ db: Database) throws { @@ -1351,7 +1394,7 @@ func myCriticalMethod(_ db: Database) throws { **Statements grouped in a savepoint can be rollbacked without invalidating a whole transaction:** ```swift -try dbQueue.inTransaction { db in +try dbQueue.write { db in try db.inSavepoint { try db.execute("DELETE ...") try db.execute("INSERT ...") // need to rollback the delete above if this fails @@ -1359,13 +1402,12 @@ try dbQueue.inTransaction { db in } // Other savepoints, etc... - return .commit } ``` -If an error is thrown within the savepoint body, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` from your closure, the body is also rollbacked, but no error is thrown. +If an error is thrown from the savepoint block, the savepoint is rollbacked and the error is rethrown by the `inSavepoint` method. If you return `.rollback` instead of `.commit`, the savepoint is also rollbacked, but no error is thrown. -**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only committed to disk when the outermost savepoint is committed: +**Unlike transactions, savepoints can be nested.** They implicitly open a transaction if no one was opened when the savepoint begins. As such, they behave just like nested transactions. Yet the database changes are only written to disk when the outermost transaction is committed: ```swift try dbQueue.inDatabase { db in @@ -1381,7 +1423,7 @@ try dbQueue.inDatabase { db in } ``` -SQLite savepoints are more than nested transactions, though. For advanced savepoints uses, use [SQL queries](https://www.sqlite.org/lang_savepoint.html). +SQLite savepoints are more than nested transactions, though. For advanced uses, use [SQLite savepoint documentation](https://www.sqlite.org/lang_savepoint.html). ### Transaction Kinds @@ -1391,13 +1433,22 @@ SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transa The transaction kind can be changed in the database configuration, or for each transaction: ```swift -// Set the default transaction kind to IMMEDIATE: +// 1) Default configuration: +let dbQueue = try DatabaseQueue(path: "...") + +// BEGIN DEFERED TRANSACTION ... +dbQueue.write { db in ... } + +// BEGIN EXCLUSIVE TRANSACTION ... +dbQueue.inTransaction(.exclusive) { db in ... } + +// 2) Customized default transaction kind: var config = Configuration() config.defaultTransactionKind = .immediate let dbQueue = try DatabaseQueue(path: "...", configuration: config) // BEGIN IMMEDIATE TRANSACTION ... -dbQueue.inTransaction { db in ... } +dbQueue.write { db in ... } // BEGIN EXCLUSIVE TRANSACTION ... dbQueue.inTransaction(.exclusive) { db in ... } @@ -1432,7 +1483,7 @@ The `fromDatabaseValue()` factory method returns an instance of your custom type There are two kinds of prepared statements: **select statements**, and **update statements**: ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in let updateSQL = "INSERT INTO players (name, score) VALUES (:name, :score)" let updateStatement = try db.makeUpdateStatement(updateSQL) @@ -1520,7 +1571,7 @@ let reverse = DatabaseFunction("reverse", argumentCount: 1, pure: true) { (value } dbQueue.add(function: reverse) // Or dbPool.add(function: ...) -try dbQueue.inDatabase { db in +try dbQueue.read { db in // "oof" try String.fetchOne(db, "SELECT reverse('foo')")! } @@ -1542,7 +1593,7 @@ let averageOf = DatabaseFunction("averageOf", pure: true) { (values: [DatabaseVa } dbQueue.add(function: averageOf) -try dbQueue.inDatabase { db in +try dbQueue.read { db in // 2.0 try Double.fetchOne(db, "SELECT averageOf(1, 2, 3)")! } @@ -1564,7 +1615,7 @@ let sqrt = DatabaseFunction("sqrt", argumentCount: 1, pure: true) { (values: [Da dbQueue.add(function: sqrt) // SQLite error 1 with statement `SELECT sqrt(-1)`: invalid negative number -try dbQueue.inDatabase { db in +try dbQueue.read { db in try Double.fetchOne(db, "SELECT sqrt(-1)")! } ``` @@ -1629,7 +1680,7 @@ let maxLength = DatabaseFunction( dbQueue.add(function: maxLength) // Or dbPool.add(function: ...) -try dbQueue.inDatabase { db in +try dbQueue.read { db in // Some Int try Int.fetchOne(db, "SELECT maxLength(name) FROM players")! } @@ -1827,7 +1878,7 @@ let sqliteVersion = String(cString: sqlite3_libversion()) Raw pointers to database connections and statements are available through the `Database.sqliteConnection` and `Statement.sqliteStatement` properties: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in // The raw pointer to a database connection: let sqliteConnection = db.sqliteConnection @@ -1871,7 +1922,7 @@ Records **On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records": ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in if let place = try Place.fetchOne(db, key: 1) { place.isFavorite = true try place.update(db) @@ -2025,7 +2076,7 @@ Details follow: ```swift struct Place { ... } - try dbQueue.inDatabase { db in + try dbQueue.read { db in let rows = try Row.fetchAll(db, "SELECT * FROM places") let places: [Place] = rows.map { row in return Place( @@ -2043,7 +2094,7 @@ Details follow: ```swift struct Place: FetchableRecord { ... } - try dbQueue.inDatabase { db in + try dbQueue.read { db in let places = try Place.fetchAll(db, "SELECT * FROM places") } ``` @@ -2062,7 +2113,7 @@ Details follow: ```swift struct Place: TableRecord, FetchableRecord { ... } - try dbQueue.inDatabase { db in + try dbQueue.read { db in let places = try Place.order(Column("title")).fetchAll(db) let paris = try Place.fetchOne(key: 1) } @@ -2072,7 +2123,7 @@ Details follow: ```swift struct Place : PersistableRecord { ... } - try dbQueue.inDatabase { db in + try dbQueue.write { db in try Place.delete(db, key: 1) try Place(...).insert(db) } @@ -2398,7 +2449,7 @@ extension Player: FetchableRecord, PersistableRecord { } // ...and you can save and fetch players: -try dbQueue.inDatabase { db in +try dbQueue.write { db in try Player(name: "Arthur", score: 100).insert(db) let players = try Player.fetchAll(db) } @@ -2889,7 +2940,7 @@ The Query Interface **The query interface lets you write pure Swift instead of SQL:** ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in // Update database schema try db.create(table: "wines") { t in ... } @@ -2909,7 +2960,7 @@ You need to open a [database connection](#database-connections) before you can q Please bear in mind that the query interface can not generate all possible SQL queries. You may also *prefer* writing SQL, and this is just OK. From little snippets to full queries, your SQL skills are welcome: ```swift -try dbQueue.inDatabase { db in +try dbQueue.write { db in // Update database schema (with SQL) try db.execute("CREATE TABLE wines (...)") @@ -4711,7 +4762,7 @@ To split rows, we will use [row adapters](#row-adapters). Row adapters adapt row At the very beginning, there is an SQL query: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in let sql = """ SELECT players.*, teams.*, MAX(rounds.score) AS maxScore FROM players @@ -4874,7 +4925,7 @@ And when your app needs to fetch items, it now reads: ```swift // Fetch items -let items = try dbQueue.inDatabase { db in +let items = try dbQueue.read { db in try Item.fetchAll(db) } ``` @@ -4953,7 +5004,7 @@ It is now time to use our request: ```swift // Fetch items -let items = try dbQueue.inDatabase { db in +let items = try dbQueue.read { db in try Item.fetchAll(db) } @@ -5022,7 +5073,7 @@ extension Item { } // Fetch items -let items = try dbQueue.inDatabase { db in +let items = try dbQueue.read { db in try Item.fetchAll(db) } @@ -5174,23 +5225,27 @@ By default, database holds weak references to its transaction observers: they ar > :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). -Notified changes are not actually written to disk until `databaseDidCommit` is called. On the other side, `databaseDidRollback` confirms their invalidation: +Notified changes are not actually written to disk the [transaction](#transactions-and-savepoints) commits, and the until `databaseDidCommit` is called. On the other side, `databaseDidRollback` confirms their invalidation: ```swift -try dbQueue.inTransaction { db in +try dbQueue.write { db in try db.execute("INSERT ...") // 1. didChange try db.execute("UPDATE ...") // 2. didChange - return .commit // 3. willCommit, 4. didCommit -} +} // 3. willCommit, 4. didCommit try dbQueue.inTransaction { db in try db.execute("INSERT ...") // 1. didChange try db.execute("UPDATE ...") // 2. didChange return .rollback // 3. didRollback } + +try dbQueue.write { db in + try db.execute("INSERT ...") // 1. didChange + throw SomeError() // 2. throw +} // 3. didRollback ``` -Database statements that are executed outside of an explicit transaction do not drop off the radar: +Database statements that are executed outside of a transaction do not drop off the radar: ```swift try dbQueue.inDatabase { db in @@ -5308,7 +5363,7 @@ The `remove(transactionObserver:)` method explicitely stops notifications, at an dbQueue.remove(transactionObserver: observer) // From a database connection: -dbQueue.inDatabase { db in // or dbPool.write +dbQueue.inDatabase { db in db.remove(transactionObserver: observer) } ``` @@ -5411,7 +5466,7 @@ When you initialize a fetched records controller, you provide the following mand ```swift class Player : Record { ... } -let dbQueue = DatabaseQueue(...) // Or DatabasePool +let dbQueue = DatabaseQueue(...) // or DatabasePool // Using a Request from the Query Interface: let controller = FetchedRecordsController( @@ -5452,18 +5507,26 @@ try controller.performFetch() In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values. -Changes are not reflected until they are applied in the database by a successful [transaction](#transactions-and-savepoints). Transactions can be explicit, or implicit: +Changes are not reflected until they are applied in the database by a successful [transaction](#transactions-and-savepoints): ```swift -try dbQueue.inTransaction { db in +// One transaction +try dbQueue.write { db in // or dbPool.write try player1.insert(db) try player2.insert(db) - return .commit // Explicit transaction } -try dbQueue.inDatabase { db in - try player1.insert(db) // Implicit transaction - try player2.insert(db) // Implicit transaction +// One transaction +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + try player1.insert(db) + try player2.insert(db) + return .commit +} + +// Two transactions +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction + try player1.insert(db) + try player2.insert(db) } ``` @@ -5691,7 +5754,7 @@ When the database itself can be read and modified from [any thread](#database-co ```swift // Change database on the main thread: -try dbQueue.inDatabase { db in +try dbQueue.write { db in try Player(...).insert(db) } // Here callbacks have not been called yet. @@ -5822,7 +5885,7 @@ Here is an example of code that is vulnerable to SQL injection: ```swift // BAD BAD BAD let name = textField.text -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute("UPDATE students SET name = '\(name)' WHERE id = \(id)") } ``` @@ -5840,7 +5903,7 @@ To avoid those problems, **never embed raw values in your SQL queries**. The onl ```swift // Good let name = textField.text -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute( "UPDATE students SET name = ? WHERE id = ?", arguments: [name, id]) @@ -6001,8 +6064,8 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are ```swift // fatal error: Database methods are not reentrant. - dbQueue.inDatabase { db in - dbQueue.inDatabase { db in + dbQueue.write { db in + dbQueue.write { db in ... } } @@ -6252,7 +6315,7 @@ GRDB ships with three concurrency modes: - :bowtie: **Guarantee 2: reads are always isolated**. This means that they are guaranteed an immutable view of the last committed state of the database, and that you can perform subsequent fetches without fearing eventual concurrent writes to mess with your application logic: ```swift - try dbPool.read { db in // or dbQueue.inDatabase { ... } + try dbPool.read { db in // or dbQueue.read // Guaranteed to be equal let count1 = try Player.fetchCount(db) let count2 = try Player.fetchCount(db) @@ -6281,7 +6344,7 @@ Those guarantees hold as long as you follow three rules: return try User.fetchOne(db) } // dbQueue is a singleton defined somewhere in your app - let user = try dbQueue.inDatabase { db in // or dbPool.read { ... } + let user = try dbQueue.read { db in // or dbPool.read try currentUser(db) } @@ -6290,7 +6353,7 @@ Those guarantees hold as long as you follow three rules: // the database. func currentUser() throws -> User? { let dbQueue = try DatabaseQueue(...) - return try dbQueue.inDatabase { db in + return try dbQueue.read { db in try User.fetchOne(db) } } @@ -6303,7 +6366,7 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY - try dbPool.read { db in // or dbQueue.inDatabase { ... } + try dbPool.read { db in // or dbQueue.read // Guaranteed to be equal: let count1 = try Place.fetchCount(db) let count2 = try Place.fetchCount(db) @@ -6339,13 +6402,13 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY - try dbPool.write { db in // or dbQueue.inDatabase { ... } + try dbPool.write { db in // or dbQueue.write try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } // SAFE CONCURRENCY - try dbPool.writeInTransaction { db in // or dbQueue.inTransaction { ... } + try dbPool.writeInTransaction { db in // or dbQueue.inTransaction try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) return .commit @@ -6571,7 +6634,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant calls are allowed: ```swift - dbQueue.inDatabase { db1 in + dbQueue.write { db1 in // No "Database methods are not reentrant" fatal error: dbQueue.unsafeReentrantWrite { db2 in dbQueue.unsafeReentrantWrite { db3 in @@ -6635,7 +6698,7 @@ Most GRBD APIs are [synchronous](#database-connections). Spawning them into para ```swift DispatchQueue.global().async { - dbQueue.inDatabase { db in + dbQueue.write { db in // Perform database work } DispatchQueue.main.async { @@ -6651,18 +6714,25 @@ Performing multiple updates to the database is much faster when executed inside ```swift // Inefficient -try dbQueue.inDatabase { db in +try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction for player in players { try player.insert(db) } } // Efficient -try dbQueue.inTransaction { db in +try dbQueue.write { db in // or dbPool.write for player in players { try player.insert(db) } - return .Commit +} + +// Efficient +try dbQueue.inTransaction { db in // or dbPool.writeInTransaction + for player in players { + try player.insert(db) + } + return .commit } ``` @@ -6903,7 +6973,7 @@ When you want to debug a request that does not deliver the expected results, you Use the `asSQLRequest` method: ```swift -try dbQueue.inDatabase { db in +try dbQueue.read { db in let request = Wine .filter(Column("origin") == "Burgundy") .order(Column("price") @@ -6923,7 +6993,7 @@ var config = Configuration() config.trace = { print("SQL: \($0)") } // Prints all SQL statements let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) -try dbQueue.inDatabase { db in +try dbQueue.read { db in let wines = Wine .filter(Column("origin") == "Burgundy") .order(Column("price") @@ -6935,11 +7005,11 @@ try dbQueue.inDatabase { db in ### Generic parameter 'T' could not be inferred -You may get this error when using DatabaseQueue.inDatabase, DatabasePool.read, or DatabasePool.write: +You may get this error when using the `read` and `write` methods of database queues and pools: ```swift // Generic parameter 'T' could not be inferred -let x = try dbQueue.inDatabase { db in +let x = try dbQueue.read { db in let result = try String.fetchOne(db, ...) return result } @@ -6951,7 +7021,7 @@ The general workaround is to explicitly declare the type of the closure result: ```swift // General Workaround -let string = try dbQueue.inDatabase { db -> String? in +let string = try dbQueue.read { db -> String? in let result = try String.fetchOne(db, ...) return result } @@ -6961,7 +7031,7 @@ You can also, when possible, write a single-line closure: ```swift // Single-line closure workaround: -let string = try dbQueue.inDatabase { db in +let string = try dbQueue.read { db in try String.fetchOne(db, ...) } ``` From 3d9c1a2739d5aa35bec1d448ca8eb5b87d652bfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 17:26:37 +0200 Subject: [PATCH 078/348] Cleanup --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b2db51fc7..b1dc8b17f 100644 --- a/README.md +++ b/README.md @@ -6340,12 +6340,12 @@ Those guarantees hold as long as you follow three rules: ```swift // SAFE CONCURRENCY - func currentUser(_ db: Database) throws -> User? { + func fetchCurrentUser(_ db: Database) throws -> User? { return try User.fetchOne(db) } // dbQueue is a singleton defined somewhere in your app let user = try dbQueue.read { db in // or dbPool.read - try currentUser(db) + try fetchCurrentUser(db) } // UNSAFE CONCURRENCY @@ -6625,7 +6625,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling. + There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. - **`unsafeReentrantWrite`** @@ -6646,7 +6646,7 @@ DatabaseWriter and DatabaseReader fuel, for example: Reentrant database accesses make it very easy to break the second [safety rule](#guarantees-and-rules), which says: "group related statements within a single call to a DatabaseQueue or DatabasePool database access method.". Using a reentrant method is pretty much likely the sign of a wrong application architecture that needs refactoring. - Reentrant methods have been introduced in order to support [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), a set of reactive extensions to GRDB based on [RxSwift](https://github.com/ReactiveX/RxSwift) that need precise scheduling. + There is a single valid use case for reentrant methods, which is when you are unable to control database access scheduling. ### Dealing with External Connections From 090f872e800e1b60d0777c246a4f9655b4e834c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 18:09:34 +0200 Subject: [PATCH 079/348] Update documentation: don't mention dbQueue.inDatabase unless necessary --- GRDB/Core/Database.swift | 4 ++-- GRDB/Core/DatabaseFunction.swift | 4 ++-- GRDB/Core/DatabaseQueue.swift | 4 ++-- GRDB/Core/DatabaseValueConvertible.swift | 4 ++-- GRDB/Core/Row.swift | 2 +- GRDB/Core/Statement.swift | 4 ++-- GRDB/Core/StatementColumnConvertible.swift | 4 ++-- GRDB/Record/FetchableRecord.swift | 2 +- GRDB/Record/TableRecord.swift | 2 +- 9 files changed, 15 insertions(+), 15 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ef87817d6..ee961927b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -21,8 +21,8 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// let dbQueue = DatabaseQueue(...) /// /// // The Database is the `db` in the closure: -/// try dbQueue.inDatabase { db in -/// try db.execute(...) +/// try dbQueue.write { db in +/// try Player(...).insert(db) /// } public final class Database { // The Database class is not thread-safe. An instance should always be diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 873a3e922..257740ff1 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -82,7 +82,7 @@ public final class DatabaseFunction: Hashable { /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// dbQueue.add(function: fn) - /// try dbQueue.inDatabase { db in + /// try dbQueue.write { db in /// try db.execute("CREATE TABLE test(i)") /// try db.execute("INSERT INTO test(i) VALUES (1)") /// try db.execute("INSERT INTO test(i) VALUES (2)") @@ -357,7 +357,7 @@ extension DatabaseFunction { /// let dbQueue = DatabaseQueue() /// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self) /// dbQueue.add(function: fn) -/// try dbQueue.inDatabase { db in +/// try dbQueue.write { db in /// try db.execute("CREATE TABLE test(i)") /// try db.execute("INSERT INTO test(i) VALUES (1)") /// try db.execute("INSERT INTO test(i) VALUES (2)") diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index e7c4194b1..d0e1bb4ce 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -329,7 +329,7 @@ extension DatabaseQueue { /// return int + 1 /// } /// dbQueue.add(function: fn) - /// try dbQueue.inDatabase { db in + /// try dbQueue.read { db in /// try Int.fetchOne(db, "SELECT succ(1)") // 2 /// } public func add(function: DatabaseFunction) { @@ -349,7 +349,7 @@ extension DatabaseQueue { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// dbQueue.add(collation: collation) - /// try dbQueue.inDatabase { db in + /// try dbQueue.write { db in /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index ea14adeff..79cc15c89 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -41,7 +41,7 @@ extension DatabaseValueConvertible { /// A cursor of database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM links") /// while let url = urls.next() { // URL /// print(url) @@ -81,7 +81,7 @@ public final class DatabaseValueCursor : Cursor /// A cursor of optional database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM links") /// while let url = urls.next() { // URL? /// print(url) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 77abae6bc..16975da37 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -566,7 +566,7 @@ extension Row { /// A cursor of database rows. For example: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players") /// } public final class RowCursor : Cursor { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index c84ac6e1e..6219108f1 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -286,7 +286,7 @@ extension AuthorizedStatement { /// /// You create SelectStatement with the Database.makeSelectStatement() method: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! @@ -372,7 +372,7 @@ extension SelectStatement: AuthorizedStatement { } /// A cursor that iterates a database statement without producing any value. /// For example: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let statement = db.makeSelectStatement("SELECT * FROM players") /// let cursor: StatementCursor = statement.cursor() /// } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 1df56baf0..d60ad247c 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -74,7 +74,7 @@ extension StatementColumnConvertible { /// A cursor of database values extracted from a single column. /// For example: /// -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM players") /// while let name = names.next() { // String /// print(name) @@ -120,7 +120,7 @@ public final class ColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM players") /// while let email = emails.next() { // String? /// print(email ?? "") diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index aaf103b20..29a770d06 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -35,7 +35,7 @@ public protocol FetchableRecord { /// A cursor of records. For example: /// /// struct Player : FetchableRecord { ... } -/// try dbQueue.inDatabase { db in +/// try dbQueue.read { db in /// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") /// } public final class RecordCursor : Cursor { diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index a24c21c7e..82bf379e2 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -102,7 +102,7 @@ extension TableRecord { /// static let databaseTableName = "players" /// } /// - /// try dbQueue.inDatabase { db in + /// try dbQueue.write { db in /// try db.create(table: "players") { t in /// t.column("id", .integer).primaryKey() /// t.column("name", .text) From ba848d2d539bb1a4b3bb73a32576910e4da9dd86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 19:57:36 +0200 Subject: [PATCH 080/348] Less TODO --- TODO.md | 1 - 1 file changed, 1 deletion(-) diff --git a/TODO.md b/TODO.md index 81a16f481..2dc3963ac 100644 --- a/TODO.md +++ b/TODO.md @@ -22,7 +22,6 @@ GRDB 3.0 - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] HiddenColumnsAdapter - [ ] If possible: Have Record adopt Codable -- [ ] Not sure: Have DatabaseQueue wrap writes in a transaction by default Not sure From c9dc1223dd78e0f5aa0fc658f42abfd3a70086a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Apr 2018 20:14:25 +0200 Subject: [PATCH 081/348] Harmonize dbQueue.writer with dbPool.writer --- GRDB/Core/DatabaseQueue.swift | 40 +++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index d0e1bb4ce..fac705911 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -6,7 +6,7 @@ import UIKit /// A DatabaseQueue serializes access to an SQLite database. public final class DatabaseQueue: DatabaseWriter { - private var serializedDatabase: SerializedDatabase + private var writer: SerializedDatabase #if os(iOS) private weak var application: UIApplication? #endif @@ -15,12 +15,12 @@ public final class DatabaseQueue: DatabaseWriter { /// The database configuration public var configuration: Configuration { - return serializedDatabase.configuration + return writer.configuration } /// The path to the database file; it is ":memory:" for in-memory databases. public var path: String { - return serializedDatabase.path + return writer.path } // MARK: - Initializers @@ -36,7 +36,7 @@ public final class DatabaseQueue: DatabaseWriter { /// - configuration: A configuration. /// - throws: A DatabaseError whenever an SQLite error occurs. public init(path: String, configuration: Configuration = Configuration()) throws { - serializedDatabase = try SerializedDatabase( + writer = try SerializedDatabase( path: path, configuration: configuration, schemaCache: SimpleDatabaseSchemaCache()) @@ -51,7 +51,7 @@ public final class DatabaseQueue: DatabaseWriter { /// - parameter configuration: A configuration. public init(configuration: Configuration = Configuration()) { // Assume SQLite always succeeds creating an in-memory database - serializedDatabase = try! SerializedDatabase( + writer = try! SerializedDatabase( path: ":memory:", configuration: configuration, schemaCache: SimpleDatabaseSchemaCache()) @@ -78,7 +78,7 @@ extension DatabaseQueue { /// /// See also setupMemoryManagement(application:) public func releaseMemory() { - serializedDatabase.sync { $0.releaseMemory() } + writer.sync { $0.releaseMemory() } } #if os(iOS) @@ -131,7 +131,7 @@ extension DatabaseQueue { /// Changes the passphrase of an encrypted database public func change(passphrase: String) throws { - try serializedDatabase.sync { try $0.change(passphrase: passphrase) } + try writer.sync { try $0.change(passphrase: passphrase) } } } #endif @@ -156,7 +156,7 @@ extension DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func read(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync { db in + return try writer.sync { db in try db.readOnly { try block(db) } } } @@ -175,7 +175,7 @@ extension DatabaseQueue { /// /// :nodoc: public func unsafeRead(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + return try writer.sync(block) } /// Synchronously executes a block in a protected dispatch queue, and @@ -190,7 +190,7 @@ extension DatabaseQueue { /// /// :nodoc: public func unsafeReentrantRead(_ block: (Database) throws -> T) throws -> T { - return try serializedDatabase.reentrantSync(block) + return try writer.reentrantSync(block) } /// Synchronously executes *block*. @@ -207,7 +207,7 @@ extension DatabaseQueue { /// :nodoc: public func readFromCurrentState(_ block: @escaping (Database) -> Void) { // Check that we're on the correct queue... - serializedDatabase.execute { db in + writer.execute { db in // ... and that no transaction is opened. GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.") db.readOnly { block(db) } @@ -231,7 +231,7 @@ extension DatabaseQueue { /// - parameter block: A block that executes SQL statements. /// - throws: An eventual database error, or the error thrown by the block. public func write(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync { db in + return try writer.sync { db in var result: T? = nil try db.inTransaction { result = try block(db) @@ -264,7 +264,7 @@ extension DatabaseQueue { /// .commit or .rollback. /// - throws: The error thrown by the block. public func inTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { - try serializedDatabase.sync { db in + try writer.sync { db in try db.inTransaction(kind) { try block(db) } @@ -285,7 +285,7 @@ extension DatabaseQueue { /// /// :nodoc: public func writeWithoutTransaction(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + return try writer.sync(block) } /// Synchronously executes a block in a protected dispatch queue, and @@ -301,7 +301,7 @@ extension DatabaseQueue { /// - parameter block: A block that accesses the database. /// - throws: The error thrown by the block. public func inDatabase(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.sync(block) + return try writer.sync(block) } /// Synchronously executes a block in a protected dispatch queue, and @@ -315,7 +315,7 @@ extension DatabaseQueue { /// This method is reentrant. It is unsafe because it fosters dangerous /// concurrency practices. public func unsafeReentrantWrite(_ block: (Database) throws -> T) rethrows -> T { - return try serializedDatabase.reentrantSync(block) + return try writer.reentrantSync(block) } // MARK: - Functions @@ -333,12 +333,12 @@ extension DatabaseQueue { /// try Int.fetchOne(db, "SELECT succ(1)") // 2 /// } public func add(function: DatabaseFunction) { - serializedDatabase.sync { $0.add(function: function) } + writer.sync { $0.add(function: function) } } /// Remove an SQL function. public func remove(function: DatabaseFunction) { - serializedDatabase.sync { $0.remove(function: function) } + writer.sync { $0.remove(function: function) } } // MARK: - Collations @@ -353,12 +353,12 @@ extension DatabaseQueue { /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { - serializedDatabase.sync { $0.add(collation: collation) } + writer.sync { $0.add(collation: collation) } } /// Remove a collation. public func remove(collation: DatabaseCollation) { - serializedDatabase.sync { $0.remove(collation: collation) } + writer.sync { $0.remove(collation: collation) } } } From d39f02113c1028efa58d4a56aa133995c10ed9d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 16 Apr 2018 08:50:55 +0200 Subject: [PATCH 082/348] Restore T.fetchXXX(db, request) APIs which were removed in PR #311 --- GRDB/Core/DatabaseValueConvertible.swift | 120 ++++++++++++++++-- GRDB/Core/Row.swift | 78 +++++++++++- GRDB/Core/StatementColumnConvertible.swift | 116 +++++++++++++++-- GRDB/Record/FetchableRecord.swift | 70 ++++++++-- README.md | 37 +++--- .../DatabaseValueConvertibleFetchTests.swift | 34 +++++ ...bleRecord+QueryInterfaceRequestTests.swift | 6 +- Tests/GRDBTests/FetchableRecordTests.swift | 20 +++ .../QueryInterfaceExtensibilityTests.swift | 4 +- .../QueryInterfaceRequestTests.swift | 16 +-- Tests/GRDBTests/RowFetchTests.swift | 20 +++ ...StatementColumnConvertibleFetchTests.swift | 32 +++++ ...bleRecord+QueryInterfaceRequestTests.swift | 8 +- Tests/GRDBTests/TableRecordTests.swift | 6 +- 14 files changed, 494 insertions(+), 73 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index 79cc15c89..eb951b785 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -255,6 +255,67 @@ extension DatabaseValueConvertible { } } +extension DatabaseValueConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchCursor(db, request) // Cursor of String + /// while let name = try name.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> DatabaseValueCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchAll(db, request) // [String] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single value fetched from a fetch request. + /// + /// The result is nil if the query returns no row, or if no value can be + /// extracted from the first row. + /// + /// let request = Player.filter(key: 1).select(Column("name")) + /// let name = try String.fetchOne(db, request) // String? + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: DatabaseValueConvertible { // MARK: Fetching Values @@ -276,8 +337,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchCursor(statement, adapter: adapter) + return try RowDecoder.fetchCursor(db, self) } /// An array of fetched values. @@ -289,8 +349,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchAll(statement, adapter: adapter) + return try RowDecoder.fetchAll(db, self) } /// The first fetched value. @@ -305,8 +364,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchOne(statement, adapter: adapter) + return try RowDecoder.fetchOne(db, self) } } @@ -407,6 +465,49 @@ extension Optional where Wrapped: DatabaseValueConvertible { } } +extension Optional where Wrapped: DatabaseValueConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchCursor(db, request) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchAll(db, request) // [String?] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible { // MARK: Fetching Optional values @@ -428,8 +529,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor { - let (statement, adapter) = try prepare(db) - return try Optional.fetchCursor(statement, adapter: adapter) + return try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -441,7 +541,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - let (statement, adapter) = try prepare(db) - return try Optional.fetchAll(statement, adapter: adapter) + return try Optional.fetchAll(db, self) } } + diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 16975da37..3024e3835 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -735,6 +735,73 @@ extension Row { } } +extension Row { + + // MARK: - Fetching From FetchRequest + + /// Returns a cursor over rows fetched from a fetch request. + /// + /// let request = Player.all() + /// let rows = try Row.fetchCursor(db, request) // RowCursor + /// while let row = try rows.next() { // Row + /// let id: Int64 = row["id"] + /// let name: String = row["name"] + /// } + /// + /// Fetched rows are reused during the cursor iteration: don't turn a row + /// cursor into an array with `Array(rows)` or `rows.filter { ... }` since + /// you would not get the distinct rows you expect. Use `Row.fetchAll(...)` + /// instead. + /// + /// For the same reason, make sure you make a copy whenever you extract a + /// row for later use: `row.copy()`. + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> RowCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of rows fetched from a fetch request. + /// + /// let request = Player.all() + /// let rows = try Row.fetchAll(db, request) + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of rows. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Row] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single row fetched from a fetch request. + /// + /// let request = Player.filter(key: 1) + /// let row = try Row.fetchOne(db, request) + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional row. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Row? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: Row { // MARK: Fetching Rows @@ -765,8 +832,7 @@ extension FetchRequest where RowDecoder: Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RowCursor { - let (statement, adapter) = try prepare(db) - return try Row.fetchCursor(statement, adapter: adapter) + return try Row.fetchCursor(db, self) } /// An array of fetched rows. @@ -778,8 +844,7 @@ extension FetchRequest where RowDecoder: Row { /// - returns: An array of fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [Row] { - let (statement, adapter) = try prepare(db) - return try Row.fetchAll(statement, adapter: adapter) + return try Row.fetchAll(db, self) } /// The first fetched row. @@ -791,11 +856,10 @@ extension FetchRequest where RowDecoder: Row { /// - returns: A,n optional rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> Row? { - let (statement, adapter) = try prepare(db) - return try Row.fetchOne(statement, adapter: adapter) + return try Row.fetchOne(db, self) } } - + // ExpressibleByDictionaryLiteral extension Row { diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index d60ad247c..2a1dc14e7 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -283,6 +283,64 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { } } +extension DatabaseValueConvertible where Self: StatementColumnConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchCursor(db, request) // Cursor of String + /// while let name = try names.next() { // String + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> ColumnCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try String.fetchAll(db, request) // [String] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single value fetched from a fetch request. + /// + /// let request = Player.filter(key: 1).select(Column("name")) + /// let name = try String.fetchOne(db, request) // String? + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An optional value. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible { // MARK: Fetching Values @@ -304,8 +362,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> ColumnCursor { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchCursor(statement, adapter: adapter) + return try RowDecoder.fetchCursor(db, self) } /// An array of fetched values. @@ -317,8 +374,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchAll(statement, adapter: adapter) + return try RowDecoder.fetchAll(db, self) } /// The first fetched value. @@ -333,8 +389,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchOne(statement, adapter: adapter) + return try RowDecoder.fetchOne(db, self) } } @@ -435,6 +490,49 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv } } +extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchCursor(db, request) // Cursor of String? + /// while let name = try names.next() { // String? + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: A cursor over fetched optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> NullableColumnCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of optional values fetched from a fetch request. + /// + /// let request = Player.select(Column("name")) + /// let names = try Optional.fetchAll(db, request) // [String?] + /// + /// - parameters: + /// - db: A database connection. + /// - request: A FetchRequest. + /// - returns: An array of optional values. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Wrapped?] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible { // MARK: Fetching Optional values @@ -456,8 +554,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> NullableColumnCursor { - let (statement, adapter) = try prepare(db) - return try Optional.fetchCursor(statement, adapter: adapter) + return try Optional.fetchCursor(db, self) } /// An array of fetched optional values. @@ -469,7 +566,6 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] { - let (statement, adapter) = try prepare(db) - return try Optional.fetchAll(statement, adapter: adapter) + return try Optional.fetchAll(db, self) } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 29a770d06..31cc9bd1b 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -183,9 +183,67 @@ extension FetchableRecord { } } +extension FetchableRecord { + + // MARK: Fetching From FetchRequest + + /// Returns a cursor over records fetched from a fetch request. + /// + /// let request = try Player.all() + /// let players = try Player.fetchCursor(db, request) // Cursor of Player + /// while let player = try players.next() { // Player + /// ... + /// } + /// + /// If the database is modified during the cursor iteration, the remaining + /// elements are undefined. + /// + /// The cursor must be iterated in a protected dispath queue. + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: A cursor over fetched records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchCursor(_ db: Database, _ request: R) throws -> RecordCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + /// Returns an array of records fetched from a fetch request. + /// + /// let request = try Player.all() + /// let players = try Player.fetchAll(db, request) // [Player] + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: An array of records. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchAll(_ db: Database, _ request: R) throws -> [Self] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + /// Returns a single record fetched from a fetch request. + /// + /// let request = try Player.filter(key: 1) + /// let player = try Player.fetchOne(db, request) // Player? + /// + /// - parameters: + /// - db: A database connection. + /// - sql: a FetchRequest. + /// - returns: An optional record. + /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. + public static func fetchOne(_ db: Database, _ request: R) throws -> Self? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + extension FetchRequest where RowDecoder: FetchableRecord { - // MARK: Fetching Record and FetchableRecord + // MARK: Fetching Records /// A cursor over fetched records. /// @@ -204,8 +262,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchCursor(statement, adapter: adapter) + return try RowDecoder.fetchCursor(db, self) } /// An array of fetched records. @@ -217,8 +274,7 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchAll(statement, adapter: adapter) + return try RowDecoder.fetchAll(db, self) } /// The first fetched record. @@ -230,8 +286,6 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { - let (statement, adapter) = try prepare(db) - return try RowDecoder.fetchOne(statement, adapter: adapter) + return try RowDecoder.fetchOne(db, self) } } - diff --git a/README.md b/README.md index b1dc8b17f..6481f8ba4 100644 --- a/README.md +++ b/README.md @@ -1697,9 +1697,7 @@ SQLite has the opportunity to perform additional optimizations when aggregates a ```swift // SELECT maxLength("name") FROM players -Player.select(maxLength.apply(nameColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ``` @@ -3579,18 +3577,25 @@ let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player? **When the selected columns don't fit the source type**, change your target: any other type that adopts the [FetchableRecord] protocol, plain [database rows](#fetching-rows), and even [values](#values): ```swift -let maxScore = try Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +let request = Player.select(max(scoreColumn)) +let maxScore = try Int.fetchOne(db, request) // Int? -let row = try Player.select(min(scoreColumn), max(scoreColumn)) - .asRequest(of: Row.self) - .fetchOne(db)! +let request = Player.select(min(scoreColumn), max(scoreColumn)) +let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -More information about `asRequest(of:)` can be found in the [Custom Requests](#custom-requests) chapter. +You may also use the `asRequest(of:)` method, which lets you alter the type of the request itself, and feed database observation tools like [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): + +```swift +let request = Player.select(max(scoreColumn)).asRequest(of: Int.self) +request.rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { maxScore: Int? in + print("Maximum score has changed") + }) +``` ## Fetching By Key @@ -3689,19 +3694,15 @@ let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db) **Other aggregated values** can also be selected and fetched (see [SQL Functions](#sql-functions)): ```swift -let maxScore = try Player.select(max(scoreColumn)) - .asRequest(of: Int.self) - .fetchOne(db) // Int? +let request = Player.select(max(scoreColumn)) +let maxScore = try Int.fetchOne(db, request) // Int? -let row = try Player.select(min(scoreColumn), max(scoreColumn)) - .asRequest(of: Row.self) - .fetchOne(db)! +let request = Player.select(min(scoreColumn), max(scoreColumn)) +let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? ``` -More information about `asRequest(of:)` can be found in the [Custom Requests](#custom-requests) chapter. - ## Delete Requests diff --git a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift index ffdd12fe6..8501da8f4 100644 --- a/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift +++ b/Tests/GRDBTests/DatabaseValueConvertibleFetchTests.swift @@ -41,6 +41,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -49,6 +50,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -83,6 +85,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -90,6 +93,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -113,6 +117,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -120,6 +125,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -136,6 +142,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -144,6 +151,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -169,6 +177,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -176,6 +185,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -199,6 +209,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -206,6 +217,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -223,6 +235,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -231,6 +244,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -243,6 +257,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -251,6 +266,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -263,6 +279,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -271,6 +288,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -297,6 +315,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -304,6 +323,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -327,6 +347,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -334,6 +355,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -354,6 +376,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) + try test(Optional.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -362,6 +385,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -396,6 +420,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -403,6 +428,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -426,6 +452,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -433,6 +460,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -451,6 +479,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) + try test(Optional.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -459,6 +488,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -484,6 +514,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -491,6 +522,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -514,6 +546,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -521,6 +554,7 @@ class DatabaseValueConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } diff --git a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift index 7363a7753..6eb9671fa 100644 --- a/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/FetchableRecord+QueryInterfaceRequestTests.swift @@ -158,7 +158,7 @@ class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { let request = Reader.all() do { - let readers = try request.asRequest(of: AltReader.self).fetchAll(db) + let readers = try AltReader.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(readers.count, 2) XCTAssertEqual(readers[0].id!, arthur.id!) @@ -170,7 +170,7 @@ class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { } do { - let reader = try request.asRequest(of: AltReader.self).fetchOne(db)! + let reader = try AltReader.fetchOne(db, request)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(reader.id!, arthur.id!) XCTAssertEqual(reader.name, arthur.name) @@ -178,7 +178,7 @@ class FetchableRecordQueryInterfaceRequestTests: GRDBTestCase { } do { - let names = try request.asRequest(of: AltReader.self).fetchCursor(db).map { $0.name } + let names = try AltReader.fetchCursor(db, request).map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(try names.next()!, arthur.name) XCTAssertEqual(try names.next()!, barbara.name) diff --git a/Tests/GRDBTests/FetchableRecordTests.swift b/Tests/GRDBTests/FetchableRecordTests.swift index 3ca8be371..a928b9ef4 100644 --- a/Tests/GRDBTests/FetchableRecordTests.swift +++ b/Tests/GRDBTests/FetchableRecordTests.swift @@ -45,6 +45,7 @@ class FetchableRecordTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -53,6 +54,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -87,6 +89,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -94,6 +97,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -117,6 +121,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -124,6 +129,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -141,6 +147,7 @@ class FetchableRecordTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -149,6 +156,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -174,6 +182,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -181,6 +190,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -204,6 +214,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -211,6 +222,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -228,6 +240,7 @@ class FetchableRecordTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -236,6 +249,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -249,6 +263,7 @@ class FetchableRecordTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -257,6 +272,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -283,6 +299,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -290,6 +307,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -313,6 +331,7 @@ class FetchableRecordTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -320,6 +339,7 @@ class FetchableRecordTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } diff --git a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift index b415dd871..f2d5c55c6 100644 --- a/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExtensibilityTests.swift @@ -68,7 +68,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.execute("INSERT INTO records (date) VALUES (?)", arguments: [date]) let request = Record.select(strftime("%Y", Column("date"))) - let year = try request.asRequest(of: Int.self).fetchOne(db) + let year = try Int.fetchOne(db, request) XCTAssertEqual(year, 1970) XCTAssertEqual(self.lastSQLQuery, "SELECT STRFTIME('%Y', \"date\") FROM \"records\"") } @@ -105,7 +105,7 @@ class QueryInterfaceExtensibilityTests: GRDBTestCase { try db.execute("INSERT INTO records (text) VALUES (?)", arguments: ["foo"]) let request = Record.select(cast(Column("text"), as: .blob)) - let dbValue = try request.asRequest(of: DatabaseValue.self).fetchOne(db)! + let dbValue = try DatabaseValue.fetchOne(db, request)! switch dbValue.storage { case .blob: break diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index f1d71d783..754aa8057 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -51,7 +51,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) do { - let rows = try tableRequest.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, tableRequest) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0]["id"] as Int64, 1) @@ -63,7 +63,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { } do { - let row = try tableRequest.asRequest(of: Row.self).fetchOne(db)! + let row = try Row.fetchOne(db, tableRequest)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(row["id"] as Int64, 1) XCTAssertEqual(row["name"] as String, "Arthur") @@ -72,7 +72,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { var names: [String] = [] - let rows = try tableRequest.asRequest(of: Row.self).fetchCursor(db) + let rows = try Row.fetchCursor(db, tableRequest) while let row = try rows.next() { names.append(row["name"]) } @@ -139,7 +139,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - 1") - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -156,7 +156,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - ?", arguments: [1]) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -173,7 +173,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(sql: "name, id - :n", arguments: ["n": 1]) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -190,7 +190,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = tableRequest.select(Col.name, Col.id - 1) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -206,7 +206,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) let request = tableRequest.select(Col.name.aliased("nom"), (Col.age + 1).aliased("agePlusOne")) - let row = try request.asRequest(of: Row.self).fetchOne(db)! + let row = try Row.fetchOne(db, request)! XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", (\"age\" + 1) AS \"agePlusOne\" FROM \"readers\"") XCTAssertEqual(row["nom"] as String, "Arthur") XCTAssertEqual(row["agePlusOne"] as Int, 43) diff --git a/Tests/GRDBTests/RowFetchTests.swift b/Tests/GRDBTests/RowFetchTests.swift index 0586ebc28..617aba94d 100644 --- a/Tests/GRDBTests/RowFetchTests.swift +++ b/Tests/GRDBTests/RowFetchTests.swift @@ -34,6 +34,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchCursor(db, sql)) try test(Row.fetchCursor(statement)) + try test(Row.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -42,6 +43,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter)) try test(Row.fetchCursor(statement, adapter: adapter)) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -76,6 +78,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw(), NULL" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -83,6 +86,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -106,6 +110,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchCursor(db, sql), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -113,6 +118,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Row.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -130,6 +136,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchAll(db, sql)) try test(Row.fetchAll(statement)) + try test(Row.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -138,6 +145,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter)) try test(Row.fetchAll(statement, adapter: adapter)) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -163,6 +171,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -170,6 +179,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -193,6 +203,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchAll(db, sql), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -200,6 +211,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Row.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -217,6 +229,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) + try test(Row.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -225,6 +238,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -238,6 +252,7 @@ class RowFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Row.fetchOne(db, sql)) try test(Row.fetchOne(statement)) + try test(Row.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -246,6 +261,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter)) try test(Row.fetchOne(statement, adapter: adapter)) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -272,6 +288,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -279,6 +296,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -302,6 +320,7 @@ class RowFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Row.fetchOne(db, sql), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -309,6 +328,7 @@ class RowFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Row.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Row.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Row.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index a97363c0a..97121e429 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -100,6 +100,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchCursor(db, sql)) try test(Fetched.fetchCursor(statement)) + try test(Fetched.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -108,6 +109,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter)) try test(Fetched.fetchCursor(statement, adapter: adapter)) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -142,6 +144,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -149,6 +152,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -172,6 +176,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchCursor(db, sql), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -179,6 +184,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -196,6 +202,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchAll(db, sql)) try test(Fetched.fetchAll(statement)) + try test(Fetched.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -204,6 +211,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter)) try test(Fetched.fetchAll(statement, adapter: adapter)) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -229,6 +237,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -236,6 +245,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -259,6 +269,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchAll(db, sql), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -266,6 +277,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -283,6 +295,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -291,6 +304,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -303,6 +317,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -311,6 +326,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -323,6 +339,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Fetched.fetchOne(db, sql)) try test(Fetched.fetchOne(statement)) + try test(Fetched.fetchOne(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchOne(db)) } do { @@ -331,6 +348,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter)) try test(Fetched.fetchOne(statement, adapter: adapter)) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchOne(db)) } } @@ -357,6 +375,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -364,6 +383,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -387,6 +407,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Fetched.fetchOne(db, sql), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql)), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchOne(db), sql: sql) } do { @@ -394,6 +415,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Fetched.fetchOne(db, sql, adapter: adapter), sql: sql) try test(Fetched.fetchOne(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Fetched.fetchOne(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchOne(db), sql: sql) } } @@ -416,6 +438,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchCursor(db, sql)) try test(Optional.fetchCursor(statement)) + try test(Optional.fetchCursor(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchCursor(db)) } do { @@ -424,6 +447,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter)) try test(Optional.fetchCursor(statement, adapter: adapter)) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db)) } } @@ -447,6 +471,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchCursor(db, sql), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchCursor(db), sql: sql) } do { @@ -454,6 +479,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchCursor(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchCursor(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchCursor(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchCursor(db), sql: sql) } } @@ -473,6 +499,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let statement = try db.makeSelectStatement(sql) try test(Optional.fetchAll(db, sql)) try test(Optional.fetchAll(statement)) + try test(Optional.fetchAll(db, SQLRequest(sql))) try test(SQLRequest(sql).fetchAll(db)) } do { @@ -481,6 +508,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter)) try test(Optional.fetchAll(statement, adapter: adapter)) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter))) try test(SQLRequest(sql, adapter: adapter).fetchAll(db)) } } @@ -506,6 +534,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT throw()" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -513,6 +542,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } @@ -536,6 +566,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let sql = "SELECT * FROM nonExistingTable" try test(Optional.fetchAll(db, sql), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql)), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql)), sql: sql) try test(SQLRequest(sql).fetchAll(db), sql: sql) } do { @@ -543,6 +574,7 @@ class StatementColumnConvertibleFetchTests: GRDBTestCase { let adapter = SuffixRowAdapter(fromIndex: 1) try test(Optional.fetchAll(db, sql, adapter: adapter), sql: sql) try test(Optional.fetchAll(db.makeSelectStatement(sql), adapter: adapter), sql: sql) + try test(Optional.fetchAll(db, SQLRequest(sql, adapter: adapter)), sql: sql) try test(SQLRequest(sql, adapter: adapter).fetchAll(db), sql: sql) } } diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index 7e6845684..52bee069f 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -91,7 +91,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - 1") - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -108,7 +108,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - ?", arguments: [1]) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -125,7 +125,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(sql: "name, id - :n", arguments: ["n": 1]) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT name, id - 1 FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") @@ -142,7 +142,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try db.execute("INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) let request = Reader.select(Col.name, Col.id - 1) - let rows = try request.asRequest(of: Row.self).fetchAll(db) + let rows = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", (\"id\" - 1) FROM \"readers\"") XCTAssertEqual(rows.count, 2) XCTAssertEqual(rows[0][0] as String, "Arthur") diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index 54ce6be41..fefb44642 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -16,7 +16,7 @@ class TableRecordTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"t1\"") } } @@ -29,7 +29,7 @@ class TableRecordTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"t1\"") } } @@ -42,7 +42,7 @@ class TableRecordTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute("CREATE TABLE t1(a,b,c)") - _ = try Record.all().asRequest(of: Row.self).fetchAll(db) + _ = try Row.fetchAll(db, Record.all()) XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"") } } From 362c4baeca9b0a75b82cb0146753674c6eba01ec Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Sun, 15 Apr 2018 19:47:16 +0700 Subject: [PATCH 083/348] initial scanf() based date string parser --- .../Foundation/DatabaseDateComponents.swift | 8 +- .../Support/Foundation/SQLiteDateParser.swift | 90 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) create mode 100644 GRDB/Core/Support/Foundation/SQLiteDateParser.swift diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 93d7978d4..4ad284876 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -2,6 +2,8 @@ import Foundation /// DatabaseDateComponents reads and stores DateComponents in the database. public struct DatabaseDateComponents : DatabaseValueConvertible { + + public static var useScanfStrategy = true /// The available formats for reading and storing date components. public enum Format : String { @@ -130,7 +132,11 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { guard let string = String.fromDatabaseValue(dbValue) else { return nil } - + + if useScanfStrategy { + return SQLiteDateParser.components(from: string) + } + var dateComponents = DateComponents() let scanner = Scanner(string: string) scanner.charactersToBeSkipped = CharacterSet() diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift new file mode 100644 index 000000000..4e7d2c895 --- /dev/null +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -0,0 +1,90 @@ +import Foundation + +// inspired by: http://jordansmith.io/performant-date-parsing/ + +class SQLiteDateParser { + + private static var mutex: pthread_mutex_t = { + var mutex = pthread_mutex_t() + pthread_mutex_init(&mutex, nil) + return mutex + }() + + private static let year = UnsafeMutablePointer.allocate(capacity: 1) + private static let month = UnsafeMutablePointer.allocate(capacity: 1) + private static let day = UnsafeMutablePointer.allocate(capacity: 1) + private static let hour = UnsafeMutablePointer.allocate(capacity: 1) + private static let minute = UnsafeMutablePointer.allocate(capacity: 1) + private static let second = UnsafeMutablePointer.allocate(capacity: 1) + + public static func components(from dateString: String) -> DatabaseDateComponents? { + switch dateString.count { + case 23, 19, 16, 10: + return datetimeComponents(from: dateString) + case 12, 8, 5: + return timeComponents(from: dateString) + default: + return nil + } + } + + // - YYYY-MM-DD + // - YYYY-MM-DD HH:MM + // - YYYY-MM-DD HH:MM:SS + // - YYYY-MM-DD HH:MM:SS.SSS + // - YYYY-MM-DDTHH:MM + // - YYYY-MM-DDTHH:MM:SS + // - YYYY-MM-DDTHH:MM:SS.SSS + private static func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { + pthread_mutex_lock(&mutex) + + let parseCount = withVaList([year, month, day, hour, minute, second]) { pointer in + vsscanf(dateString, "%d-%d-%d%*c%d:%d:%f", pointer) + } + + var components = DateComponents() + + components.year = Int(year.pointee) + components.month = Int(month.pointee) + components.day = Int(day.pointee) + + if parseCount >= 5 { + components.hour = Int(hour.pointee) + components.minute = Int(minute.pointee) + } + + if parseCount >= 6 { + components.second = Int(second.pointee) + components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) + } + + pthread_mutex_unlock(&mutex) + + return DatabaseDateComponents(components, format: .YMD_HMSS) + } + + // - HH:MM + // - HH:MM:SS + // - HH:MM:SS.SSS + private static func timeComponents(from timeString: String) -> DatabaseDateComponents? { + pthread_mutex_lock(&mutex) + + let parseCount = withVaList([hour, minute, second]) { pointer in + vsscanf(timeString, "%d:%d:%f", pointer) + } + + var components = DateComponents() + + components.hour = Int(hour.pointee) + components.minute = Int(minute.pointee) + + if parseCount >= 3 { + components.second = Int(second.pointee) + components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) + } + + pthread_mutex_unlock(&mutex) + + return DatabaseDateComponents(components, format: .HMSS) + } +} From f5f8ab59717f33f81dae82bbeae24ec44f4593f7 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Mon, 16 Apr 2018 16:32:32 +0700 Subject: [PATCH 084/348] add SQLiteDateParser to project file --- GRDB.xcodeproj/project.pbxproj | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 093beb624..fe8efafdc 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -625,6 +625,9 @@ 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; }; 6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; 6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; }; + C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; + C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; + C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = C96C0F242084A442006B2981 /* SQLiteDateParser.swift */; }; DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; /* End PBXBuildFile section */ @@ -1028,6 +1031,7 @@ 56FF453F1D2C23BA00F21EF9 /* MutablePersistableDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableDeleteTests.swift; sourceTree = ""; }; 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = ""; }; 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = ""; }; + C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = ""; }; DC3773F319C8CBB3004FCF85 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; @@ -1135,6 +1139,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + C96C0F242084A442006B2981 /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -2195,6 +2200,7 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, @@ -2360,6 +2366,7 @@ 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, @@ -2762,6 +2769,7 @@ 5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, + C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 567517C820131B220094BF41 /* RecordBox.swift in Sources */, From 59d7909f5018ee98a7aac83a125c66a955705071 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Mon, 16 Apr 2018 17:21:00 +0700 Subject: [PATCH 085/348] return correct Format for partial date/time combinations --- .../Support/Foundation/SQLiteDateParser.swift | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 4e7d2c895..a1de51307 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -37,28 +37,29 @@ class SQLiteDateParser { // - YYYY-MM-DDTHH:MM:SS.SSS private static func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { pthread_mutex_lock(&mutex) + defer { pthread_mutex_unlock(&mutex) } let parseCount = withVaList([year, month, day, hour, minute, second]) { pointer in vsscanf(dateString, "%d-%d-%d%*c%d:%d:%f", pointer) } + guard parseCount >= 3 else { return nil } + var components = DateComponents() components.year = Int(year.pointee) components.month = Int(month.pointee) components.day = Int(day.pointee) - if parseCount >= 5 { - components.hour = Int(hour.pointee) - components.minute = Int(minute.pointee) - } + guard parseCount >= 5 else { return DatabaseDateComponents(components, format: .YMD) } - if parseCount >= 6 { - components.second = Int(second.pointee) - components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) - } + components.hour = Int(hour.pointee) + components.minute = Int(minute.pointee) - pthread_mutex_unlock(&mutex) + guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) } + + components.second = Int(second.pointee) + components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) return DatabaseDateComponents(components, format: .YMD_HMSS) } @@ -68,23 +69,24 @@ class SQLiteDateParser { // - HH:MM:SS.SSS private static func timeComponents(from timeString: String) -> DatabaseDateComponents? { pthread_mutex_lock(&mutex) + defer { pthread_mutex_unlock(&mutex) } let parseCount = withVaList([hour, minute, second]) { pointer in vsscanf(timeString, "%d:%d:%f", pointer) } + guard parseCount >= 2 else { return nil } + var components = DateComponents() components.hour = Int(hour.pointee) components.minute = Int(minute.pointee) - if parseCount >= 3 { - components.second = Int(second.pointee) - components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) - } - - pthread_mutex_unlock(&mutex) - + guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) } + + components.second = Int(second.pointee) + components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) + return DatabaseDateComponents(components, format: .HMSS) } } From b444d376f4e5648d90ec35da482aec2b196408f0 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Mon, 16 Apr 2018 17:39:41 +0700 Subject: [PATCH 086/348] differentiate between SS and SS.SSS formats --- .../Support/Foundation/SQLiteDateParser.swift | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index a1de51307..eae297b3e 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -15,7 +15,8 @@ class SQLiteDateParser { private static let day = UnsafeMutablePointer.allocate(capacity: 1) private static let hour = UnsafeMutablePointer.allocate(capacity: 1) private static let minute = UnsafeMutablePointer.allocate(capacity: 1) - private static let second = UnsafeMutablePointer.allocate(capacity: 1) + private static let second = UnsafeMutablePointer.allocate(capacity: 1) + private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 1) public static func components(from dateString: String) -> DatabaseDateComponents? { switch dateString.count { @@ -39,14 +40,13 @@ class SQLiteDateParser { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } - let parseCount = withVaList([year, month, day, hour, minute, second]) { pointer in - vsscanf(dateString, "%d-%d-%d%*c%d:%d:%f", pointer) + let parseCount = withVaList([year, month, day, hour, minute, second, nanosecond]) { pointer in + vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%d", pointer) } guard parseCount >= 3 else { return nil } var components = DateComponents() - components.year = Int(year.pointee) components.month = Int(month.pointee) components.day = Int(day.pointee) @@ -59,7 +59,10 @@ class SQLiteDateParser { guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) } components.second = Int(second.pointee) - components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) + + guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } + + components.nanosecond = Int(nanosecond.pointee) return DatabaseDateComponents(components, format: .YMD_HMSS) } @@ -71,22 +74,24 @@ class SQLiteDateParser { pthread_mutex_lock(&mutex) defer { pthread_mutex_unlock(&mutex) } - let parseCount = withVaList([hour, minute, second]) { pointer in - vsscanf(timeString, "%d:%d:%f", pointer) + let parseCount = withVaList([hour, minute, second, nanosecond]) { pointer in + vsscanf(timeString, "%d:%d:%d.%d", pointer) } guard parseCount >= 2 else { return nil } var components = DateComponents() - components.hour = Int(hour.pointee) components.minute = Int(minute.pointee) guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) } - + components.second = Int(second.pointee) - components.nanosecond = Int((second.pointee - Float(components.second!)) * 1_000_000_000) - + + guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } + + components.nanosecond = Int(nanosecond.pointee) + return DatabaseDateComponents(components, format: .HMSS) } } From 969fac5c4b798b12ba3c53a2f27c0555d3e3af6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 16 Apr 2018 14:01:54 +0200 Subject: [PATCH 087/348] Cleanup --- README.md | 88 +++++++++++++++++++++++++++---------------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 6481f8ba4..6b5543b7f 100644 --- a/README.md +++ b/README.md @@ -4852,14 +4852,14 @@ But we may want to make it more usable and robust: To address the first bullet, let's define a record that holds our player, optional team, and maximum score. Since it can decode database rows, it adopts the [FetchableRecord] protocol: ```swift -struct Item { +struct PlayerInfo { var player: Player var team: Team? var maxScore: Int } -/// Item can decode rows: -extension Item: FetchableRecord { +/// PlayerInfo can decode rows: +extension PlayerInfo: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4873,11 +4873,11 @@ extension Item: FetchableRecord { } ``` -Let's now write the method that fetches items: +Let's now write the method that fetches PlayerInfo records: ```swift -extension Item { - static func fetchAll(_ db: Database) throws -> [Item] { +extension PlayerInfo { + static func fetchAll(_ db: Database) throws -> [PlayerInfo] { ``` To acknowledge that both Player and Team records may customize their selection of the "players" and "teams" columns, we'll write our SQL in a slightly different way: @@ -4914,20 +4914,20 @@ Now is the time to build adapters (taking in account the customized selection of > :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for players, one for teams, and one for the remaining columns. -And finally, we can fetch items: +And finally, we can fetch player infos: ```swift - return try Item.fetchAll(db, sql, adapter: adapter) + return try PlayerInfo.fetchAll(db, sql, adapter: adapter) } } ``` -And when your app needs to fetch items, it now reads: +And when your app needs to fetch player infos, it now reads: ```swift -// Fetch items -let items = try dbQueue.read { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } ``` @@ -4942,19 +4942,19 @@ let items = try dbQueue.read { db in ### Splitting Rows, the Request Way -The `Item.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. +The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. -It is recommended that your read the previous paragraphs before you dive in this sample code. We start with the same Item record as above: +It is recommended that your read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above: ```swift -struct Item { +struct PlayerInfo { var player: Player var team: Team? var maxScore: Int } -/// Item can decode rows: -extension Item: FetchableRecord { +/// PlayerInfo can decode rows: +extension PlayerInfo: FetchableRecord { private enum Scopes { static let player = "player" static let team = "team" @@ -4971,9 +4971,9 @@ extension Item: FetchableRecord { Now we write a method that returns a request, and build the fetching method on top of that request: ```swift -extension Item { - /// The request for all items - static func all() -> AdaptedFetchRequest> { +extension PlayerInfo { + /// The request for all player infos + static func all() -> AdaptedFetchRequest> { let sql = """ SELECT \(Player.selectionSQL()), @@ -4984,7 +4984,7 @@ extension Item { LEFT JOIN rounds ON ... GROUP BY ... """ - return SQLRequest(sql).adapted { db in + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) @@ -4994,8 +4994,8 @@ extension Item { } } - /// Fetches all items - static func fetchAll(_ db: Database) throws -> [Item] { + /// Fetches all player infos + static func fetchAll(_ db: Database) throws -> [PlayerInfo] { return try all().fetchAll(db) } } @@ -5004,16 +5004,16 @@ extension Item { It is now time to use our request: ```swift -// Fetch items -let items = try dbQueue.read { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } -// Track items with RxRGDB: -Item.all() +// Track player infos with RxRGDB: +PlayerInfo.all() .rx.fetchAll(in: dbQueue) - .subscribe(onNext: { items: [Item] in - print("items have changed") + .subscribe(onNext: { playerInfos: [PlayerInfo] in + print("Player infos have changed") }) ``` @@ -5038,15 +5038,15 @@ struct Team: Decodable, FetchableRecord, TableRecord { var name: String var color: Color } -struct Item: Decodable, FetchableRecord { +struct PlayerInfo: Decodable, FetchableRecord { var player: Player var team: Team? var maxScore: Int } -extension Item { - /// The request for all items - static func all() -> AdaptedFetchRequest> { +extension PlayerInfo { + /// The request for all player infos + static func all() -> AdaptedFetchRequest> { let sql = """ SELECT \(Player.selectionSQL()), @@ -5057,7 +5057,7 @@ extension Item { LEFT JOIN rounds ON ... GROUP BY ... """ - return SQLRequest(sql).adapted { db in + return SQLRequest(sql).adapted { db in let adapters = try splittingRowAdapters(columnCounts: [ Player.numberOfSelectedColumns(db), Team.numberOfSelectedColumns(db)]) @@ -5067,22 +5067,22 @@ extension Item { } } - /// Fetches all items - static func fetchAll(_ db: Database) throws -> [Item] { + /// Fetches all player infos + static func fetchAll(_ db: Database) throws -> [PlayerInfo] { return try all().fetchAll(db) } } -// Fetch items -let items = try dbQueue.read { db in - try Item.fetchAll(db) +// Fetch player infos +let playerInfos = try dbQueue.read { db in + try PlayerInfo.fetchAll(db) } -// Track items with RxRGDB: -Item.all() +// Track player infos with RxRGDB: +PlayerInfo.all() .rx.fetchAll(in: dbQueue) - .subscribe(onNext: { items: [Item] in - print("items have changed") + .subscribe(onNext: { playerInfos: [PlayerInfo] in + print("Player infos have changed") }) ``` From 2a2c5a772f93e1dea6fa77405c62cd497977307b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 16 Apr 2018 14:05:04 +0200 Subject: [PATCH 088/348] Cleanup --- README.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6b5543b7f..6e45f1558 100644 --- a/README.md +++ b/README.md @@ -4898,7 +4898,20 @@ To acknowledge that both Player and Team records may customize their selection o `Player.selectionSQL()` will output `players.*`, unless Player defines a [customized selection](#columns-selected-by-a-request). -> :point_up: **Note**: you may also provide an alias: `SELECT \(Players.selectionSQL(alias: "p")) FROM players p ...` +> :point_up: **Note**: you may also use SQL table aliases: +> +> ```swift +> let sql = """ +> SELECT +> \(Player.selectionSQL(alias: "p")), +> \(Team.selectionSQL(alias: "t")), +> MAX(r.score) AS maxScore +> FROM players p +> LEFT JOIN teams t ON ... +> LEFT JOIN rounds r ON ... +> GROUP BY ... +> """ +> ``` Now is the time to build adapters (taking in account the customized selection of both players and teams). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: From a2c06c1bdb99feb6840bf7a814821f4e7411bc79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 16 Apr 2018 14:05:36 +0200 Subject: [PATCH 089/348] Cleanup --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 6e45f1558..2d188ab34 100644 --- a/README.md +++ b/README.md @@ -4901,16 +4901,16 @@ To acknowledge that both Player and Team records may customize their selection o > :point_up: **Note**: you may also use SQL table aliases: > > ```swift -> let sql = """ -> SELECT -> \(Player.selectionSQL(alias: "p")), -> \(Team.selectionSQL(alias: "t")), -> MAX(r.score) AS maxScore -> FROM players p -> LEFT JOIN teams t ON ... -> LEFT JOIN rounds r ON ... -> GROUP BY ... -> """ +> let sql = """ +> SELECT +> \(Player.selectionSQL(alias: "p")), +> \(Team.selectionSQL(alias: "t")), +> MAX(r.score) AS maxScore +> FROM players p +> LEFT JOIN teams t ON ... +> LEFT JOIN rounds r ON ... +> GROUP BY ... +> """ > ``` Now is the time to build adapters (taking in account the customized selection of both players and teams). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: From 7a1aa88edb1ad82408cdc281b9eff550b6bbabb1 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Mon, 16 Apr 2018 19:18:49 +0700 Subject: [PATCH 090/348] fractions of seconds are not the same thing as integer counts of nanoseconds --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index eae297b3e..75b164fcd 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -62,7 +62,7 @@ class SQLiteDateParser { guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } - components.nanosecond = Int(nanosecond.pointee) + components.nanosecond = nanosecondsInt(for: nanosecond.pointee) return DatabaseDateComponents(components, format: .YMD_HMSS) } @@ -90,8 +90,17 @@ class SQLiteDateParser { guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } - components.nanosecond = Int(nanosecond.pointee) + components.nanosecond = nanosecondsInt(for: nanosecond.pointee) return DatabaseDateComponents(components, format: .HMSS) } + + private static func nanosecondsInt(for secondFractional: Int32) -> Int { + guard secondFractional > 0 else { return 0 } + + let magnitude = Int32(log10(Double(secondFractional))) + let multiplier = Int32(pow(10.0, Double(8 - magnitude))) + + return Int(secondFractional * multiplier) + } } From bb59f5e6f7cc3e31477e195518ae93f6fd5214b1 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 11:05:47 +0700 Subject: [PATCH 091/348] 0.123 is not the same thing as 0.000123 --- .../Support/Foundation/SQLiteDateParser.swift | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 75b164fcd..d7cb74e01 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -16,7 +16,7 @@ class SQLiteDateParser { private static let hour = UnsafeMutablePointer.allocate(capacity: 1) private static let minute = UnsafeMutablePointer.allocate(capacity: 1) private static let second = UnsafeMutablePointer.allocate(capacity: 1) - private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 1) + private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 9) public static func components(from dateString: String) -> DatabaseDateComponents? { switch dateString.count { @@ -41,7 +41,7 @@ class SQLiteDateParser { defer { pthread_mutex_unlock(&mutex) } let parseCount = withVaList([year, month, day, hour, minute, second, nanosecond]) { pointer in - vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%d", pointer) + vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%s", pointer) } guard parseCount >= 3 else { return nil } @@ -62,7 +62,7 @@ class SQLiteDateParser { guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } - components.nanosecond = nanosecondsInt(for: nanosecond.pointee) + components.nanosecond = nanosecondsInt(for: nanosecond) return DatabaseDateComponents(components, format: .YMD_HMSS) } @@ -75,7 +75,7 @@ class SQLiteDateParser { defer { pthread_mutex_unlock(&mutex) } let parseCount = withVaList([hour, minute, second, nanosecond]) { pointer in - vsscanf(timeString, "%d:%d:%d.%d", pointer) + vsscanf(timeString, "%d:%d:%d.%s", pointer) } guard parseCount >= 2 else { return nil } @@ -90,17 +90,14 @@ class SQLiteDateParser { guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } - components.nanosecond = nanosecondsInt(for: nanosecond.pointee) + components.nanosecond = nanosecondsInt(for: nanosecond) return DatabaseDateComponents(components, format: .HMSS) } - private static func nanosecondsInt(for secondFractional: Int32) -> Int { - guard secondFractional > 0 else { return 0 } - - let magnitude = Int32(log10(Double(secondFractional))) - let multiplier = Int32(pow(10.0, Double(8 - magnitude))) - - return Int(secondFractional * multiplier) + private static func nanosecondsInt(for nanoCString: UnsafePointer) -> Int { + let nanoString = "0." + String(cString: nanoCString) + guard let doubleValue = Double(nanoString) else { return 0 } + return Int(doubleValue * 1_000_000_000) } } From dad163771ff18368e54acd9c1248caab8ee94e66 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 12:38:23 +0700 Subject: [PATCH 092/348] not all nanosecond fractions have 3 sig figs, so can't hard code the acceptable string lengths --- .../Support/Foundation/SQLiteDateParser.swift | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index d7cb74e01..e176c0881 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -19,14 +19,17 @@ class SQLiteDateParser { private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 9) public static func components(from dateString: String) -> DatabaseDateComponents? { - switch dateString.count { - case 23, 19, 16, 10: + guard dateString.count >= 5 else { return nil } + + if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { return datetimeComponents(from: dateString) - case 12, 8, 5: - return timeComponents(from: dateString) - default: - return nil } + + if dateString[dateString.index(dateString.startIndex, offsetBy: 2)] == ":" { + return timeComponents(from: dateString) + } + + return nil } // - YYYY-MM-DD From eba5df1fcc1ae9a3c9ac346bed8bda886a420103 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 12:57:59 +0700 Subject: [PATCH 093/348] fix the tests to expect less nanosecond precision loss --- Tests/GRDBTests/FoundationDateTests.swift | 4 ++-- Tests/GRDBTests/FoundationNSDateTests.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 920d15f01..6e0a29fef 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -179,7 +179,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) } } @@ -259,7 +259,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) } } } diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index ea43fb71f..0b3330c5e 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -162,7 +162,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the NSDateComponents -> NSDate conversion. Not a big deal. + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) } } @@ -242,7 +242,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the NSDateComponents -> NSDate conversion. Not a big deal. + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) } } } From 3bcc5b806425b3f94bc927e3360cdc566481c425 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 13:20:11 +0700 Subject: [PATCH 094/348] permit precision loss down to 3 sig figs --- Tests/GRDBTests/FoundationDateTests.swift | 2 +- Tests/GRDBTests/FoundationNSDateTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 6e0a29fef..43e7a9b66 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -259,7 +259,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 600_000) // permit precision loss down to 3 sig figs } } } diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index 0b3330c5e..411c307ad 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -242,7 +242,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 600_000) // permit precision loss down to 3 sig figs } } } From 33066133fc2b206f833e6fb389c75854cd99afd6 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 14:32:33 +0700 Subject: [PATCH 095/348] truncate date/time strings that include seconds precision beyond the nanosecond scale --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index e176c0881..02eaa672a 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -16,17 +16,19 @@ class SQLiteDateParser { private static let hour = UnsafeMutablePointer.allocate(capacity: 1) private static let minute = UnsafeMutablePointer.allocate(capacity: 1) private static let second = UnsafeMutablePointer.allocate(capacity: 1) - private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 9) + private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 11) public static func components(from dateString: String) -> DatabaseDateComponents? { guard dateString.count >= 5 else { return nil } if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { - return datetimeComponents(from: dateString) + // a date string with full nanosecond precision is 29 chars + return datetimeComponents(from: String(dateString.prefix(29))) } if dateString[dateString.index(dateString.startIndex, offsetBy: 2)] == ":" { - return timeComponents(from: dateString) + // a time string with full nanosecond precision is 18 chars + return timeComponents(from: String(dateString.prefix(18))) } return nil From bde72e562e18501bfe9d0f2208d11633edc545dd Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 15:14:09 +0700 Subject: [PATCH 096/348] Revert "permit precision loss down to 3 sig figs" This reverts commit 3bcc5b806425b3f94bc927e3360cdc566481c425. --- Tests/GRDBTests/FoundationDateTests.swift | 2 +- Tests/GRDBTests/FoundationNSDateTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 43e7a9b66..6e0a29fef 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -259,7 +259,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 600_000) // permit precision loss down to 3 sig figs + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) } } } diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index 411c307ad..0b3330c5e 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -242,7 +242,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 600_000) // permit precision loss down to 3 sig figs + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) } } } From 7320f880667ee762db303d0c2a0a897e536dc063 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 15:14:18 +0700 Subject: [PATCH 097/348] Revert "fix the tests to expect less nanosecond precision loss" This reverts commit eba5df1fcc1ae9a3c9ac346bed8bda886a420103. --- Tests/GRDBTests/FoundationDateTests.swift | 4 ++-- Tests/GRDBTests/FoundationNSDateTests.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Tests/GRDBTests/FoundationDateTests.swift b/Tests/GRDBTests/FoundationDateTests.swift index 6e0a29fef..920d15f01 100644 --- a/Tests/GRDBTests/FoundationDateTests.swift +++ b/Tests/GRDBTests/FoundationDateTests.swift @@ -179,7 +179,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. } } @@ -259,7 +259,7 @@ class FoundationDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date), 1) XCTAssertEqual(calendar.component(.minute, from: date), 2) XCTAssertEqual(calendar.component(.second, from: date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the DateComponents -> Date conversion. Not a big deal. } } } diff --git a/Tests/GRDBTests/FoundationNSDateTests.swift b/Tests/GRDBTests/FoundationNSDateTests.swift index 0b3330c5e..ea43fb71f 100644 --- a/Tests/GRDBTests/FoundationNSDateTests.swift +++ b/Tests/GRDBTests/FoundationNSDateTests.swift @@ -162,7 +162,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the NSDateComponents -> NSDate conversion. Not a big deal. } } @@ -242,7 +242,7 @@ class FoundationNSDateTests : GRDBTestCase { XCTAssertEqual(calendar.component(.hour, from: date as Date), 1) XCTAssertEqual(calendar.component(.minute, from: date as Date), 2) XCTAssertEqual(calendar.component(.second, from: date as Date), 3) - XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_560_000) < 10) + XCTAssertTrue(abs(calendar.component(.nanosecond, from: date as Date) - 4_000_000) < 10) // We actually get 4_000_008. Some precision is lost during the NSDateComponents -> NSDate conversion. Not a big deal. } } } From 3b546dedd8fd087b01db4cac096eca9f83fdc3b5 Mon Sep 17 00:00:00 2001 From: Matt Greenfield Date: Tue, 17 Apr 2018 15:17:09 +0700 Subject: [PATCH 098/348] truncate nanosecond precision to 3 sig figs --- .../Core/Support/Foundation/SQLiteDateParser.swift | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 02eaa672a..2e7fe2367 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -22,13 +22,19 @@ class SQLiteDateParser { guard dateString.count >= 5 else { return nil } if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { - // a date string with full nanosecond precision is 29 chars - return datetimeComponents(from: String(dateString.prefix(29))) + /*** + Note: A date string with full nanosecond precision is 29 chars. + This call is truncating the nanosecond fraction to a max of 3 sig figs (ie 23 chars). + */ + return datetimeComponents(from: String(dateString.prefix(23))) } if dateString[dateString.index(dateString.startIndex, offsetBy: 2)] == ":" { - // a time string with full nanosecond precision is 18 chars - return timeComponents(from: String(dateString.prefix(18))) + /*** + Note: A time string with full nanosecond precision is 18 chars. + This call is truncating the nanosecond fraction to a max of 3 sig figs (ie 12 chars). + */ + return timeComponents(from: String(dateString.prefix(12))) } return nil From 9a6daedd6d4dd2507fc8893e3df48c55106173a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 18 Apr 2018 07:31:11 +0200 Subject: [PATCH 099/348] Cleanup --- GRDB/Core/Row.swift | 4 ++-- GRDB/Core/RowAdapter.swift | 2 +- GRDB/Core/Statement.swift | 2 ++ TODO.md | 2 ++ 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 3024e3835..5af21fe26 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -143,8 +143,8 @@ extension Row { /// let row = try Row.fetchOne(db, "SELECT NULL, NULL")! /// row.containsNonNullValue // false public var containsNonNullValue: Bool { - for i in (0.., diff --git a/TODO.md b/TODO.md index 2dc3963ac..41b2829c6 100644 --- a/TODO.md +++ b/TODO.md @@ -22,6 +22,8 @@ GRDB 3.0 - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] HiddenColumnsAdapter - [ ] If possible: Have Record adopt Codable +- [ ] PR for Row.lookup() and breadth-first search of the scope +- [ ] PR for OffsettedAdapter Not sure From 2daba261a20cb6193e53afa699141dc0806f4c15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 08:09:46 +0200 Subject: [PATCH 100/348] GRDB3 TODO --- TODO.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/TODO.md b/TODO.md index 41b2829c6..3e38d3e81 100644 --- a/TODO.md +++ b/TODO.md @@ -24,6 +24,10 @@ GRDB 3.0 - [ ] If possible: Have Record adopt Codable - [ ] PR for Row.lookup() and breadth-first search of the scope - [ ] PR for OffsettedAdapter +- [ ] Find a common name for DatabaseQueue.inDatabase / DatabasePool.writeWithoutTransaction: + - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite + - sync + - ? Not sure From 57932235ba3e46c0744d8764fb295aa3e53a3776 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 09:07:16 +0200 Subject: [PATCH 101/348] Introduce RowScopes collection, a view of a row's scopes --- GRDB/Core/Row.swift | 131 +++++++++----------- GRDB/Core/RowAdapter.swift | 15 +-- GRDB/Record/FetchableRecord+Decodable.swift | 10 +- 3 files changed, 66 insertions(+), 90 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 5af21fe26..fade89e11 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -147,7 +147,7 @@ extension Row { return true } - for name in scopeNames where scoped(on: name)!.containsNonNullValue { + for (_, scopedRow) in scopes where scopedRow.containsNonNullValue { return true } @@ -483,7 +483,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record { - guard let scopedRow = scoped(on: scope) else { + guard let scopedRow = scopes[scope] else { // Programmer error fatalError("no such scope: \(scope)") } @@ -499,7 +499,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record? { - guard let scopedRow = scoped(on: scope), scopedRow.containsNonNullValue else { + guard let scopedRow = scopes[scope], scopedRow.containsNonNullValue else { return nil } return Record(row: scopedRow) @@ -510,35 +510,9 @@ extension Row { // MARK: - Scopes - var scopeNames: Set { - return impl.scopeNames - } - - /// Returns a scoped row, if the row was fetched with a row adapter that - /// defines this scope. - /// - /// // Two adapters - /// let fooAdapter = ColumnMapping(["value": "foo"]) - /// let barAdapter = ColumnMapping(["value": "bar"]) - /// - /// // Define scopes - /// let adapter = ScopeAdapter([ - /// "foo": fooAdapter, - /// "bar": barAdapter]) - /// - /// // Fetch - /// let sql = "SELECT 'foo' AS foo, 'bar' AS bar" - /// let row = try Row.fetchOne(db, sql, adapter: adapter)! - /// - /// // Scoped rows: - /// if let fooRow = row.scoped(on: "foo") { - /// fooRow["value"] // "foo" - /// } - /// if let barRow = row.scopeed(on: "bar") { - /// barRow["value"] // "bar" - /// } - public func scoped(on name: String) -> Row? { - return impl.scoped(on: name) + /// Returns a view of the scopes defined by row adapters + var scopes: RowScopes { + return impl.scopes } /// Returns a copy of the row, without any scopes. @@ -926,15 +900,15 @@ extension Row { } } - let lscopeNames = lhs.impl.scopeNames - let rscopeNames = rhs.impl.scopeNames + let lscopeNames = lhs.scopes.names + let rscopeNames = rhs.scopes.names guard lscopeNames == rscopeNames else { return false } for name in lscopeNames { - let lscope = lhs.scoped(on: name) - let rscope = rhs.scoped(on: name) + let lscope = lhs.scopes[name] + let rscope = rhs.scopes[name] guard lscope == rscope else { return false } @@ -983,9 +957,8 @@ extension Row { } else { str = description } - for scope in scopeNames.sorted() { - let scopedRow = scoped(on: scope)! - str += "\n" + prefix + "- " + scope + ": " + scopedRow.debugDescription(level: level + 1) + for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) { + str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1) } return str @@ -1027,6 +1000,46 @@ extension RowIndex { } } +// MARK: - RowScopes + +public struct RowScopes: Collection { + public typealias Index = Dictionary.Index + private let row: Row + private let scopes: [String: LayoutedRowAdapter] + + var names: Dictionary.Keys { + return scopes.keys + } + + init(row: Row, scopes: [String: LayoutedRowAdapter]) { + self.row = row + self.scopes = scopes + } + + public var startIndex: Index { + return scopes.startIndex + } + + public var endIndex: Index { + return scopes.endIndex + } + + public func index(after i: Index) -> Index { + return scopes.index(after: i) + } + + public subscript(position: Index) -> (name: String, row: Row) { + let (name, adapter) = scopes[position] + return (name: name, row: Row(base: row, adapter: adapter)) + } + + public subscript(_ name: String) -> Row? { + guard let adapter = scopes[name] else { + return nil + } + return Row(base: row, adapter: adapter) + } +} // MARK: - RowImpl @@ -1035,6 +1048,7 @@ protocol RowImpl { var count: Int { get } var isFetched: Bool { get } var unadaptedRow: Row { get } + var scopes: RowScopes { get } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue func fastValue(atUncheckedIndex index: Int) -> Value func fastValue(atUncheckedIndex index: Int) -> Value? @@ -1046,9 +1060,6 @@ protocol RowImpl { // leftmost column that matches *name*. func index(ofColumn name: String) -> Int? - func scoped(on name: String) -> Row? - var scopeNames: Set { get } - // row.impl is guaranteed to be self. func copy(_ row: Row) -> Row } @@ -1058,6 +1069,10 @@ extension RowImpl { return Row(impl: self) } + var scopes: RowScopes { + return RowScopes(row: Row(), scopes: [:]) + } + func hasNull(atUncheckedIndex index:Int) -> Bool { return databaseValue(atUncheckedIndex: index).isNull } @@ -1114,14 +1129,6 @@ private struct ArrayRowImpl : RowImpl { return columns.index { (column, _) in column.lowercased() == lowercaseName } } - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - func copy(_ row: Row) -> Row { return row } @@ -1166,14 +1173,6 @@ private struct StatementCopyRowImpl : RowImpl { return columnNames.index { $0.lowercased() == lowercaseName } } - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - func copy(_ row: Row) -> Row { return row } @@ -1247,14 +1246,6 @@ private struct StatementRowImpl : RowImpl { return lowercaseColumnIndexes[name.lowercased()] } - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - func copy(_ row: Row) -> Row { return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef) } @@ -1290,14 +1281,6 @@ private struct EmptyRowImpl : RowImpl { return nil } - func scoped(on name: String) -> Row? { - return nil - } - - var scopeNames: Set { - return [] - } - func copy(_ row: Row) -> Row { return row } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index dfe1b8650..f01f14d99 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -487,6 +487,10 @@ struct AdaptedRowImpl : RowImpl { return base.isFetched } + var scopes: RowScopes { + return RowScopes(row: base, scopes: adapter.scopes) + } + func hasNull(atUncheckedIndex index: Int) -> Bool { let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index) return base.impl.hasNull(atUncheckedIndex: mappedIndex) @@ -520,17 +524,6 @@ struct AdaptedRowImpl : RowImpl { return mapping.layoutIndex(ofColumn: name) } - func scoped(on name: String) -> Row? { - guard let adapter = adapter.scopes[name] else { - return nil - } - return Row(base: base, adapter: adapter) - } - - var scopeNames: Set { - return Set(adapter.scopes.keys) - } - func copy(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index 65b973c06..b91ec7acd 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -13,7 +13,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer var allKeys: [Key] { let row = decoder.row let columnNames = Set(row.columnNames) - let scopeNames = row.scopeNames + let scopeNames = Set(row.scopes.names) return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) } } @@ -25,7 +25,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool { let row = decoder.row - return row.hasColumn(key.stringValue) || (row.scoped(on: key.stringValue) != nil) + return row.hasColumn(key.stringValue) || (row.scopes[key.stringValue] != nil) } /// Decodes a null value for the given key. @@ -35,7 +35,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool { let row = decoder.row - return row[key.stringValue] == nil && (row.scoped(on: key.stringValue) == nil) + return row[key.stringValue] == nil && (row.scopes[key.stringValue] == nil) } /// Decodes a value of the given type for the given key. @@ -84,7 +84,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } // Fallback on scope - if let scopedRow = row.scoped(on: key.stringValue), scopedRow.containsNonNullValue { + if let scopedRow = row.scopes[key.stringValue], scopedRow.containsNonNullValue { return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) } @@ -115,7 +115,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } // Fallback on scope - if let scopedRow = row.scoped(on: key.stringValue) { + if let scopedRow = row.scopes[key.stringValue] { return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) } From 7e260cf53708294e3df98e4e190e84cfff5526a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 14:41:49 +0200 Subject: [PATCH 102/348] Update tests for new Row.scopes view --- GRDB/Core/Row.swift | 4 +- GRDB/Legacy/Fixits-3.0.swift | 10 + Tests/GRDBTests/JoinSupportTests.swift | 32 +-- Tests/GRDBTests/RowAdapterTests.swift | 226 ++++++++++++------ .../RowCopiedFromStatementTests.swift | 5 +- .../RowFromDictionaryLiteralTests.swift | 5 +- Tests/GRDBTests/RowFromDictionaryTests.swift | 5 +- Tests/GRDBTests/RowFromStatementTests.swift | 5 +- 8 files changed, 198 insertions(+), 94 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index fade89e11..a0db522da 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -511,7 +511,7 @@ extension Row { // MARK: - Scopes /// Returns a view of the scopes defined by row adapters - var scopes: RowScopes { + public var scopes: RowScopes { return impl.scopes } @@ -1007,7 +1007,7 @@ public struct RowScopes: Collection { private let row: Row private let scopes: [String: LayoutedRowAdapter] - var names: Dictionary.Keys { + public var names: Dictionary.Keys { return scopes.keys } diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index 6d9eb8c5d..b1730ba26 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -58,3 +58,13 @@ extension MutablePersistableRecord { @available(*, unavailable, renamed: "databaseEquals") public func databaseEqual(_ record: Self) -> Bool { preconditionFailure() } } + +extension Row { + /// :nodoc: + @available(*, unavailable, message: "Use row.scopes.names instead") + var scopeNames: Set { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, message: "Use row.scopes[name] instead") + public func scoped(on name: String) -> Row? { preconditionFailure() } +} diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index a144bb860..e9569bc28 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -95,7 +95,7 @@ private struct FlatModel: FetchableRecord { self.t2Left = row[Scopes.t2Left] self.t2Right = row[Scopes.t2Right] self.t3 = row[Scopes.t3] - self.t5count = row.scoped(on: Scopes.suffix)!["t5count"] + self.t5count = row.scopes[Scopes.suffix]!["t5count"] } static func all() -> AdaptedFetchRequest> { @@ -299,11 +299,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": 1, "name": "A3", // t5count "t5count": 5]) - XCTAssertEqual(rows[0].scoped(on: "t1")!, ["id": 1, "name": "A1"]) - XCTAssertEqual(rows[0].scoped(on: "t2Left")!, ["id": 1, "t1id": 1, "name": "left"]) - XCTAssertEqual(rows[0].scoped(on: "t2Right")!, ["id": 2, "t1id": 1, "name": "right"]) - XCTAssertEqual(rows[0].scoped(on: "t3")!, ["t1id": 1, "name": "A3"]) - XCTAssertEqual(rows[0].scoped(on: "suffix")!, ["t5count": 5]) + XCTAssertEqual(rows[0].scopes["t1"]!, ["id": 1, "name": "A1"]) + XCTAssertEqual(rows[0].scopes["t2Left"]!, ["id": 1, "t1id": 1, "name": "left"]) + XCTAssertEqual(rows[0].scopes["t2Right"]!, ["id": 2, "t1id": 1, "name": "right"]) + XCTAssertEqual(rows[0].scopes["t3"]!, ["t1id": 1, "name": "A3"]) + XCTAssertEqual(rows[0].scopes["suffix"]!, ["t5count": 5]) XCTAssertEqual(rows[1].unscoped, [ // t1.* @@ -316,11 +316,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": nil, "name": nil, // t5count "t5count": 2]) - XCTAssertEqual(rows[1].scoped(on: "t1")!, ["id": 2, "name": "A2"]) - XCTAssertEqual(rows[1].scoped(on: "t2Left")!, ["id": 3, "t1id": 2, "name": "left"]) - XCTAssertEqual(rows[1].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[1].scoped(on: "t3")!, ["t1id": nil, "name": nil]) - XCTAssertEqual(rows[1].scoped(on: "suffix")!, ["t5count": 2]) + XCTAssertEqual(rows[1].scopes["t1"]!, ["id": 2, "name": "A2"]) + XCTAssertEqual(rows[1].scopes["t2Left"]!, ["id": 3, "t1id": 2, "name": "left"]) + XCTAssertEqual(rows[1].scopes["t2Right"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scopes["t3"]!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[1].scopes["suffix"]!, ["t5count": 2]) XCTAssertEqual(rows[2].unscoped, [ // t1.* @@ -333,11 +333,11 @@ class JoinSupportTests: GRDBTestCase { "t1id": nil, "name": nil, // t5count "t5count": 0]) - XCTAssertEqual(rows[2].scoped(on: "t1")!, ["id": 3, "name": "A3"]) - XCTAssertEqual(rows[2].scoped(on: "t2Left")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "t2Right")!, ["id": nil, "t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "t3")!, ["t1id": nil, "name": nil]) - XCTAssertEqual(rows[2].scoped(on: "suffix")!, ["t5count": 0]) + XCTAssertEqual(rows[2].scopes["t1"]!, ["id": 3, "name": "A3"]) + XCTAssertEqual(rows[2].scopes["t2Left"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["t2Right"]!, ["id": nil, "t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["t3"]!, ["t1id": nil, "name": nil]) + XCTAssertEqual(rows[2].scopes["suffix"]!, ["t5count": 0]) } } diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 5d86741ef..47e48dca2 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -275,24 +275,32 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id2"] as Int, 2) XCTAssertEqual(row["val2"] as String, "foo2") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") + XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 2) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else { XCTFail() } - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") + if let scopedRow = row.scopes["sub2"] { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } - XCTAssertTrue(row.scoped(on: "SUB1") == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes["SUB1"] == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. + XCTAssertTrue(row.scopes["missing"] == nil) } } @@ -309,24 +317,32 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") + XCTAssertEqual(Set(row.scopes.names), ["sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 2) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else { XCTFail() } - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") + if let scopedRow = row.scopes["sub2"] { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } - - XCTAssertTrue(row.scoped(on: "SUB1") == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. - XCTAssertTrue(row.scoped(on: "missing") == nil) + + XCTAssertTrue(row.scopes["SUB1"] == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. + XCTAssertTrue(row.scopes["missing"] == nil) } } @@ -337,34 +353,42 @@ class AdapterRowTests : RowTestCase { let adapter1 = ColumnMapping(["id": "id1", "val": "val1"]) let adapter2 = ColumnMapping(["id": "id2", "val": "val2"]) + // - sub0 is defined in the the first scoped adapter + // - sub1 is defined in the the first scoped adapter, and then + // redefined in the second + // - sub2 is defined in the the second scoped adapter let mainAdapter = ScopeAdapter(["sub0": adapter0, "sub1": adapter2]) let adapter = mainAdapter.addingScopes(["sub1": adapter1, "sub2": adapter2]) let row = try Row.fetchOne(db, "SELECT 0 AS id0, 'foo0' AS val0, 1 AS id1, 'foo1' AS val1, 2 as id2, 'foo2' AS val2", adapter: adapter)! - // sub0 is defined in the the first scoped adapter - if let scope = row.scoped(on: "sub0") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 0) - XCTAssertEqual(scope["val"] as String, "foo0") + XCTAssertEqual(Set(row.scopes.names), ["sub0", "sub1", "sub2"]) + XCTAssertEqual(row.scopes.count, 3) + for (name, scopedRow) in row.scopes { + if name == "sub0" { + XCTAssertEqual(scopedRow, ["id": 0, "val": "foo0"]) + } else if name == "sub1" { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) + } else if name == "sub2" { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub0"] { + XCTAssertEqual(scopedRow, ["id": 0, "val": "foo0"]) } else { XCTFail() } - // sub1 is defined in the the first scoped adapter, and then - // redefined in the second - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) } else { XCTFail() } - // sub2 is defined in the the second scoped adapter - if let scope = row.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") + if let scopedRow = row.scopes["sub2"] { + XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } @@ -385,15 +409,31 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(row["id"] as Int, 0) XCTAssertEqual(row["val"] as String, "foo0") - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 1) - XCTAssertEqual(scope["val"] as String, "foo1") + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(scope.count, 2) - XCTAssertEqual(scope["id"] as Int, 2) - XCTAssertEqual(scope["val"] as String, "foo2") + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) + } else { + XCTFail() + } + } + + if let subScopedRow = scopedRow.scopes["sub2"] { + XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } @@ -402,7 +442,7 @@ class AdapterRowTests : RowTestCase { } // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) } } @@ -442,13 +482,32 @@ class AdapterRowTests : RowTestCase { "sub2": SuffixRowAdapter(fromIndex: 1)])]) let row = try Row.fetchOne(db, "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2", "a3"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue, 3.databaseValue]) + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) + } else { + XCTFail() + } + } - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2", "a3"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue, 3.databaseValue]) + if let subScopedRow = scopedRow.scopes["sub2"] { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) } else { XCTFail() } @@ -457,7 +516,7 @@ class AdapterRowTests : RowTestCase { } // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) } } @@ -534,13 +593,32 @@ class AdapterRowTests : RowTestCase { "sub2": RangeRowAdapter(1..<3)])]) let row = try Row.fetchOne(db, "SELECT 0 AS a0, 1 AS a1, 2 AS a2, 3 AS a3", adapter: adapter)! - if let scope = row.scoped(on: "sub1") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue]) + XCTAssertEqual(Set(row.scopes.names), ["sub1"]) + XCTAssertEqual(row.scopes.count, 1) + for (name, scopedRow) in row.scopes { + if name == "sub1" { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) + } else { + XCTFail() + } + } + + if let scopedRow = row.scopes["sub1"] { + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) - if let scope = scope.scoped(on: "sub2") { - XCTAssertEqual(Array(scope.columnNames), ["a1", "a2"]) - XCTAssertEqual(Array(scope.databaseValues), [1.databaseValue, 2.databaseValue]) + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) + } else { + XCTFail() + } + } + + if let subScopedRow = scopedRow.scopes["sub2"] { + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) } else { XCTFail() } @@ -549,7 +627,7 @@ class AdapterRowTests : RowTestCase { } // sub2 is only defined in sub1 - XCTAssertTrue(row.scoped(on: "sub2") == nil) + XCTAssertTrue(row.scopes["sub2"] == nil) } } @@ -569,9 +647,21 @@ class AdapterRowTests : RowTestCase { XCTAssertEqual(copiedRow["a"] as Int, 0) XCTAssertEqual(copiedRow["b"] as Int, 1) XCTAssertEqual(copiedRow["c"] as Int, 2) - if let scope = copiedRow.scoped(on: "sub") { - XCTAssertEqual(scope.count, 1) - XCTAssertEqual(scope["a"] as Int, 1) + + XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) + XCTAssertEqual(copiedRow.scopes.count, 1) + for (name, scopedRow) in copiedRow.scopes { + if name == "sub" { + XCTAssertEqual(scopedRow, ["a": 1]) + } else { + XCTFail() + } + } + + if let scopedRow = copiedRow.scopes["sub"] { + XCTAssertEqual(scopedRow, ["a": 1]) + } else { + XCTFail() } } else { XCTFail() @@ -621,9 +711,9 @@ class AdapterRowTests : RowTestCase { (row1, row3, true), (row1, row4, false), (row1, row5, false), - (row1.scoped(on: "sub"), row3.scoped(on: "sub"), true), - (row1.scoped(on: "sub"), row4.scoped(on: "sub"), true), - (row1.scoped(on: "sub"), row5.scoped(on: "sub"), false)] + (row1.scopes["sub"], row3.scopes["sub"], true), + (row1.scopes["sub"], row4.scopes["sub"], true), + (row1.scopes["sub"], row5.scopes["sub"], false)] for (lrow, rrow, equal) in tests { if equal { XCTAssertEqual(lrow, rrow) @@ -740,8 +830,8 @@ class AdapterRowTests : RowTestCase { - b: [id:1 val:"foo1"] - ba: [id:2 val:"foo2"] """) - XCTAssertEqual(row.scoped(on: "a")!.description, "[id:1 val:\"foo1\"]") - XCTAssertEqual(row.scoped(on: "a")!.debugDescription, """ + XCTAssertEqual(row.scopes["a"]!.description, "[id:1 val:\"foo1\"]") + XCTAssertEqual(row.scopes["a"]!.debugDescription, """ ▿ [id:1 val:"foo1"] unadapted: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] - a: [id0:0 val0:"foo0" id1:1 val1:"foo1" id2:2 val2:"foo2"] diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 8767a074b..02a3b7ee8 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -245,11 +245,12 @@ class RowCopiedFromStatementTests: RowTestCase { } } - func testVariants() throws { + func testScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let row = try Row.fetchOne(db, "SELECT 'foo' AS nAmE, 1 AS foo")! - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index 36f72601c..4772a53a9 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -206,9 +206,10 @@ class RowFromDictionaryLiteralTests : RowTestCase { XCTAssertTrue(row.hasColumn("FOO")) } - func testSubRows() { + func testScopes() { let row: Row = ["a": 0, "b": 1, "c": 2] - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index bfdc2bb76..5324e5102 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -196,9 +196,10 @@ class RowFromDictionaryTests : RowTestCase { XCTAssertTrue(row.hasColumn("FOO")) } - func testSubRows() { + func testScopes() { let row = Row(["a": 0, "b": 1, "c": 2]) - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 556151428..a9ff27299 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -308,14 +308,15 @@ class RowFromStatementTests : RowTestCase { } } - func testVariants() throws { + func testScopes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in var rowFetched = false let rows = try Row.fetchCursor(db, "SELECT 'foo' AS nAmE, 1 AS foo") while let row = try rows.next() { rowFetched = true - XCTAssertTrue(row.scoped(on: "missing") == nil) + XCTAssertTrue(row.scopes.isEmpty) + XCTAssertTrue(row.scopes["missing"] == nil) } XCTAssertTrue(rowFetched) } From 33d65e85d81c25b1fda845562fa40f505b1e32e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 14:44:05 +0200 Subject: [PATCH 103/348] Update documentation for scoped rows --- README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 2d188ab34..f0e3dc642 100644 --- a/README.md +++ b/README.md @@ -1813,13 +1813,13 @@ let adapter = ScopeAdapter([ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! ``` -ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access with the `Row.scoped(on:)` method. This method returns an optional Row, which is nil if the scope is missing. +ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access with `Row.scopes[]`. This subscript returns an optional Row, which is nil if the scope is missing. ```swift -row // [a:0 b:1 c:2 d:3] -row.scoped(on: "left") // [a:0 b:1] -row.scoped(on: "right") // [c:2 d:3] -row.scoped(on: "missing") // nil +row // [a:0 b:1 c:2 d:3] +row.scopes["left"] // [a:0 b:1] +row.scopes["right"] // [c:2 d:3] +row.scopes["missing"] // nil ``` Scopes can be nested: @@ -1835,13 +1835,13 @@ let adapter = ScopeAdapter([ ]) let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! -let leftRow = row.scoped(on: "left")! -leftRow.scoped(on: "left") // [a:0] -leftRow.scoped(on: "right") // [b:1] +let leftRow = row.scopes["left"]! +leftRow.scopes["left"] // [a:0] +leftRow.scopes["right"] // [b:1] -let rightRow = row.scoped(on: "right")! -rightRow.scoped(on: "left") // [c:2] -rightRow.scoped(on: "right") // [d:3] +let rightRow = row.scopes["right"]! +rightRow.scopes["left"] // [c:2] +rightRow.scopes["right"] // [d:3] ``` Any adapter can be extended with scopes: @@ -1853,7 +1853,7 @@ let adapter = ScopeAdapter(base: baseAdapter, scopes: [ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! row // [a:0 b:1] -row.scoped(on: "remainder") // [c:2 d:3] +row.scopes["remainder"] // [c:2 d:3] ``` From 9cb1bac2fca6204e608fdc30b37c8c3716af369b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 14:46:23 +0200 Subject: [PATCH 104/348] Update documentation for scoped rows --- GRDB/Core/RowAdapter.swift | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index f01f14d99..8865382c3 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -14,10 +14,10 @@ import Foundation /// "c": adapters[2], /// "d": adapters[3]]) /// let row = try Row.fetchOne(db, sql, adapter: adapter) -/// row.scoped(on: "a") // [1] -/// row.scoped(on: "b") // [2, 3, 4] -/// row.scoped(on: "c") // [5, 6] -/// row.scoped(on: "d") // [7, 8] +/// row.scopes["a"] // [1] +/// row.scopes["b"] // [2, 3, 4] +/// row.scopes["c"] // [5, 6] +/// row.scopes["d"] // [7, 8] public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] { guard !columnCounts.isEmpty else { // Identity adapter @@ -366,10 +366,10 @@ public struct RangeRowAdapter : RowAdapter { /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// // Scoped rows: -/// if let fooRow = row.scoped(on: "foo") { +/// if let fooRow = row.scopes["foo"] { /// fooRow["value"] // "foo" /// } -/// if let barRow = row.scopeed(on: "bar") { +/// if let barRow = row.scopes["bar"] { /// barRow["value"] // "bar" /// } public struct ScopeAdapter : RowAdapter { @@ -386,8 +386,8 @@ public struct ScopeAdapter : RowAdapter { /// /// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)]) /// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)! - /// row // [1, 2, 3] - /// row.scoped(on: "suffix") // [2, 3] + /// row // [1, 2, 3] + /// row.scopes["suffix"] // [2, 3] /// /// - parameter scopes: A dictionary that maps scope names to /// row adapters. @@ -403,8 +403,8 @@ public struct ScopeAdapter : RowAdapter { /// let baseAdapter = RangeRowAdapter(0..<1) /// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)]) /// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)! - /// row // [1] - /// row.scoped(on: "initial") // [2, 3] + /// row // [1] + /// row.scopes["initial"] // [2, 3] /// /// If the base adapter already defines scopes, the given scopes replace /// eventual existing scopes with the same name. From 4e659c550ebf1a2f8eb897fb93d22d0cf043a08a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 19:18:02 +0200 Subject: [PATCH 105/348] Rename RowScopes to Row.Scopes. Harmonize row derivation. --- GRDB/Core/Row.swift | 178 ++++++++++++++++++++++++------------- GRDB/Core/RowAdapter.swift | 19 ++-- 2 files changed, 128 insertions(+), 69 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index a0db522da..6b9271e92 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -61,7 +61,7 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl /// the iteration of a query: make sure to make a copy of it whenever you /// want to keep a specific one: `row.copy()`. public func copy() -> Row { - return impl.copy(self) + return impl.copiedRow(self) } // MARK: - Not Public @@ -510,8 +510,29 @@ extension Row { // MARK: - Scopes - /// Returns a view of the scopes defined by row adapters - public var scopes: RowScopes { + /// Returns a view of the scopes defined by row adapters. + /// + /// For example: + /// + /// // Define scopes + /// let adapter = ScopeAdapter([ + /// "prefix": RangeRowAdapter(0..<1), + /// "suffix": RangeRowAdapter(1..<2)]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopes.count // 2 + /// row.scopes.names // ["prefix", "suffix"] + /// + /// if let prefixRow = row.scopes["prefix"] { + /// prefixRow // [foo:1] + /// } + /// if let suffixRow = row.scopes["suffix"] { + /// suffixRow // [bar:2] + /// } + public var scopes: Scopes { return impl.scopes } @@ -526,7 +547,7 @@ extension Row { /// // Success: /// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"]) public var unscoped: Row { - return Row(impl: ArrayRowImpl(columns: map { ($0, $1) })) + return impl.unscopedRow(self) } /// Return the raw row fetched from the database. @@ -534,7 +555,7 @@ extension Row { /// This property can turn out useful when you debug the consumption of /// adapted rows, such as rows fetched from joined requests. public var unadapted: Row { - return impl.unadaptedRow + return impl.unadaptedRow(self) } } @@ -1000,44 +1021,81 @@ extension RowIndex { } } -// MARK: - RowScopes +// MARK: - Row.Scopes -public struct RowScopes: Collection { - public typealias Index = Dictionary.Index - private let row: Row - private let scopes: [String: LayoutedRowAdapter] - - public var names: Dictionary.Keys { - return scopes.keys - } - - init(row: Row, scopes: [String: LayoutedRowAdapter]) { - self.row = row - self.scopes = scopes - } - - public var startIndex: Index { - return scopes.startIndex - } - - public var endIndex: Index { - return scopes.endIndex - } - - public func index(after i: Index) -> Index { - return scopes.index(after: i) - } - - public subscript(position: Index) -> (name: String, row: Row) { - let (name, adapter) = scopes[position] - return (name: name, row: Row(base: row, adapter: adapter)) - } - - public subscript(_ name: String) -> Row? { - guard let adapter = scopes[name] else { - return nil +extension Row { + /// A view of the scopes defined by row adapters. It is a collection of + /// tuples made of a scope name and a scoped row, which behaves like a + /// dictionary. + /// + /// For example: + /// + /// // Define scopes + /// let adapter = ScopeAdapter([ + /// "prefix": RangeRowAdapter(0..<1), + /// "suffix": RangeRowAdapter(1..<2)]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopes.count // 2 + /// row.scopes.names // ["prefix", "suffix"] + /// + /// if let prefixRow = row.scopes["prefix"] { + /// prefixRow // [foo:1] + /// } + /// if let suffixRow = row.scopes["suffix"] { + /// suffixRow // [bar:2] + /// } + public struct Scopes: Collection { + public typealias Index = Dictionary.Index + private let row: Row + private let scopes: [String: LayoutedRowAdapter] + + /// All defined scopes + public var names: Dictionary.Keys { + return scopes.keys + } + + init() { + self.init(row: Row(), scopes: [:]) + } + + init(row: Row, scopes: [String: LayoutedRowAdapter]) { + self.row = row + self.scopes = scopes + } + + /// :nodoc: + public var startIndex: Index { + return scopes.startIndex + } + + /// :nodoc: + public var endIndex: Index { + return scopes.endIndex + } + + /// :nodoc: + public func index(after i: Index) -> Index { + return scopes.index(after: i) + } + + /// :nodoc: + public subscript(position: Index) -> (name: String, row: Row) { + let (name, adapter) = scopes[position] + return (name: name, row: Row(base: row, adapter: adapter)) + } + + /// Returns the row associated with the given scope, or nil if the + /// scope is not defined. + public subscript(_ name: String) -> Row? { + guard let adapter = scopes[name] else { + return nil + } + return Row(base: row, adapter: adapter) } - return Row(base: row, adapter: adapter) } } @@ -1047,8 +1105,7 @@ public struct RowScopes: Collection { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } - var unadaptedRow: Row { get } - var scopes: RowScopes { get } + var scopes: Row.Scopes { get } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue func fastValue(atUncheckedIndex index: Int) -> Value func fastValue(atUncheckedIndex index: Int) -> Value? @@ -1061,16 +1118,26 @@ protocol RowImpl { func index(ofColumn name: String) -> Int? // row.impl is guaranteed to be self. - func copy(_ row: Row) -> Row + func unscopedRow(_ row: Row) -> Row + func unadaptedRow(_ row: Row) -> Row + func copiedRow(_ row: Row) -> Row } extension RowImpl { - var unadaptedRow: Row { - return Row(impl: self) + func copiedRow(_ row: Row) -> Row { + return row } - var scopes: RowScopes { - return RowScopes(row: Row(), scopes: [:]) + func unscopedRow(_ row: Row) -> Row { + return row + } + + func unadaptedRow(_ row: Row) -> Row { + return row + } + + var scopes: Row.Scopes { + return Row.Scopes() } func hasNull(atUncheckedIndex index:Int) -> Bool { @@ -1128,10 +1195,6 @@ private struct ArrayRowImpl : RowImpl { let lowercaseName = name.lowercased() return columns.index { (column, _) in column.lowercased() == lowercaseName } } - - func copy(_ row: Row) -> Row { - return row - } } @@ -1172,10 +1235,6 @@ private struct StatementCopyRowImpl : RowImpl { let lowercaseName = name.lowercased() return columnNames.index { $0.lowercased() == lowercaseName } } - - func copy(_ row: Row) -> Row { - return row - } } @@ -1246,12 +1305,11 @@ private struct StatementRowImpl : RowImpl { return lowercaseColumnIndexes[name.lowercased()] } - func copy(_ row: Row) -> Row { + func copiedRow(_ row: Row) -> Row { return Row(copiedFromSQLiteStatement: sqliteStatement, statementRef: statementRef) } } - /// See Row.init() private struct EmptyRowImpl : RowImpl { var count: Int { @@ -1280,8 +1338,4 @@ private struct EmptyRowImpl : RowImpl { func index(ofColumn name: String) -> Int? { return nil } - - func copy(_ row: Row) -> Row { - return row - } } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 8865382c3..e548c49cd 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -475,10 +475,6 @@ struct AdaptedRowImpl : RowImpl { self.mapping = adapter.mapping } - var unadaptedRow: Row { - return base.unadapted - } - var count: Int { return mapping.layoutColumns.count } @@ -487,8 +483,8 @@ struct AdaptedRowImpl : RowImpl { return base.isFetched } - var scopes: RowScopes { - return RowScopes(row: base, scopes: adapter.scopes) + var scopes: Row.Scopes { + return Row.Scopes(row: base, scopes: adapter.scopes) } func hasNull(atUncheckedIndex index: Int) -> Bool { @@ -524,7 +520,16 @@ struct AdaptedRowImpl : RowImpl { return mapping.layoutIndex(ofColumn: name) } - func copy(_ row: Row) -> Row { + func copiedRow(_ row: Row) -> Row { return Row(base: base.copy(), adapter: adapter) } + + func unscopedRow(_ row: Row) -> Row { + assert(adapter.mapping.scopes.isEmpty) + return Row(base: base, adapter: adapter.mapping) + } + + func unadaptedRow(_ row: Row) -> Row { + return base.unadapted + } } From 098c11baf2f226b279be26a360f6e2c80cbd6466 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 19:50:43 +0200 Subject: [PATCH 106/348] Row.Scopes.lookup(_:) performs a breadth-first lookup of a scope name --- GRDB/Core/Row.swift | 26 +++ Tests/GRDBTests/RowAdapterTests.swift | 167 ++++++++---------- .../RowCopiedFromStatementTests.swift | 1 + .../RowFromDictionaryLiteralTests.swift | 1 + Tests/GRDBTests/RowFromDictionaryTests.swift | 1 + Tests/GRDBTests/RowFromStatementTests.swift | 1 + 6 files changed, 104 insertions(+), 93 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 6b9271e92..10266067f 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1096,6 +1096,32 @@ extension Row { } return Row(base: row, adapter: adapter) } + + /// Returns the row associated with the given scope, by performing a + /// breadth-first search in this row's scopes and the scopes of its + /// scoped rows, recursively. + public func lookup(_ name: String) -> Row? { + struct Node { + let row: Row + let name: String + } + + var fifo: [Node] = scopes.map { (name, adapter) in + Node(row: Row(base: row, adapter: adapter), name: name) + } + + while !fifo.isEmpty { + let node = fifo.removeFirst() + if node.name == name { + return node.row + } + for (name, scopedRow) in node.row.scopes { + fifo.append(Node(row: scopedRow, name: name)) + } + } + + return nil + } } } diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 47e48dca2..6d2c14407 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -287,20 +287,19 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - if let scopedRow = row.scopes["sub2"] { - XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub2"]!, ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) + + XCTAssertTrue(row.scopes["SUB1"] == nil) + XCTAssertTrue(row.scopes.lookup("SUB1") == nil) - XCTAssertTrue(row.scopes["SUB1"] == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } } @@ -329,20 +328,19 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - if let scopedRow = row.scopes["sub2"] { - XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) - XCTAssertTrue(row.scopes["SUB1"] == nil) // case-insensitivity is not really required here, and case-sensitivity helps the implementation because it allows the use of a dictionary. So let's enforce this with a public test. + XCTAssertTrue(row.scopes["SUB1"] == nil) + XCTAssertTrue(row.scopes.lookup("SUB1") == nil) + XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } } @@ -375,23 +373,17 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub0"] { - XCTAssertEqual(scopedRow, ["id": 0, "val": "foo0"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub0"], ["id": 0, "val": "foo0"]) + XCTAssertTrue(row.scopes["sub0"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub0"), row.scopes["sub0"]) + + XCTAssertEqual(row.scopes["sub1"], ["id": 1, "val": "foo1"]) + XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow, ["id": 1, "val": "foo1"]) - } else { - XCTFail() - } - - if let scopedRow = row.scopes["sub2"] { - XCTAssertEqual(scopedRow, ["id": 2, "val": "foo2"]) - } else { - XCTFail() - } + XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) + XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) } } @@ -419,30 +411,27 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) - - XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) - XCTAssertEqual(scopedRow.scopes.count, 1) - for (name, subScopedRow) in scopedRow.scopes { - if name == "sub2" { - XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) - } else { - XCTFail() - } - } - - if let subScopedRow = scopedRow.scopes["sub2"] { + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["id": 1, "val": "foo1"]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { XCTAssertEqual(subScopedRow, ["id": 2, "val": "foo2"]) } else { XCTFail() } - } else { - XCTFail() } + XCTAssertEqual(scopedRow.scopes["sub2"]!, ["id": 2, "val": "foo2"]) + XCTAssertTrue(scopedRow.scopes["sub2"]!.scopes.isEmpty) + // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) } } @@ -492,31 +481,28 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) - - XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) - XCTAssertEqual(scopedRow.scopes.count, 1) - for (name, subScopedRow) in scopedRow.scopes { - if name == "sub2" { - XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) - } else { - XCTFail() - } - } - - if let subScopedRow = scopedRow.scopes["sub2"] { + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2, "a3": 3]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) - XCTAssertTrue(subScopedRow.scopes.isEmpty) } else { XCTFail() } - } else { - XCTFail() } + let subScopedRow = scopedRow.scopes["sub2"]! + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2, "a3": 3]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) + // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) } } @@ -603,31 +589,28 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = row.scopes["sub1"] { - XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) - - XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) - XCTAssertEqual(scopedRow.scopes.count, 1) - for (name, subScopedRow) in scopedRow.scopes { - if name == "sub2" { - XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) - } else { - XCTFail() - } - } - - if let subScopedRow = scopedRow.scopes["sub2"] { + let scopedRow = row.scopes["sub1"]! + XCTAssertEqual(scopedRow.unscoped, ["a1": 1, "a2": 2]) + + XCTAssertEqual(Set(scopedRow.scopes.names), ["sub2"]) + XCTAssertEqual(scopedRow.scopes.count, 1) + for (name, subScopedRow) in scopedRow.scopes { + if name == "sub2" { XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) - XCTAssertTrue(subScopedRow.scopes.isEmpty) } else { XCTFail() } - } else { - XCTFail() } + let subScopedRow = scopedRow.scopes["sub2"]! + XCTAssertEqual(subScopedRow, ["a1": 1, "a2": 2]) + XCTAssertTrue(subScopedRow.scopes.isEmpty) + // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) + + XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) } } @@ -658,11 +641,9 @@ class AdapterRowTests : RowTestCase { } } - if let scopedRow = copiedRow.scopes["sub"] { - XCTAssertEqual(scopedRow, ["a": 1]) - } else { - XCTFail() - } + XCTAssertEqual(copiedRow.scopes["sub"]!, ["a": 1]) + XCTAssertTrue(copiedRow.scopes["sub"]!.scopes.isEmpty) + XCTAssertEqual(copiedRow.scopes.lookup("sub")!, ["a": 1]) } else { XCTFail() } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 02a3b7ee8..50b622fe7 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -251,6 +251,7 @@ class RowCopiedFromStatementTests: RowTestCase { let row = try Row.fetchOne(db, "SELECT 'foo' AS nAmE, 1 AS foo")! XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index 4772a53a9..81db84906 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -210,6 +210,7 @@ class RowFromDictionaryLiteralTests : RowTestCase { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 5324e5102..9e54359d5 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -200,6 +200,7 @@ class RowFromDictionaryTests : RowTestCase { let row = Row(["a": 0, "b": 1, "c": 2]) XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index a9ff27299..141bae2aa 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -317,6 +317,7 @@ class RowFromStatementTests : RowTestCase { rowFetched = true XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) + XCTAssertTrue(row.scopes.lookup("missing") == nil) } XCTAssertTrue(rowFetched) } From 0362ae76eaf72616c1195f4343c8f86d75aad04f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 20:29:11 +0200 Subject: [PATCH 107/348] Rename Row.Scopes to Row.ScopesView. Move breadth-first lookup to a new view, row.scopesTree, of type Row.ScopesTreeView --- GRDB/Core/Row.swift | 126 +++++++++++++----- GRDB/Core/RowAdapter.swift | 4 +- Tests/GRDBTests/RowAdapterTests.swift | 47 ++++--- .../RowCopiedFromStatementTests.swift | 2 +- .../RowFromDictionaryLiteralTests.swift | 2 +- Tests/GRDBTests/RowFromDictionaryTests.swift | 2 +- Tests/GRDBTests/RowFromStatementTests.swift | 2 +- 7 files changed, 124 insertions(+), 61 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 10266067f..e41008814 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -510,32 +510,53 @@ extension Row { // MARK: - Scopes - /// Returns a view of the scopes defined by row adapters. + /// Returns a view on the scopes defined by row adapters. /// /// For example: /// - /// // Define scopes + /// // Define a tree of scopes /// let adapter = ScopeAdapter([ - /// "prefix": RangeRowAdapter(0..<1), - /// "suffix": RangeRowAdapter(1..<2)]) + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) /// /// // Fetch /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// row.scopes.count // 2 - /// row.scopes.names // ["prefix", "suffix"] + /// row.scopes.names // ["foo", "bar"] /// - /// if let prefixRow = row.scopes["prefix"] { - /// prefixRow // [foo:1] - /// } - /// if let suffixRow = row.scopes["suffix"] { - /// suffixRow // [bar:2] - /// } - public var scopes: Scopes { + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // nil + public var scopes: ScopesView { return impl.scopes } + /// Returns a view on the scopes tree defined by row adapters. + /// + /// For example: + /// + /// // Define a tree of scopes + /// let adapter = ScopeAdapter([ + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopesTree.names // ["foo", "bar", "baz"] + /// + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // [baz:3] + public var scopesTree: ScopesTreeView { + return ScopesTreeView(scopes: scopes) + } + /// Returns a copy of the row, without any scopes. /// /// This property can turn out useful when you want to test the content of @@ -1021,7 +1042,7 @@ extension RowIndex { } } -// MARK: - Row.Scopes +// MARK: - Row.ScopesView extension Row { /// A view of the scopes defined by row adapters. It is a collection of @@ -1030,30 +1051,28 @@ extension Row { /// /// For example: /// - /// // Define scopes + /// // Define a tree of scopes /// let adapter = ScopeAdapter([ - /// "prefix": RangeRowAdapter(0..<1), - /// "suffix": RangeRowAdapter(1..<2)]) + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) /// /// // Fetch /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// /// row.scopes.count // 2 - /// row.scopes.names // ["prefix", "suffix"] + /// row.scopes.names // ["foo", "bar"] /// - /// if let prefixRow = row.scopes["prefix"] { - /// prefixRow // [foo:1] - /// } - /// if let suffixRow = row.scopes["suffix"] { - /// suffixRow // [bar:2] - /// } - public struct Scopes: Collection { + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // nil + public struct ScopesView: Collection { public typealias Index = Dictionary.Index private let row: Row private let scopes: [String: LayoutedRowAdapter] - /// All defined scopes + /// The scopes defined on this row. public var names: Dictionary.Keys { return scopes.keys } @@ -1096,28 +1115,61 @@ extension Row { } return Row(base: row, adapter: adapter) } + } +} + +// MARK: - Row.ScopesTreeView + +extension Row { + + /// A view on the scopes tree defined by row adapters. + /// + /// For example: + /// + /// // Define a tree of scopes + /// let adapter = ScopeAdapter([ + /// "foo": RangeRowAdapter(0..<1), + /// "bar": RangeRowAdapter(1..<2).addingScopes([ + /// "baz" : RangeRowAdapter(2..<3)])]) + /// + /// // Fetch + /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" + /// let row = try Row.fetchOne(db, sql, adapter: adapter)! + /// + /// row.scopesTree.names // ["foo", "bar", "baz"] + /// + /// row.scopesTree["foo"] // [foo:1] + /// row.scopesTree["bar"] // [bar:2] + /// row.scopesTree["baz"] // [baz:3] + public struct ScopesTreeView { + let scopes: ScopesView + /// The scopes defined on this row, recursively. + public var names: Set { + var names = Set() + for (name, row) in scopes { + names.insert(name) + names.formUnion(row.scopesTree.names) + } + return names + } + /// Returns the row associated with the given scope, by performing a /// breadth-first search in this row's scopes and the scopes of its /// scoped rows, recursively. - public func lookup(_ name: String) -> Row? { + public subscript(_ name: String) -> Row? { struct Node { - let row: Row let name: String + let row: Row } - var fifo: [Node] = scopes.map { (name, adapter) in - Node(row: Row(base: row, adapter: adapter), name: name) - } - + var fifo = Array(scopes) while !fifo.isEmpty { let node = fifo.removeFirst() if node.name == name { return node.row } - for (name, scopedRow) in node.row.scopes { - fifo.append(Node(row: scopedRow, name: name)) - } + fifo.append(contentsOf: node.row.scopes) } return nil @@ -1131,7 +1183,7 @@ extension Row { protocol RowImpl { var count: Int { get } var isFetched: Bool { get } - var scopes: Row.Scopes { get } + var scopes: Row.ScopesView { get } func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue func fastValue(atUncheckedIndex index: Int) -> Value func fastValue(atUncheckedIndex index: Int) -> Value? @@ -1162,8 +1214,8 @@ extension RowImpl { return row } - var scopes: Row.Scopes { - return Row.Scopes() + var scopes: Row.ScopesView { + return Row.ScopesView() } func hasNull(atUncheckedIndex index:Int) -> Bool { diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index e548c49cd..3434651ac 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -483,8 +483,8 @@ struct AdaptedRowImpl : RowImpl { return base.isFetched } - var scopes: Row.Scopes { - return Row.Scopes(row: base, scopes: adapter.scopes) + var scopes: Row.ScopesView { + return Row.ScopesView(row: base, scopes: adapter.scopes) } func hasNull(atUncheckedIndex index: Int) -> Bool { diff --git a/Tests/GRDBTests/RowAdapterTests.swift b/Tests/GRDBTests/RowAdapterTests.swift index 6d2c14407..c5c79e8a7 100644 --- a/Tests/GRDBTests/RowAdapterTests.swift +++ b/Tests/GRDBTests/RowAdapterTests.swift @@ -287,19 +287,21 @@ class AdapterRowTests : RowTestCase { } } + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"]!, ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) XCTAssertTrue(row.scopes["SUB1"] == nil) - XCTAssertTrue(row.scopes.lookup("SUB1") == nil) + XCTAssertTrue(row.scopesTree["SUB1"] == nil) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } @@ -328,19 +330,21 @@ class AdapterRowTests : RowTestCase { } } + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopes["sub1"]!, ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) XCTAssertTrue(row.scopes["SUB1"] == nil) - XCTAssertTrue(row.scopes.lookup("SUB1") == nil) + XCTAssertTrue(row.scopesTree["SUB1"] == nil) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } @@ -373,17 +377,19 @@ class AdapterRowTests : RowTestCase { } } + XCTAssertEqual(row.scopesTree.names, ["sub0", "sub1", "sub2"]) + XCTAssertEqual(row.scopes["sub0"], ["id": 0, "val": "foo0"]) XCTAssertTrue(row.scopes["sub0"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub0"), row.scopes["sub0"]) + XCTAssertEqual(row.scopesTree["sub0"], row.scopes["sub0"]) XCTAssertEqual(row.scopes["sub1"], ["id": 1, "val": "foo1"]) XCTAssertTrue(row.scopes["sub1"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) XCTAssertEqual(row.scopes["sub2"], ["id": 2, "val": "foo2"]) XCTAssertTrue(row.scopes["sub2"]!.scopes.isEmpty) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub2"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub2"]) } } @@ -430,8 +436,9 @@ class AdapterRowTests : RowTestCase { // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -501,8 +508,9 @@ class AdapterRowTests : RowTestCase { // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -609,8 +617,9 @@ class AdapterRowTests : RowTestCase { // sub2 is only defined in sub1 XCTAssertTrue(row.scopes["sub2"] == nil) - XCTAssertEqual(row.scopes.lookup("sub1"), row.scopes["sub1"]) - XCTAssertEqual(row.scopes.lookup("sub2"), row.scopes["sub1"]!.scopes["sub2"]) + XCTAssertEqual(row.scopesTree.names, ["sub1", "sub2"]) + XCTAssertEqual(row.scopesTree["sub1"], row.scopes["sub1"]) + XCTAssertEqual(row.scopesTree["sub2"], row.scopes["sub1"]!.scopes["sub2"]) } } @@ -641,9 +650,11 @@ class AdapterRowTests : RowTestCase { } } + XCTAssertEqual(Set(copiedRow.scopes.names), ["sub"]) XCTAssertEqual(copiedRow.scopes["sub"]!, ["a": 1]) XCTAssertTrue(copiedRow.scopes["sub"]!.scopes.isEmpty) - XCTAssertEqual(copiedRow.scopes.lookup("sub")!, ["a": 1]) + XCTAssertEqual(copiedRow.scopesTree.names, ["sub"]) + XCTAssertEqual(copiedRow.scopesTree["sub"]!, ["a": 1]) } else { XCTFail() } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 50b622fe7..10bd99e55 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -251,7 +251,7 @@ class RowCopiedFromStatementTests: RowTestCase { let row = try Row.fetchOne(db, "SELECT 'foo' AS nAmE, 1 AS foo")! XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index 81db84906..33d959670 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -210,7 +210,7 @@ class RowFromDictionaryLiteralTests : RowTestCase { let row: Row = ["a": 0, "b": 1, "c": 2] XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 9e54359d5..2fe4e414b 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -200,7 +200,7 @@ class RowFromDictionaryTests : RowTestCase { let row = Row(["a": 0, "b": 1, "c": 2]) XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } func testCopy() { diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index 141bae2aa..79a281c94 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -317,7 +317,7 @@ class RowFromStatementTests : RowTestCase { rowFetched = true XCTAssertTrue(row.scopes.isEmpty) XCTAssertTrue(row.scopes["missing"] == nil) - XCTAssertTrue(row.scopes.lookup("missing") == nil) + XCTAssertTrue(row.scopesTree["missing"] == nil) } XCTAssertTrue(rowFetched) } From 4b3854d05da792af061ee3752688f3b88313fd1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 20:46:58 +0200 Subject: [PATCH 108/348] Finally, the meat: perform breadth-first search in `let record = row[key]`, and in FetchableRecord & Decodable --- GRDB/Core/Row.swift | 4 +- GRDB/Record/FetchableRecord+Decodable.swift | 45 +++++--- Tests/GRDBTests/JoinSupportTests.swift | 107 +++++++++++++++++++- 3 files changed, 140 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index e41008814..44ffeaa9e 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -483,7 +483,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record { - guard let scopedRow = scopes[scope] else { + guard let scopedRow = scopesTree[scope] else { // Programmer error fatalError("no such scope: \(scope)") } @@ -499,7 +499,7 @@ extension Row { /// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support /// for more information. public subscript(_ scope: String) -> Record? { - guard let scopedRow = scopes[scope], scopedRow.containsNonNullValue else { + guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else { return nil } return Record(row: scopedRow) diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index b91ec7acd..e6135260c 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -13,7 +13,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer var allKeys: [Key] { let row = decoder.row let columnNames = Set(row.columnNames) - let scopeNames = Set(row.scopes.names) + let scopeNames = Set(row.scopesTree.names) return columnNames.union(scopeNames).compactMap { Key(stringValue: $0) } } @@ -25,7 +25,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - returns: Whether the `Decoder` has an entry for the given key. func contains(_ key: Key) -> Bool { let row = decoder.row - return row.hasColumn(key.stringValue) || (row.scopes[key.stringValue] != nil) + return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil) } /// Decodes a null value for the given key. @@ -35,7 +35,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer /// - throws: `DecodingError.keyNotFound` if `self` does not have an entry for the given key. func decodeNil(forKey key: Key) throws -> Bool { let row = decoder.row - return row[key.stringValue] == nil && (row.scopes[key.stringValue] == nil) + return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil) } /// Decodes a value of the given type for the given key. @@ -69,7 +69,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer func decodeIfPresent(_ type: T.Type, forKey key: Key) throws -> T? where T : Decodable { let row = decoder.row - // Try column + // Column? if row.hasColumn(key.stringValue) { let dbValue: DatabaseValue = row[key.stringValue] if let type = T.self as? DatabaseValueConvertible.Type { @@ -83,9 +83,15 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } } - // Fallback on scope - if let scopedRow = row.scopes[key.stringValue], scopedRow.containsNonNullValue { - return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + // Scope? + if let scopedRow = row.scopesTree[key.stringValue], scopedRow.containsNonNullValue { + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return (type.init(row: scopedRow) as! T) + } else { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } } return nil @@ -102,7 +108,7 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer func decode(_ type: T.Type, forKey key: Key) throws -> T where T : Decodable { let row = decoder.row - // Try column + // Column? if row.hasColumn(key.stringValue) { let dbValue: DatabaseValue = row[key.stringValue] if let type = T.self as? DatabaseValueConvertible.Type { @@ -114,13 +120,25 @@ private struct RowKeyedDecodingContainer: KeyedDecodingContainer } } - // Fallback on scope - if let scopedRow = row.scopes[key.stringValue] { - return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + // Scope? + if let scopedRow = row.scopesTree[key.stringValue] { + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return type.init(row: scopedRow) as! T + } else { + return try T(from: RowDecoder(row: scopedRow, codingPath: codingPath + [key])) + } } - let path = (codingPath.map { $0.stringValue } + [key.stringValue]).joined(separator: ".") - fatalError("No such column or scope: \(path)") + // Base row + if let type = T.self as? FetchableRecord.Type { + // Prefer FetchableRecord decoding over Decodable. + // This allows custom row decoding + return type.init(row: row) as! T + } else { + return try T(from: RowDecoder(row: row, codingPath: codingPath + [key])) + } } /// Returns the data stored for the given key as represented in a container keyed by the given key type. @@ -255,3 +273,4 @@ extension FetchableRecord where Self: Decodable { try! self.init(from: RowDecoder(row: row, codingPath: [])) } } + diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index e9569bc28..f436c4965 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -110,7 +110,24 @@ private struct FlatModel: FetchableRecord { Scopes.t2Left: adapters[1], Scopes.t2Right: adapters[2], Scopes.t3: adapters[3], - Scopes.suffix: adapters[4]]) // The only test for adapters[4] + Scopes.suffix: adapters[4]]) + } + } + + static func hierarchicalAll() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + Scopes.t1: adapters[0], + "t2": ScopeAdapter(base: EmptyRowAdapter(), scopes: [ + Scopes.t2Left: adapters[1], + Scopes.t2Right: adapters[2]]), + Scopes.t3: adapters[3], + Scopes.suffix: adapters[4]]) } } } @@ -136,6 +153,22 @@ private struct CodableFlatModel: FetchableRecord, Codable { CodingKeys.t3.stringValue: adapters[3]]) } } + + static func hierarchicalAll() -> AdaptedFetchRequest> { + return SQLRequest(testedSQL).adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + T1.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T2.numberOfSelectedColumns(db), + T3.numberOfSelectedColumns(db)]) + return ScopeAdapter([ + CodingKeys.t1.stringValue: adapters[0], + "t2": ScopeAdapter(base: EmptyRowAdapter(), scopes: [ + CodingKeys.t2Left.stringValue: adapters[1], + CodingKeys.t2Right.stringValue: adapters[2]]), + CodingKeys.t3.stringValue: adapters[3]]) + } + } } private struct CodableNestedModel: FetchableRecord, Codable { @@ -377,6 +410,42 @@ class JoinSupportTests: GRDBTestCase { } } + func testFlatModelFromHierarchicalRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let models = try FlatModel.hierarchicalAll().fetchAll(db) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + func testCodableFlatModel() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -413,6 +482,42 @@ class JoinSupportTests: GRDBTestCase { } } + func testCodableFlatModelFromHierarchicalRequest() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let models = try CodableFlatModel.hierarchicalAll().fetchAll(db) + XCTAssertEqual(models.count, 3) + + XCTAssertEqual(models[0].t1.id, 1) + XCTAssertEqual(models[0].t1.name, "A1") + XCTAssertEqual(models[0].t2Left!.id, 1) + XCTAssertEqual(models[0].t2Left!.t1id, 1) + XCTAssertEqual(models[0].t2Left!.name, "left") + XCTAssertEqual(models[0].t2Right!.id, 2) + XCTAssertEqual(models[0].t2Right!.t1id, 1) + XCTAssertEqual(models[0].t2Right!.name, "right") + XCTAssertEqual(models[0].t3!.t1id, 1) + XCTAssertEqual(models[0].t3!.name, "A3") + XCTAssertEqual(models[0].t5count, 5) + + XCTAssertEqual(models[1].t1.id, 2) + XCTAssertEqual(models[1].t1.name, "A2") + XCTAssertEqual(models[1].t2Left!.id, 3) + XCTAssertEqual(models[1].t2Left!.t1id, 2) + XCTAssertEqual(models[1].t2Left!.name, "left") + XCTAssertNil(models[1].t2Right) + XCTAssertNil(models[1].t3) + XCTAssertEqual(models[1].t5count, 2) + + XCTAssertEqual(models[2].t1.id, 3) + XCTAssertEqual(models[2].t1.name, "A3") + XCTAssertNil(models[2].t2Left) + XCTAssertNil(models[2].t2Right) + XCTAssertNil(models[2].t3) + XCTAssertEqual(models[2].t5count, 0) + } + } + func testCodableNestedModel() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From b550e2bfd560e97a106b63d5aaf2920d1c36c943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 21:45:40 +0200 Subject: [PATCH 109/348] Cleanup --- GRDB/Core/Row.swift | 34 ++++++++++++++-------------------- 1 file changed, 14 insertions(+), 20 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 44ffeaa9e..7cdcdf1bf 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -514,7 +514,7 @@ extension Row { /// /// For example: /// - /// // Define a tree of scopes + /// // Define a tree of nested scopes /// let adapter = ScopeAdapter([ /// "foo": RangeRowAdapter(0..<1), /// "bar": RangeRowAdapter(1..<2).addingScopes([ @@ -524,12 +524,12 @@ extension Row { /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// - /// row.scopes.count // 2 - /// row.scopes.names // ["foo", "bar"] + /// row.scopes.count // 2 + /// row.scopes.names // ["foo", "bar"] /// - /// row.scopesTree["foo"] // [foo:1] - /// row.scopesTree["bar"] // [bar:2] - /// row.scopesTree["baz"] // nil + /// row.scopes["foo"] // [foo:1] + /// row.scopes["bar"] // [bar:2] + /// row.scopes["baz"] // nil public var scopes: ScopesView { return impl.scopes } @@ -538,7 +538,7 @@ extension Row { /// /// For example: /// - /// // Define a tree of scopes + /// // Define a tree of nested scopes /// let adapter = ScopeAdapter([ /// "foo": RangeRowAdapter(0..<1), /// "bar": RangeRowAdapter(1..<2).addingScopes([ @@ -1051,7 +1051,7 @@ extension Row { /// /// For example: /// - /// // Define a tree of scopes + /// // Define a tree of nested scopes /// let adapter = ScopeAdapter([ /// "foo": RangeRowAdapter(0..<1), /// "bar": RangeRowAdapter(1..<2).addingScopes([ @@ -1061,12 +1061,12 @@ extension Row { /// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz" /// let row = try Row.fetchOne(db, sql, adapter: adapter)! /// - /// row.scopes.count // 2 - /// row.scopes.names // ["foo", "bar"] + /// row.scopes.count // 2 + /// row.scopes.names // ["foo", "bar"] /// - /// row.scopesTree["foo"] // [foo:1] - /// row.scopesTree["bar"] // [bar:2] - /// row.scopesTree["baz"] // nil + /// row.scopes["foo"] // [foo:1] + /// row.scopes["bar"] // [bar:2] + /// row.scopes["baz"] // nil public struct ScopesView: Collection { public typealias Index = Dictionary.Index private let row: Row @@ -1126,7 +1126,7 @@ extension Row { /// /// For example: /// - /// // Define a tree of scopes + /// // Define a tree of nested scopes /// let adapter = ScopeAdapter([ /// "foo": RangeRowAdapter(0..<1), /// "bar": RangeRowAdapter(1..<2).addingScopes([ @@ -1158,11 +1158,6 @@ extension Row { /// breadth-first search in this row's scopes and the scopes of its /// scoped rows, recursively. public subscript(_ name: String) -> Row? { - struct Node { - let name: String - let row: Row - } - var fifo = Array(scopes) while !fifo.isEmpty { let node = fifo.removeFirst() @@ -1171,7 +1166,6 @@ extension Row { } fifo.append(contentsOf: node.row.scopes) } - return nil } } From e45642b6c143bbe557e89b86a21f484e7ff72c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 19 Apr 2018 21:48:12 +0200 Subject: [PATCH 110/348] Cleanup --- GRDB/Core/Row.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 7cdcdf1bf..28ae77920 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1160,11 +1160,11 @@ extension Row { public subscript(_ name: String) -> Row? { var fifo = Array(scopes) while !fifo.isEmpty { - let node = fifo.removeFirst() - if node.name == name { - return node.row + let scope = fifo.removeFirst() + if scope.name == name { + return scope.row } - fifo.append(contentsOf: node.row.scopes) + fifo.append(contentsOf: scope.row.scopes) } return nil } From efa0e3850f750a060c8a81234d274344447f7669 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 06:16:10 +0200 Subject: [PATCH 111/348] GRDB3 TODO --- TODO.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/TODO.md b/TODO.md index 3e38d3e81..ee8354e8c 100644 --- a/TODO.md +++ b/TODO.md @@ -21,8 +21,6 @@ GRDB 3.0 - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] HiddenColumnsAdapter -- [ ] If possible: Have Record adopt Codable -- [ ] PR for Row.lookup() and breadth-first search of the scope - [ ] PR for OffsettedAdapter - [ ] Find a common name for DatabaseQueue.inDatabase / DatabasePool.writeWithoutTransaction: - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite From 6d9bce3a25da5a39c17410df666773497d159d84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:08:17 +0200 Subject: [PATCH 112/348] Add SQLiteDateParser.swift to GRDBCustom and GRDBCipher ... so that all GRDB flavors can use the new technique. GRDB has three distinct projects since #282. --- GRDBCipher.xcodeproj/project.pbxproj | 6 ++++++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 56d9918cb..0593c452d 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -284,6 +284,8 @@ 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; + 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */; }; 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */; }; 567156171CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 5671561D1CB16729007DC145 /* DatabaseValueConversionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */; }; @@ -919,6 +921,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 5671566C1CB16729007DC145 /* GRDBCipherOSXEncryptedTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCipherOSXEncryptedTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; @@ -1168,6 +1171,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + 567071F6208A00D4006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -2069,6 +2073,7 @@ 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, + 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, 5680520C2013209300E87861 /* RecordBox.swift in Sources */, @@ -2464,6 +2469,7 @@ 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, + 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* Persistable.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, 5680520D2013209900E87861 /* RecordBox.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 314f5d50d..f0a987832 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -111,6 +111,8 @@ 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; + 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; 5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 56741EAB1E66A8B3003E422D /* RequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* RequestTests.swift */; }; @@ -618,6 +620,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -855,6 +858,7 @@ 5605F1521C672E4000235C62 /* NSString.swift */, 5657AB0E1D10899D006283EF /* URL.swift */, 56A8C22F1D1914540096E9D4 /* UUID.swift */, + 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */, ); path = Foundation; sourceTree = ""; @@ -1770,6 +1774,7 @@ 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, + 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableMapping.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 5680520E201320A200E87861 /* RecordBox.swift in Sources */, @@ -2017,6 +2022,7 @@ 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, + 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableMapping.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 568052092013207000E87861 /* RecordBox.swift in Sources */, From 7aabfeaeac102d39efb8728bb5db1cb5705d83b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:09:22 +0200 Subject: [PATCH 113/348] SQLiteDateParser: get rid of the mutex --- .../Core/Support/Foundation/SQLiteDateParser.swift | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 2e7fe2367..98fad7b60 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -3,13 +3,7 @@ import Foundation // inspired by: http://jordansmith.io/performant-date-parsing/ class SQLiteDateParser { - - private static var mutex: pthread_mutex_t = { - var mutex = pthread_mutex_t() - pthread_mutex_init(&mutex, nil) - return mutex - }() - + private static let year = UnsafeMutablePointer.allocate(capacity: 1) private static let month = UnsafeMutablePointer.allocate(capacity: 1) private static let day = UnsafeMutablePointer.allocate(capacity: 1) @@ -48,9 +42,6 @@ class SQLiteDateParser { // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS private static func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { - pthread_mutex_lock(&mutex) - defer { pthread_mutex_unlock(&mutex) } - let parseCount = withVaList([year, month, day, hour, minute, second, nanosecond]) { pointer in vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%s", pointer) } @@ -82,9 +73,6 @@ class SQLiteDateParser { // - HH:MM:SS // - HH:MM:SS.SSS private static func timeComponents(from timeString: String) -> DatabaseDateComponents? { - pthread_mutex_lock(&mutex) - defer { pthread_mutex_unlock(&mutex) } - let parseCount = withVaList([hour, minute, second, nanosecond]) { pointer in vsscanf(timeString, "%d:%d:%d.%s", pointer) } From 27194c802d767daead0410e1c65552490e3e995f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:30:26 +0200 Subject: [PATCH 114/348] SQLiteDateParser: use withUnsafeMutablePointer instead of allocations OK, not really: the nanosecond components remains in the heap. But we may find a way to put 11 chars on the stack. --- .../Support/Foundation/SQLiteDateParser.swift | 81 +++++++++++++------ 1 file changed, 56 insertions(+), 25 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 98fad7b60..4721dbca9 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -4,13 +4,15 @@ import Foundation class SQLiteDateParser { - private static let year = UnsafeMutablePointer.allocate(capacity: 1) - private static let month = UnsafeMutablePointer.allocate(capacity: 1) - private static let day = UnsafeMutablePointer.allocate(capacity: 1) - private static let hour = UnsafeMutablePointer.allocate(capacity: 1) - private static let minute = UnsafeMutablePointer.allocate(capacity: 1) - private static let second = UnsafeMutablePointer.allocate(capacity: 1) - private static let nanosecond = UnsafeMutablePointer.allocate(capacity: 11) + private struct ParserComponents { + var year: Int32 = 0 + var month: Int32 = 0 + var day: Int32 = 0 + var hour: Int32 = 0 + var minute: Int32 = 0 + var second: Int32 = 0 + var nanosecond = ContiguousArray.init(repeating: 0, count: 11) + } public static func components(from dateString: String) -> DatabaseDateComponents? { guard dateString.count >= 5 else { return nil } @@ -42,29 +44,47 @@ class SQLiteDateParser { // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS private static func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { - let parseCount = withVaList([year, month, day, hour, minute, second, nanosecond]) { pointer in - vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%s", pointer) + var parserComponents = ParserComponents() + + // TODO: Get rid of this pyramid when SE-0210 has shipped + let parseCount = withUnsafeMutablePointer(to: &parserComponents.year) { yearP in + withUnsafeMutablePointer(to: &parserComponents.month) { monthP in + withUnsafeMutablePointer(to: &parserComponents.day) { dayP in + withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in + withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in + withUnsafeMutablePointer(to: &parserComponents.second) { secondP in + parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + // TODO: what if vsscanf parses a string longer than nanosecond length? + withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in + vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%s", pointer) + } + } + } + } + } + } + } } guard parseCount >= 3 else { return nil } var components = DateComponents() - components.year = Int(year.pointee) - components.month = Int(month.pointee) - components.day = Int(day.pointee) + components.year = Int(parserComponents.year) + components.month = Int(parserComponents.month) + components.day = Int(parserComponents.day) guard parseCount >= 5 else { return DatabaseDateComponents(components, format: .YMD) } - components.hour = Int(hour.pointee) - components.minute = Int(minute.pointee) + components.hour = Int(parserComponents.hour) + components.minute = Int(parserComponents.minute) guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) } - components.second = Int(second.pointee) + components.second = Int(parserComponents.second) guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } - components.nanosecond = nanosecondsInt(for: nanosecond) + components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) return DatabaseDateComponents(components, format: .YMD_HMSS) } @@ -73,29 +93,40 @@ class SQLiteDateParser { // - HH:MM:SS // - HH:MM:SS.SSS private static func timeComponents(from timeString: String) -> DatabaseDateComponents? { - let parseCount = withVaList([hour, minute, second, nanosecond]) { pointer in - vsscanf(timeString, "%d:%d:%d.%s", pointer) + var parserComponents = ParserComponents() + // TODO: Get rid of this pyramid when SE-0210 has shipped + let parseCount = withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in + withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in + withUnsafeMutablePointer(to: &parserComponents.second) { secondP in + parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in + // TODO: what if vsscanf parses a string longer than nanosecond length? + withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in + vsscanf(timeString, "%d:%d:%d.%s", pointer) + } + } + } + } } - + guard parseCount >= 2 else { return nil } var components = DateComponents() - components.hour = Int(hour.pointee) - components.minute = Int(minute.pointee) + components.hour = Int(parserComponents.hour) + components.minute = Int(parserComponents.minute) guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) } - components.second = Int(second.pointee) + components.second = Int(parserComponents.second) guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } - components.nanosecond = nanosecondsInt(for: nanosecond) + components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) return DatabaseDateComponents(components, format: .HMSS) } - private static func nanosecondsInt(for nanoCString: UnsafePointer) -> Int { - let nanoString = "0." + String(cString: nanoCString) + private static func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { + let nanoString = "0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) } guard let doubleValue = Double(nanoString) else { return 0 } return Int(doubleValue * 1_000_000_000) } From e9a668ca561eb87025c5b57c1ee0db3c59d0c8c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:31:35 +0200 Subject: [PATCH 115/348] SQLiteDateParser: no more static methods --- GRDB/Core/Support/Foundation/DatabaseDateComponents.swift | 2 +- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 4ad284876..ab877a257 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -134,7 +134,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { } if useScanfStrategy { - return SQLiteDateParser.components(from: string) + return SQLiteDateParser().components(from: string) } var dateComponents = DateComponents() diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 4721dbca9..e015786dc 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -14,7 +14,7 @@ class SQLiteDateParser { var nanosecond = ContiguousArray.init(repeating: 0, count: 11) } - public static func components(from dateString: String) -> DatabaseDateComponents? { + public func components(from dateString: String) -> DatabaseDateComponents? { guard dateString.count >= 5 else { return nil } if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { @@ -43,7 +43,7 @@ class SQLiteDateParser { // - YYYY-MM-DDTHH:MM // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS - private static func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { + private func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { var parserComponents = ParserComponents() // TODO: Get rid of this pyramid when SE-0210 has shipped @@ -92,7 +92,7 @@ class SQLiteDateParser { // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS - private static func timeComponents(from timeString: String) -> DatabaseDateComponents? { + private func timeComponents(from timeString: String) -> DatabaseDateComponents? { var parserComponents = ParserComponents() // TODO: Get rid of this pyramid when SE-0210 has shipped let parseCount = withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in @@ -125,7 +125,7 @@ class SQLiteDateParser { return DatabaseDateComponents(components, format: .HMSS) } - private static func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { + private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { let nanoString = "0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) } guard let doubleValue = Double(nanoString) else { return 0 } return Int(doubleValue * 1_000_000_000) From d1a0e8d906521b786f627a621b340735462da28b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:31:57 +0200 Subject: [PATCH 116/348] SQLiteDateParser.components(from:) is not public --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index e015786dc..7ec4a10e6 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -14,7 +14,7 @@ class SQLiteDateParser { var nanosecond = ContiguousArray.init(repeating: 0, count: 11) } - public func components(from dateString: String) -> DatabaseDateComponents? { + func components(from dateString: String) -> DatabaseDateComponents? { guard dateString.count >= 5 else { return nil } if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { From 0640f90fc1e2abf68a1d8a1c7d0f6de30493ec38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:32:50 +0200 Subject: [PATCH 117/348] (whitespace) --- .../Support/Foundation/SQLiteDateParser.swift | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 7ec4a10e6..eba61b907 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -13,10 +13,10 @@ class SQLiteDateParser { var second: Int32 = 0 var nanosecond = ContiguousArray.init(repeating: 0, count: 11) } - + func components(from dateString: String) -> DatabaseDateComponents? { guard dateString.count >= 5 else { return nil } - + if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { /*** Note: A date string with full nanosecond precision is 29 chars. @@ -24,7 +24,7 @@ class SQLiteDateParser { */ return datetimeComponents(from: String(dateString.prefix(23))) } - + if dateString[dateString.index(dateString.startIndex, offsetBy: 2)] == ":" { /*** Note: A time string with full nanosecond precision is 18 chars. @@ -32,10 +32,10 @@ class SQLiteDateParser { */ return timeComponents(from: String(dateString.prefix(12))) } - + return nil } - + // - YYYY-MM-DD // - YYYY-MM-DD HH:MM // - YYYY-MM-DD HH:MM:SS @@ -65,30 +65,30 @@ class SQLiteDateParser { } } } - + guard parseCount >= 3 else { return nil } - + var components = DateComponents() components.year = Int(parserComponents.year) components.month = Int(parserComponents.month) components.day = Int(parserComponents.day) - + guard parseCount >= 5 else { return DatabaseDateComponents(components, format: .YMD) } - + components.hour = Int(parserComponents.hour) components.minute = Int(parserComponents.minute) - + guard parseCount >= 6 else { return DatabaseDateComponents(components, format: .YMD_HM) } - + components.second = Int(parserComponents.second) - + guard parseCount >= 7 else { return DatabaseDateComponents(components, format: .YMD_HMS) } - + components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) - + return DatabaseDateComponents(components, format: .YMD_HMSS) } - + // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS @@ -109,22 +109,22 @@ class SQLiteDateParser { } guard parseCount >= 2 else { return nil } - + var components = DateComponents() components.hour = Int(parserComponents.hour) components.minute = Int(parserComponents.minute) - + guard parseCount >= 3 else { return DatabaseDateComponents(components, format: .HM) } - + components.second = Int(parserComponents.second) - + guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } - + components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) - + return DatabaseDateComponents(components, format: .HMSS) } - + private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { let nanoString = "0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) } guard let doubleValue = Double(nanoString) else { return 0 } From 8915672ce5dea7cacc196b6eee37b6d05f4a4acb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 13:51:20 +0200 Subject: [PATCH 118/348] SQLiteDateParser: parse C strings Since the goal of this PR is efficiency, we'll soon parse Date and DatabaseDateComponents right from raw SQLite buffers. --- .../Support/Foundation/SQLiteDateParser.swift | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index eba61b907..d434ba2da 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -11,26 +11,24 @@ class SQLiteDateParser { var hour: Int32 = 0 var minute: Int32 = 0 var second: Int32 = 0 - var nanosecond = ContiguousArray.init(repeating: 0, count: 11) + var nanosecond = ContiguousArray.init(repeating: 0, count: 10) // 9 digits, and trailing \0 } func components(from dateString: String) -> DatabaseDateComponents? { - guard dateString.count >= 5 else { return nil } + return dateString.withCString { cString in + components(cString: cString, length: strlen(cString)) + } + } + + func components(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { + guard length >= 5 else { return nil } - if dateString[dateString.index(dateString.startIndex, offsetBy: 4)] == "-" { - /*** - Note: A date string with full nanosecond precision is 29 chars. - This call is truncating the nanosecond fraction to a max of 3 sig figs (ie 23 chars). - */ - return datetimeComponents(from: String(dateString.prefix(23))) + if cString.advanced(by: 4).pointee == 45 /* '-' */ { + return datetimeComponents(cString: cString, length: length) } - if dateString[dateString.index(dateString.startIndex, offsetBy: 2)] == ":" { - /*** - Note: A time string with full nanosecond precision is 18 chars. - This call is truncating the nanosecond fraction to a max of 3 sig figs (ie 12 chars). - */ - return timeComponents(from: String(dateString.prefix(12))) + if cString.advanced(by: 2).pointee == 58 /* ':' */ { + return timeComponents(cString: cString, length: length) } return nil @@ -43,7 +41,7 @@ class SQLiteDateParser { // - YYYY-MM-DDTHH:MM // - YYYY-MM-DDTHH:MM:SS // - YYYY-MM-DDTHH:MM:SS.SSS - private func datetimeComponents(from dateString: String) -> DatabaseDateComponents? { + private func datetimeComponents(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { var parserComponents = ParserComponents() // TODO: Get rid of this pyramid when SE-0210 has shipped @@ -54,9 +52,8 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in - // TODO: what if vsscanf parses a string longer than nanosecond length? withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(dateString, "%d-%d-%d%*c%d:%d:%d.%s", pointer) + vsscanf(cString, "%d-%d-%d%*c%d:%d:%d.%10s", pointer) } } } @@ -92,16 +89,16 @@ class SQLiteDateParser { // - HH:MM // - HH:MM:SS // - HH:MM:SS.SSS - private func timeComponents(from timeString: String) -> DatabaseDateComponents? { + private func timeComponents(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { var parserComponents = ParserComponents() + // TODO: Get rid of this pyramid when SE-0210 has shipped let parseCount = withUnsafeMutablePointer(to: &parserComponents.hour) { hourP in withUnsafeMutablePointer(to: &parserComponents.minute) { minuteP in withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in - // TODO: what if vsscanf parses a string longer than nanosecond length? withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(timeString, "%d:%d:%d.%s", pointer) + vsscanf(cString, "%d:%d:%d.%10s", pointer) } } } @@ -126,7 +123,8 @@ class SQLiteDateParser { } private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { - let nanoString = "0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) } + // truncate the nanosecond fraction + let nanoString = ("0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }).prefix(5) guard let doubleValue = Double(nanoString) else { return 0 } return Int(doubleValue * 1_000_000_000) } From 936b31f1f08fb6cb3a454e472106cb1f2334c09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 14:04:12 +0200 Subject: [PATCH 119/348] DatabaseDateComponents adopts StatementColumnConvertible We'll need benchmarks to evaluate the gain, here --- .../Support/Foundation/DatabaseDateComponents.swift | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index ab877a257..0afbdaa54 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,7 +1,7 @@ import Foundation /// DatabaseDateComponents reads and stores DateComponents in the database. -public struct DatabaseDateComponents : DatabaseValueConvertible { +public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { public static var useScanfStrategy = true @@ -70,6 +70,17 @@ public struct DatabaseDateComponents : DatabaseValueConvertible { self.dateComponents = dateComponents } + // MARK: - StatementColumnConvertible adoption + + public init(sqliteStatement: SQLiteStatement, index: Int32) { + let cString = UnsafePointer(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) + let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen + guard let components = SQLiteDateParser().components(cString: cString, length: length) else { + fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents") + } + self.dateComponents = components.dateComponents + self.format = components.format + } // MARK: - DatabaseValueConvertible adoption From c70689fe546b0e47c5739927af3b4cccf81b4795 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 18:34:19 +0200 Subject: [PATCH 120/348] Check useScanfStrategy in DatabaseDateComponents.init(sqliteStatement:index:) ...so that we can eventually compare gains --- .../Support/Foundation/DatabaseDateComponents.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 0afbdaa54..29d7ff6e7 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -73,6 +73,16 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn // MARK: - StatementColumnConvertible adoption public init(sqliteStatement: SQLiteStatement, index: Int32) { + guard DatabaseDateComponents.useScanfStrategy else { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + guard let components = DatabaseDateComponents.fromDatabaseValue(dbValue) else { + fatalError("could not convert database value \(dbValue) to DatabaseDateComponents") + } + self.dateComponents = components.dateComponents + self.format = components.format + return + } + let cString = UnsafePointer(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen guard let components = SQLiteDateParser().components(cString: cString, length: length) else { From 11a4a6acbdcb9eec11774c03e5da7e74f1068beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 18:41:58 +0200 Subject: [PATCH 121/348] Documentation --- GRDB/Core/Support/Foundation/DatabaseDateComponents.swift | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 29d7ff6e7..5ae1e9575 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -72,6 +72,11 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn // MARK: - StatementColumnConvertible adoption + /// Returns a value initialized from a raw SQLite statement pointer. + /// + /// - parameters: + /// - sqliteStatement: A pointer to an SQLite statement. + /// - index: The column index. public init(sqliteStatement: SQLiteStatement, index: Int32) { guard DatabaseDateComponents.useScanfStrategy else { let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) From 266040747ecd51f611055b4505b69c3bc3849f62 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 18:42:12 +0200 Subject: [PATCH 122/348] Date adopts StatementColumnConvertible --- GRDB/Core/Support/Foundation/Date.swift | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index f19b0d935..51ee8eb77 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -108,6 +108,31 @@ extension Date : DatabaseValueConvertible { } } +extension Date: StatementColumnConvertible { + + /// Returns a value initialized from a raw SQLite statement pointer. + /// + /// - parameters: + /// - sqliteStatement: A pointer to an SQLite statement. + /// - index: The column index. + public init(sqliteStatement: SQLiteStatement, index: Int32) { + switch sqlite3_column_type(sqliteStatement, index) { + case SQLITE_INTEGER, SQLITE_FLOAT: + self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, Int32(index))) + case SQLITE_TEXT: + let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index) + guard let date = Date(databaseDateComponents: databaseDateComponents) else { + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + fatalError("could not convert database value \(dbValue) to Date") + } + self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) + default: + let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) + fatalError("could not convert database value \(dbValue) to Date") + } + } +} + /// The DatabaseDate date formatter for stored dates. private let storageDateFormatter: DateFormatter = { let formatter = DateFormatter() From f12495b24add08dce72161f1a7b9d7de1c6f4691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:06:02 +0200 Subject: [PATCH 123/348] New DateParsingTests in GRDBOSXPerformanceTests --- GRDB.xcodeproj/project.pbxproj | 4 +++ .../GRDBOSXPerformanceTests.xcscheme | 2 ++ Tests/Performance/DateParsingTests.swift | 35 +++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 Tests/Performance/DateParsingTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index fe8efafdc..9f31314c6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -259,6 +259,7 @@ 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; + 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071FA208A509C006AD95A /* DateParsingTests.swift */; }; 567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; }; 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; }; @@ -843,6 +844,7 @@ 566B91221FA4CF810012D5B0 /* Database+Schema.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Schema.swift"; sourceTree = ""; }; 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; + 567071FA208A509C006AD95A /* DateParsingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DateParsingTests.swift; sourceTree = ""; }; 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = ""; }; 567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = ""; }; 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = ""; }; @@ -1574,6 +1576,7 @@ 56DE7B361C42BBBB00861EB8 /* PerformanceCoreDataTests.sqlite */, 56DE7B2D1C42B23B00861EB8 /* PerformanceModel.xcdatamodeld */, 563363F81C960711000BE133 /* PerformanceRealmTests.realm */, + 567071FA208A509C006AD95A /* DateParsingTests.swift */, 56DE7B271C41302500861EB8 /* FetchNamedValuesTests.swift */, 56DE7B291C4130AF00861EB8 /* FetchPositionalValuesTests.swift */, 56DE7B2B1C41311900861EB8 /* FetchRecordClassTests.swift */, @@ -2136,6 +2139,7 @@ files = ( 56D3BE711F4EB1A00034C6D2 /* FetchRecordStructTests.swift in Sources */, 560C98231C0E23BB00BF8471 /* InsertRecordClassTests.swift in Sources */, + 56707201208A509C006AD95A /* DateParsingTests.swift in Sources */, 56DE7B2C1C41311900861EB8 /* FetchRecordClassTests.swift in Sources */, 56DE7B281C41302500861EB8 /* FetchNamedValuesTests.swift in Sources */, 56D507831F6D7B2E00AE1C5B /* InsertRecordStructTests.swift in Sources */, diff --git a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme index 2f1ecb6f3..4394516c3 100644 --- a/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme +++ b/GRDB.xcodeproj/xcshareddata/xcschemes/GRDBOSXPerformanceTests.xcscheme @@ -10,6 +10,7 @@ buildConfiguration = "Release" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + language = "" shouldUseLaunchSchemeArgsEnv = "YES"> Date: Fri, 20 Apr 2018 19:14:32 +0200 Subject: [PATCH 124/348] Cleanup --- Tests/Performance/DateParsingTests.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/Performance/DateParsingTests.swift b/Tests/Performance/DateParsingTests.swift index 05c5c917a..35d74cf09 100644 --- a/Tests/Performance/DateParsingTests.swift +++ b/Tests/Performance/DateParsingTests.swift @@ -17,7 +17,7 @@ class DateParsingTests: XCTestCase { func testParseDateComponents() { measure { - _ = try! DatabaseQueue().inDatabase { db in + try! DatabaseQueue().inDatabase { db in let cursor = try DatabaseDateComponents.fetchCursor(db, request) while try cursor.next() != nil { } } @@ -26,7 +26,7 @@ class DateParsingTests: XCTestCase { func testParseDate() { measure { - _ = try! DatabaseQueue().inDatabase { db in + try! DatabaseQueue().inDatabase { db in let cursor = try Date.fetchCursor(db, request) while try cursor.next() != nil { } } From 282255b841cb291168fd4c43845d4fe0022e3b74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:14:58 +0200 Subject: [PATCH 125/348] No need for useScanfStrategy any longer --- .../Foundation/DatabaseDateComponents.swift | 170 +----------------- 1 file changed, 1 insertion(+), 169 deletions(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 5ae1e9575..700dcae0d 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -3,8 +3,6 @@ import Foundation /// DatabaseDateComponents reads and stores DateComponents in the database. public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { - public static var useScanfStrategy = true - /// The available formats for reading and storing date components. public enum Format : String { @@ -78,16 +76,6 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. public init(sqliteStatement: SQLiteStatement, index: Int32) { - guard DatabaseDateComponents.useScanfStrategy else { - let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index) - guard let components = DatabaseDateComponents.fromDatabaseValue(dbValue) else { - fatalError("could not convert database value \(dbValue) to DatabaseDateComponents") - } - self.dateComponents = components.dateComponents - self.format = components.format - return - } - let cString = UnsafePointer(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen guard let components = SQLiteDateParser().components(cString: cString, length: length) else { @@ -158,163 +146,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn guard let string = String.fromDatabaseValue(dbValue) else { return nil } - - if useScanfStrategy { - return SQLiteDateParser().components(from: string) - } - - var dateComponents = DateComponents() - let scanner = Scanner(string: string) - scanner.charactersToBeSkipped = CharacterSet() - let hasDate: Bool - - // YYYY or HH - var initialNumber: Int = 0 - if !scanner.scanInt(&initialNumber) { - return nil - } - switch scanner.scanLocation { - case 2: - // HH - hasDate = false - - let hour = initialNumber - if hour >= 0 && hour <= 23 { - dateComponents.hour = hour - } else { - return nil - } - - case 4: - // YYYY - hasDate = true - - let year = initialNumber - if year >= 0 && year <= 9999 { - dateComponents.year = year - } else { - return nil - } - - // - - if !scanner.scanString("-", into: nil) { - return nil - } - - // MM - var month: Int = 0 - if scanner.scanInt(&month) && month >= 1 && month <= 12 { - dateComponents.month = month - } else { - return nil - } - - // - - if !scanner.scanString("-", into: nil) { - return nil - } - - // DD - var day: Int = 0 - if scanner.scanInt(&day) && day >= 1 && day <= 31 { - dateComponents.day = day - } else { - return nil - } - - // YYYY-MM-DD - if scanner.isAtEnd { - return DatabaseDateComponents(dateComponents, format: .YMD) - } - - // T/space - if !scanner.scanString("T", into: nil) && !scanner.scanString(" ", into: nil) { - return nil - } - - // HH - var hour: Int = 0 - if scanner.scanInt(&hour) && hour >= 0 && hour <= 23 { - dateComponents.hour = hour - } else { - return nil - } - - default: - return nil - } - - // : - if !scanner.scanString(":", into: nil) { - return nil - } - - // MM - var minute: Int = 0 - if scanner.scanInt(&minute) && minute >= 0 && minute <= 59 { - dateComponents.minute = minute - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HM) - } else { - return DatabaseDateComponents(dateComponents, format: .HM) - } - } - - // : - if !scanner.scanString(":", into: nil) { - return nil - } - - // SS - var second: Int = 0 - if scanner.scanInt(&second) && second >= 0 && second <= 59 { - dateComponents.second = second - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM:SS - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HMS) - } else { - return DatabaseDateComponents(dateComponents, format: .HMS) - } - } - - // . - if !scanner.scanString(".", into: nil) { - return nil - } - - // SSS - var millisecondDigits: NSString? = nil - if scanner.scanCharacters(from: .decimalDigits, into: &millisecondDigits), var millisecondDigits = millisecondDigits { - if millisecondDigits.length > 3 { - millisecondDigits = NSString(string: millisecondDigits.substring(to: 3)) - } - dateComponents.nanosecond = millisecondDigits.integerValue * 1_000_000 - } else { - return nil - } - - // [YYYY-MM-DD] HH:MM:SS.SSS - if scanner.isAtEnd { - if hasDate { - return DatabaseDateComponents(dateComponents, format: .YMD_HMSS) - } else { - return DatabaseDateComponents(dateComponents, format: .HMSS) - } - } - - // Unknown format - return nil + return SQLiteDateParser().components(from: string) } } From 85fbf64068ecc1a21390ec283711c5148ed93b20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:17:24 +0200 Subject: [PATCH 126/348] Add missing imports (should fix travis issues) --- GRDB/Core/Support/Foundation/DatabaseDateComponents.swift | 5 +++++ GRDB/Core/Support/Foundation/Date.swift | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 700dcae0d..7d2db6f00 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,4 +1,9 @@ import Foundation +#if SWIFT_PACKAGE + import CSQLite +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER + import SQLite3 +#endif /// DatabaseDateComponents reads and stores DateComponents in the database. public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumnConvertible { diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 51ee8eb77..78cdbbd30 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,4 +1,9 @@ import Foundation +#if SWIFT_PACKAGE + import CSQLite +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER + import SQLite3 +#endif /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. From 9efe4a6efadc22c0947a6d153e81c17db4e0687e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:18:46 +0200 Subject: [PATCH 127/348] Add a sanity check --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index d434ba2da..98d934b96 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -21,6 +21,8 @@ class SQLiteDateParser { } func components(cString: UnsafePointer, length: Int) -> DatabaseDateComponents? { + assert(strlen(cString) == length) + guard length >= 5 else { return nil } if cString.advanced(by: 4).pointee == 45 /* '-' */ { From 316d28746bdab05cdc2669228a0a3a3070dcb3d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:26:42 +0200 Subject: [PATCH 128/348] SQLiteDateParser: optimize nanoseconds parsing --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 98d934b96..0d8949e64 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -125,9 +125,8 @@ class SQLiteDateParser { } private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { - // truncate the nanosecond fraction - let nanoString = ("0." + nanosecond.withUnsafeBufferPointer { String(cString: $0.baseAddress!) }).prefix(5) - guard let doubleValue = Double(nanoString) else { return 0 } - return Int(doubleValue * 1_000_000_000) + return 1_000_000 * nanosecond.prefix(3).reduce(0) { (r, char) in + r * 10 + Int(char) - 48 /* '0' */ + } } } From 632bce55215018c37744007b0d4b16df10fad17d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 20 Apr 2018 19:41:34 +0200 Subject: [PATCH 129/348] SQLiteDateParser: don't parse garbage into nanoseconds --- .../Core/Support/Foundation/SQLiteDateParser.swift | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 0d8949e64..1f78d53b0 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -119,14 +119,20 @@ class SQLiteDateParser { guard parseCount >= 4 else { return DatabaseDateComponents(components, format: .HMS) } - components.nanosecond = nanosecondsInt(for: parserComponents.nanosecond) + guard let nanoseconds = nanosecondsInt(for: parserComponents.nanosecond) else { return nil } + components.nanosecond = nanoseconds return DatabaseDateComponents(components, format: .HMSS) } - private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int { - return 1_000_000 * nanosecond.prefix(3).reduce(0) { (r, char) in - r * 10 + Int(char) - 48 /* '0' */ + private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int? { + // truncate after the third digit + var result = 0 + for char in nanosecond.prefix(3) { + let digit = Int(char) - 48 /* '0' */ + guard (0...9).contains(digit) else { return nil } + result = result * 10 + digit } + return 1_000_000 * result } } From 8b175280fa7e698e0ab4a297328ec9130f5c75a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 07:40:11 +0200 Subject: [PATCH 130/348] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index ee8354e8c..3baced84d 100644 --- a/TODO.md +++ b/TODO.md @@ -80,6 +80,7 @@ Requires recompilation of SQLite: Reading list: +- Documentation generation: https://twitter.com/jckarter/status/987525569196650496: cmark is the implementation the Swift compiler uses for doc comments etc. - VACUUM (https://blogs.gnome.org/jnelson/) - http://www.sqlite.org/intern-v-extern-blob.html - https://sqlite.org/sharedcache.html From 219f96a11a907d2f29ca1a3ace3e6f2f3eb895ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 10:16:49 +0200 Subject: [PATCH 131/348] More DatabaseDateComponents parsing tests --- .../FoundationDateComponentsTests.swift | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 7edceb270..417a2af69 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -354,6 +354,156 @@ class FoundationDateComponentsTests : GRDBTestCase { } } + func testDatabaseDateComponentsParsing() { + func assertParse(_ string: String, _ dateComponent: DatabaseDateComponents, file: StaticString = #file, line: UInt = #line) { + do { + // Test DatabaseValueConvertible adoption + let parsed = DatabaseDateComponents.fromDatabaseValue(string.databaseValue)! + XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) + XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) + } + do { + // Test StatementColumnConvertible adoption + let parsed = DatabaseQueue().inDatabase { + try! DatabaseDateComponents.fetchOne($0, "SELECT ?", arguments: [string])! + } + XCTAssertEqual(parsed.format, dateComponent.format, file: file, line: line) + XCTAssertEqual(parsed.dateComponents, dateComponent.dateComponents, file: file, line: line) + } + } + + assertParse( + "0000-01-01", + DatabaseDateComponents( + DateComponents(year: 0, month: 1, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil), + format: .YMD)!) + assertParse( + "2018-12-31", + DatabaseDateComponents( + DateComponents(year: 2018, month: 12, day: 31, hour: nil, minute: nil, second: nil, nanosecond: nil), + format: .YMD)!) + assertParse( + "2018-04-21 00:00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), + format: .YMD_HM)!) + assertParse( + "2018-04-21T23:59", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: nil, nanosecond: nil), + format: .YMD_HM)!) + assertParse( + "2018-04-21 00:00:00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: nil), + format: .YMD_HMS)!) + assertParse( + "2018-04-21T23:59:59", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: nil), + format: .YMD_HMS)!) + assertParse( + "2018-04-21 00:00:00.0", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.9", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.00", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.01", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.99", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.000", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21 00:00:00.001", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), + format: .YMD_HMSS)!) + assertParse( + "2018-04-21T23:59:59.999", + DatabaseDateComponents( + DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), + format: .YMD_HMSS)!) + assertParse( + "00:00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: nil, nanosecond: nil), + format: .HM)!) + assertParse( + "23:59", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), + format: .HM)!) + assertParse( + "00:00:00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: nil), + format: .HMS)!) + assertParse( + "23:59:59", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: nil), + format: .HMS)!) + assertParse( + "00:00:00.0", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "23:59:59.9", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), + format: .HMSS)!) + assertParse( + "00:00:00.00", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "00:00:00.01", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), + format: .HMSS)!) + assertParse( + "23:59:59.99", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), + format: .HMSS)!) + assertParse( + "00:00:00.000", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), + format: .HMSS)!) + assertParse( + "00:00:00.001", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), + format: .HMSS)!) + assertParse( + "23:59:59.999", + DatabaseDateComponents( + DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), + format: .HMSS)!) + } + func testDatabaseDateComponentsFromUnparsableString() { let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue("foo".databaseValue) XCTAssertTrue(databaseDateComponents == nil) From 1311f6c87c7482645edc0986fbcfa958f5338505 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 10:17:07 +0200 Subject: [PATCH 132/348] SQLiteDateParser: fix nanosecond parsing --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 1f78d53b0..591d3c127 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -128,11 +128,13 @@ class SQLiteDateParser { private func nanosecondsInt(for nanosecond: ContiguousArray) -> Int? { // truncate after the third digit var result = 0 - for char in nanosecond.prefix(3) { + let multipliers = [100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1_000, 100, 10, 1] + for (char, multiplier) in zip(nanosecond.prefix(3), multipliers) { + if char == 0 { return result } let digit = Int(char) - 48 /* '0' */ guard (0...9).contains(digit) else { return nil } - result = result * 10 + digit + result += multiplier * digit } - return 1_000_000 * result + return result } } From 6c5d6ba6311c20537c7285ee7ff88676465a6283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 10:37:03 +0200 Subject: [PATCH 133/348] SQLiteDateParser: tighten vsscanf format --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 591d3c127..8ac84c250 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -55,7 +55,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%d-%d-%d%*c%d:%d:%d.%10s", pointer) + vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%10s", pointer) } } } @@ -100,7 +100,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%d:%d:%d.%10s", pointer) + vsscanf(cString, "%2d:%2d:%2d.%10s", pointer) } } } From f52536f4ae50aa5ca96bb19e2561b2fe46dd6ad4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 15:04:37 +0200 Subject: [PATCH 134/348] Append #334 to CHANGELOG --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6d28774e..ca07325a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,11 @@ Release Notes ============= +## Next Version + +- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909) + + ## 2.10.0 Released March 30, 2018 • [diff](https://github.com/groue/GRDB.swift/compare/v2.9.0...v2.10.0) From 00fa47b6b7cd5ca1354b1e96f49a45e54eb3d25e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 15:04:54 +0200 Subject: [PATCH 135/348] Family gets bigger :-) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 850cbbcda..ff903737e 100644 --- a/README.md +++ b/README.md @@ -6863,6 +6863,6 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy) [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From 4e57bf5a0e08475cebc498055b17fe2fc28f47a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 15:27:21 +0200 Subject: [PATCH 136/348] Fix a youth error: DatabaseDateComponents initializer from DateComponents is no longer failable --- .../Foundation/DatabaseDateComponents.swift | 8 +-- .../FoundationDateComponentsTests.swift | 56 +++++++++---------- 2 files changed, 27 insertions(+), 37 deletions(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 7d2db6f00..4ca356877 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -58,17 +58,11 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn /// Creates a DatabaseDateComponents from a DateComponents and a format. /// - /// The result is nil if and only if *dateComponents* is nil. - /// /// - parameters: /// - dateComponents: An optional DateComponents. /// - format: The format used for storing the date components in /// the database. - /// - returns: An optional DatabaseDateComponents. - public init?(_ dateComponents: DateComponents?, format: Format) { - guard let dateComponents = dateComponents else { - return nil - } + public init(_ dateComponents: DateComponents, format: Format) { self.format = format self.dateComponents = dateComponents } diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index 417a2af69..dc2c9dc78 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -376,140 +376,136 @@ class FoundationDateComponentsTests : GRDBTestCase { "0000-01-01", DatabaseDateComponents( DateComponents(year: 0, month: 1, day: 1, hour: nil, minute: nil, second: nil, nanosecond: nil), - format: .YMD)!) + format: .YMD)) assertParse( "2018-12-31", DatabaseDateComponents( DateComponents(year: 2018, month: 12, day: 31, hour: nil, minute: nil, second: nil, nanosecond: nil), - format: .YMD)!) + format: .YMD)) assertParse( "2018-04-21 00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: nil, nanosecond: nil), - format: .YMD_HM)!) + format: .YMD_HM)) assertParse( "2018-04-21T23:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: nil, nanosecond: nil), - format: .YMD_HM)!) + format: .YMD_HM)) assertParse( "2018-04-21 00:00:00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: nil), - format: .YMD_HMS)!) + format: .YMD_HMS)) assertParse( "2018-04-21T23:59:59", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: nil), - format: .YMD_HMS)!) + format: .YMD_HMS)) assertParse( "2018-04-21 00:00:00.0", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.9", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.00", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.01", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.99", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.000", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21 00:00:00.001", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "2018-04-21T23:59:59.999", DatabaseDateComponents( DateComponents(year: 2018, month: 04, day: 21, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), - format: .YMD_HMSS)!) + format: .YMD_HMSS)) assertParse( "00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: nil, nanosecond: nil), - format: .HM)!) + format: .HM)) assertParse( "23:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: nil, nanosecond: nil), - format: .HM)!) + format: .HM)) assertParse( "00:00:00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: nil), - format: .HMS)!) + format: .HMS)) assertParse( "23:59:59", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: nil), - format: .HMS)!) + format: .HMS)) assertParse( "00:00:00.0", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.9", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 900_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.00", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.01", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 10_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.99", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 990_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.000", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 0), - format: .HMSS)!) + format: .HMSS)) assertParse( "00:00:00.001", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 0, minute: 0, second: 0, nanosecond: 1_000_000), - format: .HMSS)!) + format: .HMSS)) assertParse( "23:59:59.999", DatabaseDateComponents( DateComponents(year: nil, month: nil, day: nil, hour: 23, minute: 59, second: 59, nanosecond: 999_000_000), - format: .HMSS)!) + format: .HMSS)) } func testDatabaseDateComponentsFromUnparsableString() { let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue("foo".databaseValue) XCTAssertTrue(databaseDateComponents == nil) } - - func testDatabaseDateComponentsFailureFromNilDateComponents() { - XCTAssertNil(DatabaseDateComponents(nil, format: .YMD)) - } } From c691625b15c22efee7dcf5d05d9a5bdae9920d6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 16:53:44 +0200 Subject: [PATCH 137/348] Dedicated implementations for AND and OR sql operators. Introduce joined(operator:) --- .../QueryInterfaceRequest.swift | 7 +- .../SQLExpression+QueryInterface.swift | 105 +++++++++++------- .../QueryInterface/Support/SQLOperators.swift | 48 +++++--- 3 files changed, 98 insertions(+), 62 deletions(-) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index f04147f6c..833a2b7f5 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -259,9 +259,6 @@ extension QueryInterfaceRequest where T: TableRecord { return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(db, keys: [[:]]) - GRDBPrecondition(!key.isEmpty, "Invalid empty key dictionary") - // Prevent filter(keys: [["foo": 1, "bar": 2]]) where // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) @@ -274,10 +271,10 @@ extension QueryInterfaceRequest where T: TableRecord { // Sort key columns in the same order as the unique index .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } .map { (column, value) in Column(column) == value } - return SQLBinaryOperator.and.join(columnPredicates)! // not nil because columnPredicates is not empty + return columnPredicates.joined(operator: .and) } - let keysPredicate = SQLBinaryOperator.or.join(keyPredicates)! // not nil because keyPredicates is not empty + let keysPredicate = keyPredicates.joined(operator: .or) if let expression = expression { return expression && keysPredicate diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index ee48475f6..35d993cc3 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -227,20 +227,6 @@ public struct SQLBinaryOperator : Hashable { public static func == (lhs: SQLBinaryOperator, rhs: SQLBinaryOperator) -> Bool { return lhs.sql == rhs.sql } - - // TODO: make it an extension of Sequence (like joined(separator:)) when Swift can better handle existentials - // TODO: make it public eventually - /// Return nil if expressions is empty. - func join(_ expressions: [SQLExpression]) -> SQLExpression? { - switch expressions.count { - case 0: - return nil - case 1: - return expressions[0] - default: - return SQLExpressionBinaryOperatorChain(op: self, expressions: expressions) - } - } } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -325,23 +311,6 @@ public struct SQLExpressionBinary : SQLExpression { return nil } - case .and: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case (nil, nil): return nil - case let (ids?, nil), let (nil, ids?): return ids - case let (lids?, rids?): return lids.intersection(rids) - } - - case .or: - let lids = lhs.matchedRowIds(rowIdName: rowIdName) - let rids = rhs.matchedRowIds(rowIdName: rowIdName) - switch (lids, rids) { - case let (lids?, rids?): return lids.union(rids) - default: return nil - } - default: return nil } @@ -354,29 +323,79 @@ public struct SQLExpressionBinary : SQLExpression { } } -// MARK: - SQLExpressionBinaryOperatorChain +// MARK: - SQLExpressionAnd -struct SQLExpressionBinaryOperatorChain : SQLExpression { - let op: SQLBinaryOperator +struct SQLExpressionAnd : SQLExpression { let expressions: [SQLExpression] - // Exposed to SQLBinaryOperator.join - fileprivate init(op: SQLBinaryOperator, expressions: [SQLExpression]) { - assert(expressions.count >= 2) - self.op = op + init(_ expressions: [SQLExpression]) { self.expressions = expressions } func expressionSQL(_ arguments: inout StatementArguments?) -> String { + guard let expression = expressions.first else { + // Ruby [].all? # => true + return true.sqlExpression.expressionSQL(&arguments) + } + if expressions.count == 1 { + return expression.expressionSQL(&arguments) + } let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } - let joiner = " \(op.sql) " - return "(" + expressionSQLs.joined(separator: joiner) + ")" + return "(" + expressionSQLs.joined(separator: " AND ") + ")" } func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionBinaryOperatorChain( - op: op, - expressions: expressions.map { $0.qualifiedExpression(with: qualifier) }) + return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + let matchedRowIds = expressions.compactMap { + $0.matchedRowIds(rowIdName: rowIdName) + } + guard let first = matchedRowIds.first else { + return nil + } + return matchedRowIds.suffix(from: 1).reduce(into: first) { $0.formIntersection($1) } + } +} + +// MARK: - SQLExpressionOr + +struct SQLExpressionOr : SQLExpression { + let expressions: [SQLExpression] + + init(_ expressions: [SQLExpression]) { + self.expressions = expressions + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + guard let expression = expressions.first else { + // Ruby [].any? # => false + return false.sqlExpression.expressionSQL(&arguments) + } + if expressions.count == 1 { + return expression.expressionSQL(&arguments) + } + let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } + return "(" + expressionSQLs.joined(separator: " OR ") + ")" + } + + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + if expressions.isEmpty { + return [] + } + var result: Set = [] + for expr in expressions { + guard let matchedRowIds = expr.matchedRowIds(rowIdName: rowIdName) else { + return nil + } + result.formUnion(matchedRowIds) + } + return result } } diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index 4dde080e2..b7734489d 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -697,20 +697,12 @@ public func - (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLE // MARK: - Logical Operators (AND, OR, NOT) -extension SQLBinaryOperator { - /// The `AND` binary operator - static let and = SQLBinaryOperator("AND") - - /// The `OR` binary operator - static let or = SQLBinaryOperator("OR") -} - /// A logical SQL expression with the `AND` SQL operator. /// /// // favorite AND 0 /// Column("favorite") && false public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -718,7 +710,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 AND favorite /// false && Column("favorite") public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `AND` SQL operator. @@ -726,7 +718,7 @@ public func && (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NOT NULL AND favorite /// Column("email") != nil && Column("favorite") public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.and, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionAnd([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -734,7 +726,7 @@ public func && (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // favorite OR 1 /// Column("favorite") || true public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -742,7 +734,7 @@ public func || (lhs: SQLSpecificExpressible, rhs: SQLExpressible) -> SQLExpressi /// // 0 OR favorite /// true || Column("favorite") public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A logical SQL expression with the `OR` SQL operator. @@ -750,7 +742,7 @@ public func || (lhs: SQLExpressible, rhs: SQLSpecificExpressible) -> SQLExpressi /// // email IS NULL OR hidden /// Column("email") == nil || Column("hidden") public func || (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.or, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionOr([lhs.sqlExpression, rhs.sqlExpression]) } /// A negated logical SQL expression with the `NOT` SQL operator. @@ -766,6 +758,34 @@ public prefix func ! (value: SQLSpecificExpressible) -> SQLExpression { return value.sqlExpression.negated } +public enum SQLLogicalBinaryOperator { + case and, or +} + +extension Sequence where Element: SQLExpressible { + /// Return an expression by joining all elements with an SQL logical + /// operator + public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { + let expressions: [SQLExpression] = map { $0.sqlExpression } + switch `operator` { + case .and: return SQLExpressionAnd(expressions) + case .or: return SQLExpressionOr(expressions) + } + } +} + +extension Sequence where Element == SQLExpression { + /// Return an expression by joining all elements with an SQL logical + /// operator + public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { + let expressions = Array(self) + switch `operator` { + case .and: return SQLExpressionAnd(expressions) + case .or: return SQLExpressionOr(expressions) + } + } +} + // MARK: - Like Operator From 729f6bdc6ced7a5b76da855456510ea19bf00a6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 17:05:03 +0200 Subject: [PATCH 138/348] Tests for joined(operator:) --- .../QueryInterfaceExpressionsTests.swift | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index 988918f8d..b06954417 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -727,6 +727,40 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18) AND NOT (\"name\" > 'foo'))") } + func testJoinedOperatorAnd() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL))") + } + + func testJoinedOperatorOr() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL))") + } + // MARK: - String functions From d63565f191e6c904ff7f7f6a0847e928b7917427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 17:17:46 +0200 Subject: [PATCH 139/348] Documentation for joined(operator:) --- .../QueryInterface/Support/SQLOperators.swift | 37 ++++++++++++------- README.md | 21 +++++++++++ 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index b7734489d..fe6925695 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -762,21 +762,30 @@ public enum SQLLogicalBinaryOperator { case and, or } -extension Sequence where Element: SQLExpressible { - /// Return an expression by joining all elements with an SQL logical - /// operator - public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { - let expressions: [SQLExpression] = map { $0.sqlExpression } - switch `operator` { - case .and: return SQLExpressionAnd(expressions) - case .or: return SQLExpressionOr(expressions) - } - } -} - extension Sequence where Element == SQLExpression { - /// Return an expression by joining all elements with an SQL logical - /// operator + /// Returns an expression by joining all elements with an SQL + /// logical operator. + /// + /// For example: + /// + /// // SELECT * FROM players + /// // WHERE (registered + /// // AND (score >= 1000) + /// // AND (name IS NOT NULL)) + /// let conditions = [ + /// Column("registered"), + /// Column("score") >=< 1000, + /// Column("name") != nil] + /// Player.filter(conditions.joined(operator: .and)) + /// + /// When the sequence is empty, `joined(operator: .and)` returns true, + /// and `joined(operator: .or)` returns false: + /// + /// // SELECT * FROM players WHERE 1 + /// Player.filter([].joined(operator: .and)) + /// + /// // SELECT * FROM players WHERE 0 + /// Player.filter([].joined(operator: .or)) public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { let expressions = Array(self) switch `operator` { diff --git a/README.md b/README.md index db383139d..4dc8ba7e5 100644 --- a/README.md +++ b/README.md @@ -3423,6 +3423,27 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: // SELECT * FROM players WHERE ((NOT verified) OR (score < 1000)) Player.filter(!verifiedColumn || scoreColumn < 1000) ``` + + When you want to join a sequence of expressions with `AND` or `OR` operators, use `joined(operator:)`: + + ```swift + // SELECT * FROM players WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) + let conditions = [ + verifiedColumn, + scoreColumn >=< 1000, + nameColumn != nil] + Player.filter(conditions.joined(operator: .and)) + ``` + + When the sequence is empty, `joined(operator: .and)` returns true, and `joined(operator: .or)` returns false: + + ```swift + // SELECT * FROM players WHERE 1 + Player.filter([].joined(operator: .and)) + + // SELECT * FROM players WHERE 0 + Player.filter([].joined(operator: .or)) + ``` - `BETWEEN`, `IN`, `NOT IN` From f4ab65e399458025abd480581409c90d5553e942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 17:21:16 +0200 Subject: [PATCH 140/348] Fix typo --- GRDB/QueryInterface/Support/SQLOperators.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index fe6925695..f0e8a78db 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -774,7 +774,7 @@ extension Sequence where Element == SQLExpression { /// // AND (name IS NOT NULL)) /// let conditions = [ /// Column("registered"), - /// Column("score") >=< 1000, + /// Column("score") >= 1000, /// Column("name") != nil] /// Player.filter(conditions.joined(operator: .and)) /// From b8fc762e11ecab7876319c1ec025310c58037c72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 19:28:58 +0200 Subject: [PATCH 141/348] Cleanup --- GRDB/Migration/DatabaseMigrator.swift | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index d3bd3af3c..7e8ba9b1a 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -148,7 +148,7 @@ public struct DatabaseMigrator { /// Returns the set of applied migration identifiers. public func appliedMigrations(in reader: DatabaseReader) throws -> Set { - return try reader.read { try appliedMigrations($0) } + return try reader.read { try appliedIdentifiers($0) } } @@ -165,13 +165,13 @@ public struct DatabaseMigrator { try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") } - private func appliedMigrations(_ db: Database) throws -> Set { + private func appliedIdentifiers(_ db: Database) throws -> Set { return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations")) } private func runMigrations(_ db: Database) throws { - let appliedMigrations = try self.appliedMigrations(db) - for migration in migrations where !appliedMigrations.contains(migration.identifier) { + let appliedIdentifiers = try self.appliedIdentifiers(db) + for migration in migrations where !appliedIdentifiers.contains(migration.identifier) { try migration.run(db) } } @@ -189,13 +189,13 @@ public struct DatabaseMigrator { GRDBPrecondition(prefixMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") // Subsequent migration must not be applied - let appliedMigrations = try self.appliedMigrations(db) + let appliedIdentifiers = try self.appliedIdentifiers(db) if prefixMigrations.count < migrations.count { let nextIdentifier = migrations[prefixMigrations.count].identifier - GRDBPrecondition(!appliedMigrations.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") + GRDBPrecondition(!appliedIdentifiers.contains(nextIdentifier), "database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } - for migration in prefixMigrations where !appliedMigrations.contains(migration.identifier) { + for migration in prefixMigrations where !appliedIdentifiers.contains(migration.identifier) { try migration.run(db) } } From c21a330dce4527b6dc9d39cabeb686f9fac51d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 19:40:30 +0200 Subject: [PATCH 142/348] Cleanup --- GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift | 4 ++-- GRDB/QueryInterface/FTS5+QueryInterface.swift | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 7d958533e..524ae73fd 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -2,8 +2,8 @@ extension QueryInterfaceRequest { // MARK: Full Text Search - /// Returns a new QueryInterfaceRequest with a matching predicate added - /// to the eventual set of already applied predicates. + /// Creates a request with a full-text predicate added to the eventual + /// set of already applied predicates. /// /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.all() diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index b7423d5da..0394a5450 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -3,8 +3,8 @@ // MARK: Full Text Search - /// Returns a new QueryInterfaceRequest with a matching predicate added - /// to the eventual set of already applied predicates. + /// Creates a request with a full-text predicate added to the eventual + /// set of already applied predicates. /// /// // SELECT * FROM books WHERE books MATCH '...' /// var request = Book.all() From 73e89f76aa6b6cd5faaa82054bb61559bb334a12 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 19:41:21 +0200 Subject: [PATCH 143/348] Introduce TableDefinition.autoIncrementedPrimaryKey --- GRDB/QueryInterface/TableDefinition.swift | 32 +++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 49c3d8d41..2fadbe2cf 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -248,6 +248,38 @@ public final class TableDefinition { self.withoutRowID = withoutRowID } + /// Defines the auto-incremented primary key. + /// + /// try db.create(table: "players") { t in + /// t.autoIncrementedPrimaryKey("id") + /// } + /// + /// The auto-incremented primary key is an integer primary key that + /// automatically generates unused values when you do not explicitely + /// provide one, and prevents the reuse of ids over the lifetime of + /// the database. + /// + /// **It is the preferred way to define a numeric primary key**. + /// + /// The fact that an auto-incremented primary key prevents the reuse of + /// ids is an excellent guard against data races that could happen when your + /// application processes ids in an asynchronous way. The auto-incremented + /// primary key provides the guarantee that a given id can't reference a row + /// that is different from the one it used to be at the beginning of the + /// asynchronous process, even if this row gets deleted and a new one is + /// inserted in between. + /// + /// See https://www.sqlite.org/lang_createtable.html#primkeyconst and + /// https://www.sqlite.org/lang_createtable.html#rowid + /// + /// - parameter conflitResolution: An optional conflict resolution + /// (see https://www.sqlite.org/lang_conflict.html). + /// - returns: Self so that you can further refine the column definition. + @discardableResult + public func autoIncrementedPrimaryKey(_ name: String, onConflict conflictResolution: Database.ConflictResolution? = nil) -> ColumnDefinition { + return column(name, .integer).primaryKey(onConflict: conflictResolution, autoincrement: true) + } + /// Appends a table column. /// /// try db.create(table: "players") { t in From 822ff97050dc0050dc1718d97c50a6b1228f6dd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 19:41:45 +0200 Subject: [PATCH 144/348] Tests for TableDefinition.autoIncrementedPrimaryKey --- Tests/GRDBTests/TableDefinitionTests.swift | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index f70fa0c16..b25ec0aa2 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -65,6 +65,32 @@ class TableDefinitionTests: GRDBTestCase { } } + func testAutoIncrementedPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.autoIncrementedPrimaryKey("id") + } + assertEqualSQL(lastSQLQuery, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY AUTOINCREMENT\ + ) + """) + return .rollback + } + try dbQueue.inTransaction { db in + try db.create(table: "test") { t in + t.autoIncrementedPrimaryKey("id", onConflict: .fail) + } + assertEqualSQL(lastSQLQuery, """ + CREATE TABLE "test" (\ + "id" INTEGER PRIMARY KEY ON CONFLICT FAIL AUTOINCREMENT\ + ) + """) + return .rollback + } + } + func testColumnPrimaryKeyOptions() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in From e80dab2ea9fbed4ac3e523f9daf63eedfde1407f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 19:42:27 +0200 Subject: [PATCH 145/348] Documentation for TableDefinition.autoIncrementedPrimaryKey --- README.md | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4dc8ba7e5..c01429e48 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ Avoid SQL with the [query interface](#the-query-interface): ```swift try dbQueue.write { db in try db.create(table: "places") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) t.column("longitude", .double).notNull() @@ -1707,7 +1707,7 @@ Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ```swift try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("name", .text) } @@ -2660,7 +2660,7 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab // email TEXT UNIQUE ON CONFLICT REPLACE // ) try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("email", .text).unique(onConflict: .replace) // <-- } @@ -2678,7 +2678,7 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab // email TEXT UNIQUE // ) try db.create(table: "players") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("email", .text) } @@ -3013,7 +3013,7 @@ Once granted with a [database connection](#database-connections), you can setup // longitude DOUBLE NOT NULL // ) try db.create(table: "places") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("title", .text) t.column("favorite", .boolean).notNull().defaults(to: false) t.column("longitude", .double).notNull() @@ -3067,8 +3067,11 @@ Define **not null** columns, and set **default** values: Use an individual column as **primary**, **unique**, or **foreign key**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise): ```swift - // id INTEGER PRIMARY KEY, - t.column("id", .integer).primaryKey() + // id INTEGER PRIMARY KEY AUTOINCREMENT, + t.autoIncrementedPrimaryKey("id") + + // uuid TEXT PRIMARY KEY, + t.column("uuid", .text).primaryKey() // email TEXT UNIQUE, t.column("email", .text).unique() @@ -3077,6 +3080,10 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de t.column("countryCode", .text).references("countries", onDelete: .cascade) ``` +> :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method. +> +> Such primary key prevents the reuse of ids, and is an excellent guard against data races that could happen when your application processes ids in an asynchronous way. The auto-incremented primary key provides the guarantee that a given id can't reference a row that is different from the one it used to be at the beginning of the asynchronous process, even if this row gets deleted and a new one is inserted in between. + **Create an index** on the column: ```swift From 7aacaef2cd58eb9d8cd7bf8f6901e54676105b4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 21 Apr 2018 20:11:34 +0200 Subject: [PATCH 146/348] Foster autoIncrementedPrimaryKey in documentation --- GRDB/Core/Database.swift | 2 +- GRDB/QueryInterface/TableDefinition.swift | 6 +++--- GRDB/Record/TableRecord.swift | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index ee961927b..9d38e5cd9 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -888,7 +888,7 @@ extension Database { /// An SQL column type. /// /// try db.create(table: "players") { t in - /// t.column("id", .integer).primaryKey() + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// } /// diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 2fadbe2cf..d9168e733 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -6,7 +6,7 @@ extension Database { /// Creates a database table. /// /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() @@ -35,7 +35,7 @@ extension Database { /// Creates a database table. /// /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() @@ -67,7 +67,7 @@ extension Database { /// Creates a database table. /// /// try db.create(table: "pointOfInterests") { t in - /// t.column("id", .integer).primaryKey() + /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) /// t.column("longitude", .double).notNull() diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 82bf379e2..db1483e0c 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -104,7 +104,7 @@ extension TableRecord { /// /// try dbQueue.write { db in /// try db.create(table: "players") { t in - /// t.column("id", .integer).primaryKey() + /// t.autoIncrementedPrimaryKey("id") /// t.column("name", .text) /// t.column("score", .integer) /// } From 2dae6d945f31f2579249823d60ecc0ea51bb7595 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 07:17:26 +0200 Subject: [PATCH 147/348] #330 follow-up: extract QualifiedColumn from Column --- GRDB/QueryInterface/Column.swift | 37 +++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 337cd2107..c5f4a700e 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -8,8 +8,6 @@ public struct Column : SQLExpression { /// The name of the column public let name: String - private var qualifier: SQLTableQualifier? - /// Creates a column given its name. public init(_ name: String) { self.name = name @@ -18,21 +16,36 @@ public struct Column : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier?.name { - return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier - } return name.quotedDatabaseIdentifier } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - if self.qualifier != nil { - // Never requalify - return self - } - var column = self - column.qualifier = qualifier - return column + return QualifiedColumn(name, qualifier: qualifier) + } +} + +/// A qualified column in the database, as in `SELECT t.a FROM t` +struct QualifiedColumn : SQLExpression { + let name: String + private var qualifier: SQLTableQualifier + + /// Creates a column given its name. + init(_ name: String, qualifier: SQLTableQualifier) { + self.name = name + self.qualifier = qualifier + } + + func expressionSQL(_ arguments: inout StatementArguments?) -> String { + if let qualifierName = qualifier.name { + return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier + } + return name.quotedDatabaseIdentifier + } + + func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + // Never requalify + return self } } From b2d2d17ddad28a7cd8139979a4a8dbced3fbf86f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 07:26:08 +0200 Subject: [PATCH 148/348] #330 follow-up: extract QualifiedAllColumns from AllColumns --- GRDB/QueryInterface/Column.swift | 6 +- .../SQLSelectable+QueryInterface.swift | 66 +++++++++++-------- 2 files changed, 43 insertions(+), 29 deletions(-) diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index c5f4a700e..8c2f61f56 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -6,7 +6,7 @@ public struct Column : SQLExpression { public static let rowID = Column("rowid") /// The name of the column - public let name: String + public var name: String /// Creates a column given its name. public init(_ name: String) { @@ -28,8 +28,8 @@ public struct Column : SQLExpression { /// A qualified column in the database, as in `SELECT t.a FROM t` struct QualifiedColumn : SQLExpression { - let name: String - private var qualifier: SQLTableQualifier + var name: String + private let qualifier: SQLTableQualifier /// Creates a column given its name. init(_ name: String, qualifier: SQLTableQualifier) { diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 4245a28c3..0e45abddd 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -15,9 +15,6 @@ /// // SELECT *, rowid FROM players /// let request = Player.all() public struct AllColumns { - private var qualifier: SQLTableQualifier? - - /// public init() { } } @@ -25,19 +22,12 @@ extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier?.name { - return qualifierName.quotedDatabaseIdentifier + ".*" - } return "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func countedSQL(_ arguments: inout StatementArguments?) -> String { - guard qualifier == nil else { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") - } return "*" } @@ -45,11 +35,7 @@ extension AllColumns : SQLSelectable { /// :nodoc: public func count(distinct: Bool) -> SQLCount? { // SELECT DISTINCT * FROM tableName ... - guard !distinct else { - return nil - } - - guard qualifier == nil else { + if distinct { return nil } @@ -62,25 +48,53 @@ extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - if self.qualifier != nil { - // Never requalify - return self - } - var allColumns = AllColumns() - allColumns.qualifier = qualifier - return allColumns + return QualifiedAllColumns(qualifier: qualifier) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func columnCount(_ db: Database) throws -> Int { - guard let qualifier = qualifier else { - fatalError("Can't compute number of columns without a qualifier") - } - return try db.columns(in: qualifier.tableName).count + fatalError("Can't compute number of columns without a qualifier") } } +// MARK: - QualifiedAllColumns + +/// QualifiedAllColumns is the `t.*` in `SELECT t.*`. +struct QualifiedAllColumns { + private let qualifier: SQLTableQualifier + + init(qualifier: SQLTableQualifier) { + self.qualifier = qualifier + } +} + +extension QualifiedAllColumns : SQLSelectable { + func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + if let qualifierName = qualifier.name { + return qualifierName.quotedDatabaseIdentifier + ".*" + } + return "*" + } + + func countedSQL(_ arguments: inout StatementArguments?) -> String { + // SELECT COUNT(t.*) is invalid SQL + fatalError("Not implemented, or invalid query") + } + + func count(distinct: Bool) -> SQLCount? { + return nil + } + + func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + // Never requalify + return self + } + + func columnCount(_ db: Database) throws -> Int { + return try db.columns(in: qualifier.tableName).count + } +} // MARK: - SQLAliasedExpression From 4c6147fc3765b826e59c6fe20bf672fa9331c4c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 12:05:11 +0200 Subject: [PATCH 149/348] Documentation --- README.md | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c01429e48..fdf206c9c 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,11 @@ Database access methods can return values, for easy extraction of database value let placeCount = try dbQueue.read { db in try Place.fetchCount(db) } + +let newPlaceCount = try dbQueue.write { db -> Int in + try Place(...).insert(db) + returns try Place.fetchCount(db) +} ``` **A database queue needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. @@ -361,7 +366,8 @@ See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Ap > :muscle: **Note to database experts**: The `write` and `read` database access methods generally help enforcing the [GRDB concurrency guarantees](#concurrency), and are highly recommended, even for skilled developers, because they lift most of the mental burden related to explicit SQLite transactions: > -> `DatabaseQueue.write` wraps your database statements in a transaction, and rollbacks on the first unhandled error. `DatabaseQueue.read` enforces read-only access. +> - `DatabaseQueue.write` wraps your database statements in a transaction. On the first unhandled error, the whole transaction is rollbacked, and the error rethrown. +> - `DatabaseQueue.read` does not open any transaction, but enforces read-only access. > > When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). @@ -417,6 +423,11 @@ Database access methods can return values, for easy extraction of database value let placeCount = try dbPool.read { db in try Place.fetchCount(db) } + +let newPlaceCount = try dbPool.write { db -> Int in + try Place(...).insert(db) + returns try Place.fetchCount(db) +} ``` **A database pool needs your application to follow rules in order to deliver its safety guarantees.** Please refer to the [Concurrency](#concurrency) chapter. @@ -436,8 +447,8 @@ Unlike [database queues](#database-queues), pools allow several threads to acces - Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. -- The `write` method wraps your database statements in a transaction, and rollbacks on the first unhandled error. - +- The `write` method wraps your database statements in a transaction. On the first unhandled error, the whole transaction is rollbacked, and the error rethrown. + When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints) for more information. - Database pools can take [snapshots](#database-snapshots) of the database. From d3879567c49c453ab2fe3027ed30aa6a67d6c80b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:26:40 +0200 Subject: [PATCH 150/348] New "Examples of Record Definitions" chapter (addresses #338) --- README.md | 216 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 204 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index fdf206c9c..912507489 100644 --- a/README.md +++ b/README.md @@ -1966,6 +1966,10 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) + +**Records in a glance** + +- [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) @@ -2072,6 +2076,7 @@ Details follow: - [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) +- [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) @@ -2540,38 +2545,57 @@ place.id // A unique id **Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can compare against previous versions of themselves in order to [avoid useless updates](#record-comparison). -Record subclasses define their custom database relationship by overriding database methods: +Record subclasses define their custom database relationship by overriding database methods. For example: ```swift -class Place : Record { +class Place: Record { var id: Int64? var title: String + var isFavorite: Bool var coordinate: CLLocationCoordinate2D + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + } + + /// The table columns + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let favorite = Column("favorite") + static let latitude = Column("latitude") + static let longitude = Column("longitude") + } + /// The table name override class var databaseTableName: String { return "places" } - /// Initialize from a database row + /// Creates a record from a database row required init(row: Row) { - id = row["id"] - title = row["title"] + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] coordinate = CLLocationCoordinate2D( - latitude: row["latitude"], - longitude: row["longitude"]) + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) super.init(row: row) } /// The values persisted in the database override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["title"] = title - container["latitude"] = coordinate.latitude - container["longitude"] = coordinate.longitude + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude } - /// When relevant, update record ID after a successful insertion + /// Update record ID after a successful insertion override func didInsert(with rowID: Int64, for column: String?) { id = rowID } @@ -2854,6 +2878,174 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu ``` +## Examples of Record Definitions + +We will show below how to declare a record type for the following database table: + +```swift +dbQueue.write { db in + try db.create(table: "places") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text).notNull() + t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() + } +} +``` + +Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application: + +- Example 1: Define a Codable struct and adopt each one of the [record protocols](#record-protocols-overview). + + ```swift + struct Place: Codable { + var id: Int64? + var title: String + var isFavorite: Bool + var latitude: CLLocationDegrees + var longitude: CLLocationDegrees + + var coordinate: CLLocationCoordinate2D { + get { + return CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) + } + set { + latitude = newValue.latitude + longitude = newValue.longitude + } + } + } + + extension Place: TableRecord { + /// The table name + static let databaseTableName = "players" + } + + extension Place: FetchableRecord { } + + extension Place: MutablePersistableRecord { + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowId + } + } + ``` + +- Example 2: Define a plain struct and explicitely adopt each one of the [record protocols](#record-protocols-overview). + + ```swift + struct Place { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + } + + extension Place: TableRecord { + /// The table name + static let databaseTableName = "players" + + /// The table columns + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let favorite = Column("favorite") + static let latitude = Column("latitude") + static let longitude = Column("longitude") + } + } + + extension Place: FetchableRecord { + /// Creates a record from a database row + init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + } + + extension Place: MutablePersistableRecord { + /// The values persisted in the database + func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowId + } + } + ``` + +- Example 3: Subclass the [Record class](#record-class). + + ```swift + class Place: Record { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + } + + /// The table columns + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let favorite = Column("favorite") + static let latitude = Column("latitude") + static let longitude = Column("longitude") + } + + /// The table name + override class var databaseTableName: String { + return "places" + } + + /// Creates a record from a database row + required init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + + /// The values persisted in the database + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } + } + ``` + + ## List of Record Methods This is the list of record methods, along with their required protocols. The [Record](#record-class) adopts all these protocols, and adds a few extra methods. From 6722ea8676de2bfc26199287b8144cf0e3206e3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:29:52 +0200 Subject: [PATCH 151/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 912507489..bc8b12681 100644 --- a/README.md +++ b/README.md @@ -2883,7 +2883,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu We will show below how to declare a record type for the following database table: ```swift -dbQueue.write { db in +try dbQueue.write { db in try db.create(table: "places") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() From 405b537ef29785b969f3a4158d025f36dd779514 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:32:26 +0200 Subject: [PATCH 152/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc8b12681..b1ddd2632 100644 --- a/README.md +++ b/README.md @@ -2902,7 +2902,7 @@ Each one of the three examples below is correct. You will pick one or the other struct Place: Codable { var id: Int64? var title: String - var isFavorite: Bool + var favorite: Bool var latitude: CLLocationDegrees var longitude: CLLocationDegrees From db31a94461cc760cfc6f99c5e6fbab85771f0dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:35:36 +0200 Subject: [PATCH 153/348] Typo --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index b1ddd2632..01a315402 100644 --- a/README.md +++ b/README.md @@ -2559,6 +2559,7 @@ class Place: Record { self.title = title self.isFavorite = isFavorite self.coordinate = coordinate + super.init() } /// The table columns @@ -3002,6 +3003,7 @@ Each one of the three examples below is correct. You will pick one or the other self.title = title self.isFavorite = isFavorite self.coordinate = coordinate + super.init() } /// The table columns From b590ee54441cc9321fb5e6444e3e451467e9f215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:39:28 +0200 Subject: [PATCH 154/348] Typo --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 01a315402..c9573c50b 100644 --- a/README.md +++ b/README.md @@ -2930,7 +2930,7 @@ Each one of the three examples below is correct. You will pick one or the other extension Place: MutablePersistableRecord { /// Update record ID after a successful insertion mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowId + id = rowID } } ``` @@ -2968,7 +2968,6 @@ Each one of the three examples below is correct. You will pick one or the other coordinate = CLLocationCoordinate2D( latitude: row[Columns.latitude], longitude: row[Columns.longitude]) - super.init(row: row) } } @@ -2984,7 +2983,7 @@ Each one of the three examples below is correct. You will pick one or the other /// Update record ID after a successful insertion mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowId + id = rowID } } ``` From 71d602850e92866b55c5b84631be0335429c7b80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 13:49:13 +0200 Subject: [PATCH 155/348] Typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c9573c50b..9d827c72a 100644 --- a/README.md +++ b/README.md @@ -2922,7 +2922,7 @@ Each one of the three examples below is correct. You will pick one or the other extension Place: TableRecord { /// The table name - static let databaseTableName = "players" + static let databaseTableName = "places" } extension Place: FetchableRecord { } @@ -2947,7 +2947,7 @@ Each one of the three examples below is correct. You will pick one or the other extension Place: TableRecord { /// The table name - static let databaseTableName = "players" + static let databaseTableName = "places" /// The table columns enum Columns { From 29b364d5cb555c63e8e9adfe88a9d233c8d8b0ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 14:56:40 +0200 Subject: [PATCH 156/348] Introduce SQLColumnExpression --- GRDB/Core/Row.swift | 12 ++--- GRDB/QueryInterface/Column.swift | 51 +++++++++++++------ .../FTS3+QueryInterfaceRequest.swift | 2 +- .../SQLExpression+QueryInterface.swift | 20 ++++---- GRDB/Record/PersistableRecord.swift | 4 +- README.md | 12 +---- Tests/GRDBTests/FTS3RecordTests.swift | 4 +- Tests/GRDBTests/FTS4RecordTests.swift | 4 +- Tests/GRDBTests/FTS5RecordTests.swift | 4 +- .../RecordPrimaryKeyHiddenRowIDTests.swift | 4 +- 10 files changed, 65 insertions(+), 52 deletions(-) diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 28ae77920..ff28110e1 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -347,7 +347,7 @@ extension Row { /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: SQLColumnExpression) -> DatabaseValueConvertible? { return self[column.name] } @@ -359,7 +359,7 @@ extension Row { /// If the column is missing or if the SQLite value is NULL, the result is /// nil. Otherwise the SQLite value is converted to the requested type /// `Value`. Should this conversion fail, a fatal error is raised. - public subscript(_ column: Column) -> Value? { + public subscript(_ column: SQLColumnExpression) -> Value? { return self[column.name] } @@ -375,7 +375,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: Column) -> Value? { + public subscript(_ column: SQLColumnExpression) -> Value? { return self[column.name] } @@ -388,7 +388,7 @@ extension Row { /// /// This method crashes if the fetched SQLite value is NULL, or if the /// SQLite value can not be converted to `Value`. - public subscript(_ column: Column) -> Value { + public subscript(_ column: SQLColumnExpression) -> Value { return self[column.name] } @@ -405,7 +405,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: Column) -> Value { + public subscript(_ column: SQLColumnExpression) -> Value { return self[column.name] } @@ -453,7 +453,7 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: Column) -> Data? { + public func dataNoCopy(_ column: SQLColumnExpression) -> Data? { return dataNoCopy(named: column.name) } } diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 8c2f61f56..56b0507bd 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -1,18 +1,9 @@ -/// A column in the database -/// -/// See https://github.com/groue/GRDB.swift#the-query-interface -public struct Column : SQLExpression { - /// The hidden rowID column - public static let rowID = Column("rowid") - - /// The name of the column - public var name: String - - /// Creates a column given its name. - public init(_ name: String) { - self.name = name - } - +/// The protocol for types that define database columns +public protocol SQLColumnExpression: SQLExpression { + var name: String { get } +} + +extension SQLColumnExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { @@ -26,8 +17,24 @@ public struct Column : SQLExpression { } } +/// A column in a database table +/// +/// See https://github.com/groue/GRDB.swift#the-query-interface +public struct Column: SQLColumnExpression { + /// The hidden rowID column + public static let rowID = Column("rowid") + + /// The name of the column + public var name: String + + /// Creates a column given its name. + public init(_ name: String) { + self.name = name + } +} + /// A qualified column in the database, as in `SELECT t.a FROM t` -struct QualifiedColumn : SQLExpression { +struct QualifiedColumn: SQLColumnExpression { var name: String private let qualifier: SQLTableQualifier @@ -49,3 +56,15 @@ struct QualifiedColumn : SQLExpression { return self } } + +extension CodingKey where Self: SQLColumnExpression { + public var name: String { + return stringValue + } +} + +extension SQLColumnExpression where Self: RawRepresentable, Self.RawValue == String { + public var name: String { + return rawValue + } +} diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 524ae73fd..768f613f9 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -42,7 +42,7 @@ extension TableRecord { } } -extension Column { +extension SQLColumnExpression { /// A matching SQL expression with the `MATCH` SQL operator. /// /// // content MATCH '...' diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 35d993cc3..b7ebe9512 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -285,28 +285,29 @@ public struct SQLExpressionBinary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func matchedRowIds(rowIdName: String?) -> Set? { + // FIXME: this implementation ignores column qualifiers switch op { case .equal, .is: - // Look for `id == 1` or `id IS 1`? - switch (lhs, rhs) { - case (let column as Column, let dbValue as DatabaseValue), - (let dbValue as DatabaseValue, let column as Column): - // Look for `id == 1`, `rowid == 1`, `1 == id`, `1 == rowid` - + // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` + func matchedRowIds(column: SQLColumnExpression, dbValue: DatabaseValue) -> Set? { var rowIdNames = [Column.rowID.name.lowercased()] if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) } - guard rowIdNames.contains(column.name.lowercased()) else { return nil } - if let rowId = Int64.fromDatabaseValue(dbValue) { return [rowId] } else { return [] } + } + switch (lhs, rhs) { + case (let column as SQLColumnExpression, let dbValue as DatabaseValue): + return matchedRowIds(column: column, dbValue: dbValue) + case (let dbValue as DatabaseValue, let column as SQLColumnExpression): + return matchedRowIds(column: column, dbValue: dbValue) default: return nil } @@ -431,8 +432,9 @@ struct SQLExpressionContains : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func matchedRowIds(rowIdName: String?) -> Set? { + // FIXME: this implementation ignores column qualifiers // Look for `id IN (1, 2, 3)` - guard let column = expression as? Column, + guard let column = expression as? SQLColumnExpression, let array = collection as? SQLExpressionsArray else { return nil diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index f3d8f9ade..a0c29e8a8 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -64,7 +64,7 @@ public struct PersistenceContainer { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: Column) -> DatabaseValueConvertible? { + public subscript(_ column: SQLColumnExpression) -> DatabaseValueConvertible? { get { return self[column.name] } set { self[column.name] = newValue } } @@ -362,7 +362,7 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element == Column { + public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: SQLColumnExpression { try update(db, columns: Set(columns.map { $0.name })) } diff --git a/README.md b/README.md index 9d827c72a..5614e6d7b 100644 --- a/README.md +++ b/README.md @@ -2823,19 +2823,11 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu var id: Int64? init(row: Row) { - id = row["rowid"] + id = row[Column.rowID] } } ``` - If you prefer using the Column type from the [query interface](#the-query-interface), use the `Column.rowID` constant: - - ```swift - init(row: Row) { - id = row[.rowID] - } - ``` - Your fetched records will then know their ids: ```swift @@ -2850,7 +2842,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu var id: Int64? func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["message"] = message container["date"] = date } diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index aa606459c..f440074f8 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -16,7 +16,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] @@ -28,7 +28,7 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 42d1e201a..022554d6d 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -16,7 +16,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] @@ -28,7 +28,7 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index 815fb0201..0d645db56 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -17,7 +17,7 @@ private struct Book { extension Book : FetchableRecord { init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] title = row["title"] author = row["author"] body = row["body"] @@ -29,7 +29,7 @@ extension Book : MutablePersistableRecord { static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["title"] = title container["author"] = author container["body"] = body diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 4b6f1be62..1b7f0d60e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -42,7 +42,7 @@ private class Person : Record { } required init(row: Row) { - id = row[.rowID] + id = row[Column.rowID] age = row["age"] name = row["name"] creationDate = row["creationDate"] @@ -50,7 +50,7 @@ private class Person : Record { } override func encode(to container: inout PersistenceContainer) { - container[.rowID] = id + container[Column.rowID] = id container["name"] = name container["age"] = age container["creationDate"] = creationDate From e54ccdfc5405e873d3879d1447c41099699613d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 14:56:51 +0200 Subject: [PATCH 157/348] Tests for SQLColumnExpression --- GRDB.xcodeproj/project.pbxproj | 6 + GRDBCipher.xcodeproj/project.pbxproj | 10 + GRDBCustom.xcodeproj/project.pbxproj | 6 + .../GRDBTests/SQLColumnExpressionTests.swift | 186 ++++++++++++++++++ 4 files changed, 208 insertions(+) create mode 100644 Tests/GRDBTests/SQLColumnExpressionTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 2f9e6cbb6..0c685d5d7 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -426,6 +426,8 @@ 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; + 56B6EF56208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF57208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; @@ -947,6 +949,7 @@ 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; + 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.1/Realm.framework"; sourceTree = ""; }; @@ -1270,6 +1273,7 @@ 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, + 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -2452,6 +2456,7 @@ 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, + 56B6EF57208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2598,6 +2603,7 @@ 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, + 56B6EF56208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */, 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */, 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */, diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 47e583fe3..b97c9a5bc 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -674,6 +674,10 @@ 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; + 56B6EF64208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF65208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF66208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF67208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; 56B9649E1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A11DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -1021,6 +1025,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; + 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -1317,6 +1322,7 @@ 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, + 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -2142,6 +2148,7 @@ 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */, 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, + 56B6EF64208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, @@ -2288,6 +2295,7 @@ 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 56B6EF65208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */, 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, @@ -2535,6 +2543,7 @@ 5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */, 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 56B6EF66208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, @@ -2681,6 +2690,7 @@ 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, + 56B6EF67208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index b76869c92..0f5bc591b 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -209,6 +209,8 @@ 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; + 56B6EF60208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF61208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */; }; 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -715,6 +717,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; + 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -993,6 +996,7 @@ 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, + 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -1847,6 +1851,7 @@ 5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, + 56B6EF61208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */, @@ -2094,6 +2099,7 @@ 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, + 56B6EF60208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */, 562205FD1E420EA2005860AC /* DatabasePoolBackupTests.swift in Sources */, 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, diff --git a/Tests/GRDBTests/SQLColumnExpressionTests.swift b/Tests/GRDBTests/SQLColumnExpressionTests.swift new file mode 100644 index 000000000..5442dd129 --- /dev/null +++ b/Tests/GRDBTests/SQLColumnExpressionTests.swift @@ -0,0 +1,186 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +class SQLColumnExpressionTests: GRDBTestCase { + + func testRawSQLColumnExpression() throws { + struct Player: TableRecord, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String + var score: Int + + struct Column: SQLColumnExpression { + var name: String + } + + enum Columns { + static let id = Player.Column(name: "id") + static let name = Player.Column(name: "name") + static let score = Player.Column(name: "score") + } + + static let databaseTableName = "players" + // Test databaseSelection + static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + + init(row: Row) { + // Test row subscript + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } + + func encode(to container: inout PersistenceContainer) { + // Test container subscript + container[Columns.id] = id + container[Columns.name] = name + container[Columns.score] = score + } + + static var testRequest: QueryInterfaceRequest { + // Test expression derivation + return filter(Columns.name != nil).order(Columns.score.desc) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "players") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + // Test rowId column identification + try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") + + // Test specific column updates + let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") + + // Test FTS3 match expression + let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) + var arguments: StatementArguments? = nil + XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + } + } + + func testRawRepresentableColumnExpression() throws { + struct Player: TableRecord, FetchableRecord, PersistableRecord { + var id: Int64 + var name: String + var score: Int + + enum Columns: String, SQLColumnExpression { + case id, name, score + } + + static let databaseTableName = "players" + // Test databaseSelection + static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score] + + init(row: Row) { + // Test row subscript + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } + + func encode(to container: inout PersistenceContainer) { + // Test container subscript + container[Columns.id] = id + container[Columns.name] = name + container[Columns.score] = score + } + + static var testRequest: QueryInterfaceRequest { + // Test expression derivation + return filter(Columns.name != nil).order(Columns.score.desc) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "players") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + // Test rowId column identification + try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") + + // Test specific column updates + let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + try? player.update(db, columns: [Player.Columns.name, Player.Columns.score]) + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") + + // Test FTS3 match expression + let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) + var arguments: StatementArguments? = nil + XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + } + } + + func testCodingKeyColumnExpression() throws { + struct Player: TableRecord, FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var name: String + var score: Int + + enum CodingKeys: CodingKey, SQLColumnExpression { + case id, name, score + } + + static let databaseTableName = "players" + // Test databaseSelection + static let databaseSelection: [SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score] + + static var testRequest: QueryInterfaceRequest { + // Test expression derivation + return filter(CodingKeys.name != nil).order(CodingKeys.score.desc) + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "players") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name") + t.column("score") + } + + // Test rowId column identification + try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.CodingKeys.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.CodingKeys.id).fetchedRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.CodingKeys.id == 1 || Player.CodingKeys.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.CodingKeys.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") + + // Test specific column updates + let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) + try? player.update(db, columns: [Player.CodingKeys.name, Player.CodingKeys.score]) + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") + + // Test FTS3 match expression + let expression = try Player.CodingKeys.name.match(FTS3Pattern(rawPattern: "foo")) + var arguments: StatementArguments? = nil + XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + } + } +} From f2ae44384fae94c8be9381c6d99e34d6ac23bcf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 18:13:47 +0200 Subject: [PATCH 158/348] Rename SQLColumnExpression to ColumnExpression --- GRDB.xcodeproj/project.pbxproj | 12 ++++----- GRDB/Core/Row.swift | 12 ++++----- GRDB/QueryInterface/Column.swift | 26 +++++++++++-------- .../FTS3+QueryInterfaceRequest.swift | 2 +- .../SQLExpression+QueryInterface.swift | 8 +++--- GRDB/Record/PersistableRecord.swift | 4 +-- GRDBCipher.xcodeproj/project.pbxproj | 20 +++++++------- GRDBCustom.xcodeproj/project.pbxproj | 12 ++++----- ...ests.swift => ColumnExpressionTests.swift} | 10 +++---- 9 files changed, 55 insertions(+), 51 deletions(-) rename Tests/GRDBTests/{SQLColumnExpressionTests.swift => ColumnExpressionTests.swift} (97%) diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 0c685d5d7..571eaeeb5 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -426,8 +426,8 @@ 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; - 56B6EF56208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */; }; - 56B6EF57208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; 56B7F43A1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; }; @@ -949,7 +949,7 @@ 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; - 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; + 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8C2401CA1758F00510325 /* Realm.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Realm.framework; path = "Realm/build/osx/swift-4.1/Realm.framework"; sourceTree = ""; }; @@ -1268,12 +1268,12 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56B6EF55208CB4E3002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -2456,7 +2456,7 @@ 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, - 56B6EF57208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, 56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, 56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2603,7 +2603,7 @@ 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, - 56B6EF56208CB4E3002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, 5698ACD71DA925420056AF8C /* RowTestCase.swift in Sources */, 56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */, 56741EA81E66A8B3003E422D /* FetchRequestTests.swift in Sources */, diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index ff28110e1..242637cd5 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -347,7 +347,7 @@ extension Row { /// the same name, the leftmost column is considered. /// /// The result is nil if the row does not contain the column. - public subscript(_ column: SQLColumnExpression) -> DatabaseValueConvertible? { + public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? { return self[column.name] } @@ -359,7 +359,7 @@ extension Row { /// If the column is missing or if the SQLite value is NULL, the result is /// nil. Otherwise the SQLite value is converted to the requested type /// `Value`. Should this conversion fail, a fatal error is raised. - public subscript(_ column: SQLColumnExpression) -> Value? { + public subscript(_ column: ColumnExpression) -> Value? { return self[column.name] } @@ -375,7 +375,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: SQLColumnExpression) -> Value? { + public subscript(_ column: ColumnExpression) -> Value? { return self[column.name] } @@ -388,7 +388,7 @@ extension Row { /// /// This method crashes if the fetched SQLite value is NULL, or if the /// SQLite value can not be converted to `Value`. - public subscript(_ column: SQLColumnExpression) -> Value { + public subscript(_ column: ColumnExpression) -> Value { return self[column.name] } @@ -405,7 +405,7 @@ extension Row { /// This method exists as an optimization opportunity for types that adopt /// StatementColumnConvertible. It *may* trigger SQLite built-in conversions /// (see https://www.sqlite.org/datatype3.html). - public subscript(_ column: SQLColumnExpression) -> Value { + public subscript(_ column: ColumnExpression) -> Value { return self[column.name] } @@ -453,7 +453,7 @@ extension Row { /// /// The returned data does not owns its bytes: it must not be used longer /// than the row's lifetime. - public func dataNoCopy(_ column: SQLColumnExpression) -> Data? { + public func dataNoCopy(_ column: ColumnExpression) -> Data? { return dataNoCopy(named: column.name) } } diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 56b0507bd..bdad2d1d8 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -1,9 +1,12 @@ /// The protocol for types that define database columns -public protocol SQLColumnExpression: SQLExpression { +public protocol ColumnExpression: SQLExpression { + /// The unqualified name of a database column. + /// + /// "score" is a valid unqualified name. "player.score" is not. var name: String { get } } -extension SQLColumnExpression { +extension ColumnExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func expressionSQL(_ arguments: inout StatementArguments?) -> String { @@ -20,7 +23,7 @@ extension SQLColumnExpression { /// A column in a database table /// /// See https://github.com/groue/GRDB.swift#the-query-interface -public struct Column: SQLColumnExpression { +public struct Column: ColumnExpression { /// The hidden rowID column public static let rowID = Column("rowid") @@ -34,7 +37,7 @@ public struct Column: SQLColumnExpression { } /// A qualified column in the database, as in `SELECT t.a FROM t` -struct QualifiedColumn: SQLColumnExpression { +struct QualifiedColumn: ColumnExpression { var name: String private let qualifier: SQLTableQualifier @@ -57,13 +60,14 @@ struct QualifiedColumn: SQLColumnExpression { } } -extension CodingKey where Self: SQLColumnExpression { - public var name: String { - return stringValue - } -} - -extension SQLColumnExpression where Self: RawRepresentable, Self.RawValue == String { +/// Support for column enums: +/// +/// struct Player { +/// enum Columns: ColumnExpression { +/// case id, name, score +/// } +/// } +extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String { public var name: String { return rawValue } diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 768f613f9..171b12868 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -42,7 +42,7 @@ extension TableRecord { } } -extension SQLColumnExpression { +extension ColumnExpression { /// A matching SQL expression with the `MATCH` SQL operator. /// /// // content MATCH '...' diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index b7ebe9512..a7a7f8dcc 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -289,7 +289,7 @@ public struct SQLExpressionBinary : SQLExpression { switch op { case .equal, .is: // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` - func matchedRowIds(column: SQLColumnExpression, dbValue: DatabaseValue) -> Set? { + func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set? { var rowIdNames = [Column.rowID.name.lowercased()] if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) @@ -304,9 +304,9 @@ public struct SQLExpressionBinary : SQLExpression { } } switch (lhs, rhs) { - case (let column as SQLColumnExpression, let dbValue as DatabaseValue): + case (let column as ColumnExpression, let dbValue as DatabaseValue): return matchedRowIds(column: column, dbValue: dbValue) - case (let dbValue as DatabaseValue, let column as SQLColumnExpression): + case (let dbValue as DatabaseValue, let column as ColumnExpression): return matchedRowIds(column: column, dbValue: dbValue) default: return nil @@ -434,7 +434,7 @@ struct SQLExpressionContains : SQLExpression { func matchedRowIds(rowIdName: String?) -> Set? { // FIXME: this implementation ignores column qualifiers // Look for `id IN (1, 2, 3)` - guard let column = expression as? SQLColumnExpression, + guard let column = expression as? ColumnExpression, let array = collection as? SQLExpressionsArray else { return nil diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index a0c29e8a8..389035274 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -64,7 +64,7 @@ public struct PersistenceContainer { /// It is undefined behavior to set different values for the same column. /// Column names are case insensitive, so defining both "name" and "NAME" /// is considered undefined behavior. - public subscript(_ column: SQLColumnExpression) -> DatabaseValueConvertible? { + public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? { get { return self[column.name] } set { self[column.name] = newValue } } @@ -362,7 +362,7 @@ extension MutablePersistableRecord { /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. - public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: SQLColumnExpression { + public func update(_ db: Database, columns: Sequence) throws where Sequence.Element: ColumnExpression { try update(db, columns: Set(columns.map { $0.name })) } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index b97c9a5bc..1f5d77772 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -674,10 +674,10 @@ 56B14E851D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; - 56B6EF64208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; - 56B6EF65208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; - 56B6EF66208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; - 56B6EF67208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF64208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */; }; 56B9649E1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A11DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -1025,7 +1025,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; - 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; + 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -1317,12 +1317,12 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56B6EF62208CB762002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -2148,7 +2148,7 @@ 560FC57D1CB00B880014AA8E /* RecordInitializersTests.swift in Sources */, 56176C5F1EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 565F03C31CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, - 56B6EF64208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF64208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB3F1D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 560FC57E1CB00B880014AA8E /* MutablePersistableRecordTests.swift in Sources */, 5657AB5F1D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, @@ -2295,7 +2295,7 @@ 5671563B1CB16729007DC145 /* RecordInitializersTests.swift in Sources */, 56176C651EACCCC8000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 5657AB681D108BA9006283EF /* FoundationURLTests.swift in Sources */, - 56B6EF65208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF65208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5671563C1CB16729007DC145 /* MutablePersistableRecordTests.swift in Sources */, 5671563D1CB16729007DC145 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 567E55F31D2BDDFE00CC6F79 /* EncryptionTests.swift in Sources */, @@ -2543,7 +2543,7 @@ 5657AB6B1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCA4F1CB1AA9900F48B96 /* DataMemoryTests.swift in Sources */, 56176C711EACCCCA000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, - 56B6EF66208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF66208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5672DE5D1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56AFCA501CB1AA9900F48B96 /* RecordCopyTests.swift in Sources */, 56FF45451D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, @@ -2690,7 +2690,7 @@ 56AFCAA51CB1ABC800F48B96 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56AFCAA61CB1ABC800F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, 56176C771EACCCCB000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, - 56B6EF67208CB762002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF67208CB762002F0ACB /* ColumnExpressionTests.swift in Sources */, 5657AB6C1D108BA9006283EF /* FoundationURLTests.swift in Sources */, 56AFCAA81CB1ABC800F48B96 /* DataMemoryTests.swift in Sources */, 56AFCAA91CB1ABC800F48B96 /* RecordCopyTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 0f5bc591b..ecf88c2b8 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -209,8 +209,8 @@ 56B021D01D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E821D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; - 56B6EF60208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */; }; - 56B6EF61208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */; }; + 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; + 56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */; }; 56B9649F1DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964A21DA51B4C0002DA19 /* FTS5.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B9649C1DA51B4C0002DA19 /* FTS5.swift */; }; 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; }; @@ -717,7 +717,7 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; - 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLColumnExpressionTests.swift; sourceTree = ""; }; + 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = ""; }; @@ -991,12 +991,12 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, 56300B5D1C53C38F005A543B /* QueryInterfaceRequestTests.swift */, 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */, - 56B6EF5E208CB746002F0ACB /* SQLColumnExpressionTests.swift */, 566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */, 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */, 5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */, @@ -1851,7 +1851,7 @@ 5698ACBD1DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5623931F1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 562393701DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, - 56B6EF61208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF61208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, F3BA81121CFB3059003DC1BA /* DatabaseMigratorTests.swift in Sources */, 56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */, F3BA80EB1CFB3016003DC1BA /* FetchableRecordTests.swift in Sources */, @@ -2099,7 +2099,7 @@ 5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56B964C61DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, - 56B6EF60208CB746002F0ACB /* SQLColumnExpressionTests.swift in Sources */, + 56B6EF60208CB746002F0ACB /* ColumnExpressionTests.swift in Sources */, 562205FD1E420EA2005860AC /* DatabasePoolBackupTests.swift in Sources */, 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */, diff --git a/Tests/GRDBTests/SQLColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift similarity index 97% rename from Tests/GRDBTests/SQLColumnExpressionTests.swift rename to Tests/GRDBTests/ColumnExpressionTests.swift index 5442dd129..410dc7aef 100644 --- a/Tests/GRDBTests/SQLColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -7,15 +7,15 @@ import XCTest import GRDB #endif -class SQLColumnExpressionTests: GRDBTestCase { +class ColumnExpressionTests: GRDBTestCase { - func testRawSQLColumnExpression() throws { + func testRawColumnExpression() throws { struct Player: TableRecord, FetchableRecord, PersistableRecord { var id: Int64 var name: String var score: Int - struct Column: SQLColumnExpression { + struct Column: ColumnExpression { var name: String } @@ -82,7 +82,7 @@ class SQLColumnExpressionTests: GRDBTestCase { var name: String var score: Int - enum Columns: String, SQLColumnExpression { + enum Columns: String, ColumnExpression { case id, name, score } @@ -143,7 +143,7 @@ class SQLColumnExpressionTests: GRDBTestCase { var name: String var score: Int - enum CodingKeys: CodingKey, SQLColumnExpression { + enum CodingKeys: CodingKey, ColumnExpression { case id, name, score } From d6f93afffe0e4fae65869f6dad71e6d1cfde2cbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 22 Apr 2018 19:10:10 +0200 Subject: [PATCH 159/348] Update documentation in order to foster column enums --- README.md | 63 ++++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 5614e6d7b..105bca737 100644 --- a/README.md +++ b/README.md @@ -2177,15 +2177,12 @@ extension Place : FetchableRecord { } ``` -Rows also accept keys of type `Column`: +Rows also accept columns: ```swift extension Place : FetchableRecord { - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let latitude = Column("latitude") - static let longitude = Column("longitude") + enum Columns: String, ColumnExpression { + case id, title, latitude, longitude } init(row: Row) { @@ -2335,15 +2332,12 @@ try paris.insert(db) paris.id // some value ``` -Persistence containers also accept keys of type `Column`: +Persistence containers also accept columns: ```swift extension Place : MutablePersistableRecord { - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let latitude = Column("latitude") - static let longitude = Column("longitude") + enum Columns: String, ColumnExpression { + case id, title, latitude, longitude } func encode(to container: inout PersistenceContainer) { @@ -2562,20 +2556,16 @@ class Place: Record { super.init() } - /// The table columns - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let favorite = Column("favorite") - static let latitude = Column("latitude") - static let longitude = Column("longitude") - } - /// The table name override class var databaseTableName: String { return "places" } + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + /// Creates a record from a database row required init(row: Row) { id = row[Columns.id] @@ -2942,12 +2932,8 @@ Each one of the three examples below is correct. You will pick one or the other static let databaseTableName = "places" /// The table columns - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let favorite = Column("favorite") - static let latitude = Column("latitude") - static let longitude = Column("longitude") + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude } } @@ -2997,20 +2983,16 @@ Each one of the three examples below is correct. You will pick one or the other super.init() } - /// The table columns - enum Columns { - static let id = Column("id") - static let title = Column("title") - static let favorite = Column("favorite") - static let latitude = Column("latitude") - static let longitude = Column("longitude") - } - /// The table name override class var databaseTableName: String { return "places" } + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + /// Creates a record from a database row required init(row: Row) { id = row[Columns.id] @@ -3381,6 +3363,15 @@ let idColumn = Column("id") let nameColumn = Column("name") ``` +You can also declare column enums, if you prefer: + +```swift +enum Columns: String, ColumnExpression { + case id + case name +} +``` + You can now build requests with the following methods: `all`, `none`, `select`, `distinct`, `filter`, `matching`, `group`, `having`, `order`, `reversed`, `limit`. All those methods return another request, which you can further refine by applying another method: `Player.select(...).filter(...).order(...)`. - `all()`, `none()`: the requests for all rows, or no row. From 5ee390f0daeb6615672219d88246ffbfabbcec46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 23 Apr 2018 08:19:15 +0200 Subject: [PATCH 160/348] No more support for CodingKey & ColumnExpression --- Tests/GRDBTests/ColumnExpressionTests.swift | 47 --------------------- 1 file changed, 47 deletions(-) diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index 410dc7aef..5c6625171 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -136,51 +136,4 @@ class ColumnExpressionTests: GRDBTestCase { XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") } } - - func testCodingKeyColumnExpression() throws { - struct Player: TableRecord, FetchableRecord, PersistableRecord, Codable { - var id: Int64 - var name: String - var score: Int - - enum CodingKeys: CodingKey, ColumnExpression { - case id, name, score - } - - static let databaseTableName = "players" - // Test databaseSelection - static let databaseSelection: [SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score] - - static var testRequest: QueryInterfaceRequest { - // Test expression derivation - return filter(CodingKeys.name != nil).order(CodingKeys.score.desc) - } - } - - let dbQueue = try makeDatabaseQueue() - try dbQueue.inDatabase { db in - try db.create(table: "players") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name") - t.column("score") - } - - // Test rowId column identification - try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.CodingKeys.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.CodingKeys.id).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.CodingKeys.id == 1 || Player.CodingKeys.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.CodingKeys.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") - - // Test specific column updates - let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) - try? player.update(db, columns: [Player.CodingKeys.name, Player.CodingKeys.score]) - XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") - - // Test FTS3 match expression - let expression = try Player.CodingKeys.name.match(FTS3Pattern(rawPattern: "foo")) - var arguments: StatementArguments? = nil - XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") - } - } } From 4409b07ef5db6d3fc513fa7415ec007f484d4678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 23 Apr 2018 08:39:19 +0200 Subject: [PATCH 161/348] ColumnExpression documentation --- GRDB/QueryInterface/Column.swift | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index bdad2d1d8..cd6ecb5c0 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -1,4 +1,23 @@ -/// The protocol for types that define database columns +/// Adopt the ColumnExpression protocol in order to define a custom column type. +/// +/// You can, for example, define a String-based column enum: +/// +/// enum Columns: String, ColumnExpression { +/// case id, name, score +/// } +/// let nameColumn = Columns.name +/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +/// +/// You can also define a genuine column type: +/// +/// struct MyColumn: ColumnExpression { +/// var name: String +/// var sqlType: String +/// } +/// let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR") +/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +/// +/// See https://github.com/groue/GRDB.swift#the-query-interface public protocol ColumnExpression: SQLExpression { /// The unqualified name of a database column. /// @@ -20,7 +39,10 @@ extension ColumnExpression { } } -/// A column in a database table +/// A column in a database table. +/// +/// When you need to introduce your own column type, don't wrap a Column. +/// Instead, adopt the ColumnExpression protocol. /// /// See https://github.com/groue/GRDB.swift#the-query-interface public struct Column: ColumnExpression { From 5fe609ae5c4a9cee127571c13dc290ac7060349c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 24 Apr 2018 09:32:07 +0200 Subject: [PATCH 162/348] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 3baced84d..22dea21ce 100644 --- a/TODO.md +++ b/TODO.md @@ -26,6 +26,7 @@ GRDB 3.0 - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite - sync - ? +- [ ] Since associations prefer singular table names, provide a default implementation for TableRecord.databaseTableName Not sure From e5c4409ad463a8abfc59702b97678df5b138ea58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 08:57:44 +0200 Subject: [PATCH 163/348] Enhance documentation --- README.md | 182 ++++++++++++++++++++++++++++++++---------------------- 1 file changed, 107 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 105bca737..eda94cb48 100644 --- a/README.md +++ b/README.md @@ -366,7 +366,7 @@ See [DemoApps/GRDBDemoiOS/AppDatabase.swift](DemoApps/GRDBDemoiOS/GRDBDemoiOS/Ap > :muscle: **Note to database experts**: The `write` and `read` database access methods generally help enforcing the [GRDB concurrency guarantees](#concurrency), and are highly recommended, even for skilled developers, because they lift most of the mental burden related to explicit SQLite transactions: > -> - `DatabaseQueue.write` wraps your database statements in a transaction. On the first unhandled error, the whole transaction is rollbacked, and the error rethrown. +> - `DatabaseQueue.write` wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, the whole transaction is rollbacked, and the error is rethrown. > - `DatabaseQueue.read` does not open any transaction, but enforces read-only access. > > When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints). @@ -447,13 +447,13 @@ Unlike [database queues](#database-queues), pools allow several threads to acces - Unlike reads, writes are serialized. There is never more than a single thread that is writing into the database. -- The `write` method wraps your database statements in a transaction. On the first unhandled error, the whole transaction is rollbacked, and the error rethrown. +- The `write` method wraps your database statements in a transaction that commits if and only if no error occurs. On the first unhandled error, the whole transaction is rollbacked, and the error is rethrown. When precise transaction handling is required, see [Transactions and Savepoints](#transactions-and-savepoints) for more information. - Database pools can take [snapshots](#database-snapshots) of the database. -See the [Concurrency](#concurrency) chapter for more details about database pools, and advanced use cases. +See the [Concurrency](#concurrency) chapter for more details about database pools, how they differ from database queues, and advanced use cases. ### DatabasePool Configuration @@ -659,9 +659,11 @@ Both arrays and cursors can iterate over database results. How do you choose one ```swift // Wrong let cursor = try dbQueue.read { try Player.fetchCursor($0, ...) } + while let player = try players.next() { ... } // OK let array = try dbQueue.read { try Player.fetchAll($0, ...) } + for player in players { // use player } ``` - **Cursors can be iterated only one time.** Arrays can be iterated many times. @@ -1287,17 +1289,21 @@ GRDB generally opens transactions for you, as a way to enforce its [concurrency ```swift // BEGIN TRANSACTION -// INSERT INTO players ... +// INSERT INTO credits ... +// INSERT INTO debits ... // COMMIT try dbQueue.write { db in - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) } // BEGIN TRANSACTION -// INSERT INTO players ... +// INSERT INTO credits ... +// INSERT INTO debits ... // COMMIT try dbPool.write { db in - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) } ``` @@ -1309,46 +1315,56 @@ Yet you may need to exactly control when transactions take place: `DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: ```swift -// INSERT INTO players (...) +// INSERT INTO credits ... +// INSERT INTO debits ... try dbQueue.inDatabase { db in - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) } -// INSERT INTO players (...) +// INSERT INTO credits ... +// INSERT INTO debits ... try dbPool.writeWithoutTransaction { db in - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) } ``` -> :warning: **Warning**: it is dangerous to write in a database pool outside of a transaction, because concurrent reads may see an inconsistent state of the database: -> -> ```swift -> // UNSAFE CONCURRENCY -> try dbPool.writeWithoutTransaction { db in -> try Credit(destinationAccout, amount).insert(db) -> // <- Concurrent dbPool.read sees a partial db update here -> try Debit(sourceAccount, amount).insert(db) -> } -> ``` +**Writing outside of any transaction can be dangerous.** In our credit/debit example, you may successfully insert a credit, but fail inserting the debit, and end up with unbalanced accounts (oops). + +Furthermore, outside of any transaction, database pool concurrent reads may see an inconsistent state of the database: + +```swift +// UNSAFE CONCURRENCY +try dbPool.writeWithoutTransaction { db in + try Credit(destinationAccout, amount).insert(db) + // <- Concurrent dbPool.read sees a partial db update here + try Debit(sourceAccount, amount).insert(db) +} +``` To open explicit transactions, use one of the `Database.inTransaction`, `DatabaseQueue.inTransaction`, or `DatabasePool.writeInTransaction` methods: ```swift // BEGIN TRANSACTION -// INSERT INTO players ... +// INSERT INTO credits ... +// INSERT INTO debits ... // COMMIT try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.inTransaction { - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) return .commit } } // BEGIN TRANSACTION -// INSERT INTO players (...) +// INSERT INTO credits ... +// INSERT INTO debits ... // COMMIT try dbQueue.inTransaction { db in // or dbPool.writeInTransaction - try Player(...).insert(db) + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) return .commit } ``` @@ -1365,7 +1381,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.execute("BEGIN TRANSACTION") ... - try db.execute("COMMIT") + try db.execute("ROLLBACK") } ``` @@ -1406,9 +1422,10 @@ func myCriticalMethod(_ db: Database) throws { ```swift try dbQueue.write { db in - try db.inSavepoint { - try db.execute("DELETE ...") - try db.execute("INSERT ...") // need to rollback the delete above if this fails + // Makes sure both inserts succeed, or none: + try db.inSavepoint { + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) return .commit } @@ -1714,38 +1731,34 @@ Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ## Database Schema Introspection -**SQLite provides database schema introspection tools**, such as the [sqlite_master](https://www.sqlite.org/faq.html#q7) table, and the pragma [table_info](https://www.sqlite.org/pragma.html#pragma_table_info): +GRDB comes with a set of schema introspection methods: ```swift -try db.create(table: "players") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text) +try dbQueue.read { db in + // Bool, true if the table exists + try db.tableExists("players") + + // [ColumnInfo], the columns in the table + try db.columns(in: "players") + + // PrimaryKeyInfo + try db.primaryKey("players") + + // [ForeignKeyInfo], the foreign keys defined on the table + try db.foreignKeys(on: "players") + + // [IndexInfo], the indexes defined on the table + try db.indexes(on: "players") + + // Bool, true if column(s) is a unique key + try db.table("players", hasUniqueKey: ["email"]) } -// [type:"table" name:"players" tbl_name:"players" rootpage:2 -// sql:"CREATE TABLE players(id INTEGER PRIMARY KEY, name TEXT)"] -for row in try Row.fetchAll(db, "SELECT * FROM sqlite_master") { - print(row) -} +// Bool, true if argument is the name of an internal SQLite table +Database.isSQLiteInternalTable(...) -// [cid:0 name:"id" type:"INTEGER" notnull:0 dflt_value:NULL pk:1] -// [cid:1 name:"name" type:"TEXT" notnull:0 dflt_value:NULL pk:0] -for row in try Row.fetchAll(db, "PRAGMA table_info('players')") { - print(row) -} -``` - -GRDB provides high-level methods as well: - -```swift -try db.tableExists("players") // Bool, true if the table exists -try db.columns(in: "players") // [ColumnInfo], the columns in the table -try db.indexes(on: "players") // [IndexInfo], the indexes defined on the table -try db.foreignKeys(on: "players") // [ForeignKeyInfo], the foreign keys defined on the table -try db.primaryKey("players") // PrimaryKeyInfo -try db.table("players", hasUniqueKey: ["email"]) // Bool, true if column(s) is a unique key -Database.isSQLiteInternalTable(...) // Bool, true if argument is the name of an internal SQLite table -Database.isGRDBInternalTable(...) // Bool, true if argument is the name of an internal GRDB table +// Bool, true if argument is the name of an internal GRDB table +Database.isGRDBInternalTable(...) ``` @@ -1824,7 +1837,7 @@ let adapter = ScopeAdapter([ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c, 3 AS d", adapter: adapter)! ``` -ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access with `Row.scopes[]`. This subscript returns an optional Row, which is nil if the scope is missing. +ScopeAdapter does not change the columns and values of the fetched row. Instead, it defines *scopes*, which you access through the `Row.scopes` property: ```swift row // [a:0 b:1 c:2 d:3] @@ -1953,7 +1966,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Deleting Records](#deleting-records) - [Counting Records](#counting-records) -**Protocols and the Record class** +**Protocols and the Record Class** - [Record Protocols Overview](#record-protocols-overview) - [FetchableRecord Protocol](#fetchablerecord-protocol) @@ -1967,7 +1980,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) -**Records in a glance** +**Records in a Glance** - [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) @@ -2086,7 +2099,7 @@ Details follow: - [FetchableRecord] is able to **decode database rows**. - You can always decode rows yourself: + It is always possible to decode rows without this protocol: ```swift struct Place { ... } @@ -2104,7 +2117,7 @@ Details follow: } ``` - But FetchableRecord lets you write code that is much more readable, and much more efficient as well, both in terms of performance and memory usage: + But FetchableRecord lets you write code that is easier to read, and more efficient as well, both in terms of performance and memory usage: ```swift struct Place: FetchableRecord { ... } @@ -2682,7 +2695,7 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab ```swift // CREATE TABLE players ( - // id INTEGER PRIMARY KEY, + // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE ON CONFLICT REPLACE // ) try db.create(table: "players") { t in @@ -2700,12 +2713,12 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab ```swift // CREATE TABLE players ( - // id INTEGER PRIMARY KEY, + // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE // ) try db.create(table: "players") { t in t.autoIncrementedPrimaryKey("id") - t.column("email", .text) + t.column("email", .text).unique() } // Again, despite the unique index on email, both inserts succeed. @@ -2879,7 +2892,7 @@ try dbQueue.write { db in Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application: -- Example 1: Define a Codable struct and adopt each one of the [record protocols](#record-protocols-overview). +- **Example 1**: Define a Codable struct and adopt each one of the [record protocols](#record-protocols-overview). ```swift struct Place: Codable { @@ -2917,7 +2930,7 @@ Each one of the three examples below is correct. You will pick one or the other } ``` -- Example 2: Define a plain struct and explicitely adopt each one of the [record protocols](#record-protocols-overview). +- **Example 2**: Define a plain struct and explicitely adopt each one of the [record protocols](#record-protocols-overview). ```swift struct Place { @@ -2966,7 +2979,7 @@ Each one of the three examples below is correct. You will pick one or the other } ``` -- Example 3: Subclass the [Record class](#record-class). +- **Example 3**: Subclass the [Record class](#record-class). ```swift class Place: Record { @@ -3184,7 +3197,7 @@ Once granted with a [database connection](#database-connections), you can setup ```swift // CREATE TABLE places ( -// id INTEGER PRIMARY KEY, +// id INTEGER PRIMARY KEY AUTOINCREMENT, // title TEXT, // favorite BOOLEAN NOT NULL DEFAULT 0, // latitude DOUBLE NOT NULL, @@ -3366,6 +3379,8 @@ let nameColumn = Column("name") You can also declare column enums, if you prefer: ```swift +// Columns.id and Columns.name can be used just as +// idColumn and nameColumn declared above. enum Columns: String, ColumnExpression { case id case name @@ -5454,7 +5469,7 @@ By default, database holds weak references to its transaction observers: they ar > :point_up: **Note**: the changes that are not notified are changes to internal system tables (such as `sqlite_master`), changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables, and the deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite). -Notified changes are not actually written to disk the [transaction](#transactions-and-savepoints) commits, and the until `databaseDidCommit` is called. On the other side, `databaseDidRollback` confirms their invalidation: +Notified changes are not actually written to disk until the [transaction](#transactions-and-savepoints) commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation: ```swift try dbQueue.write { db in @@ -5470,11 +5485,11 @@ try dbQueue.inTransaction { db in try dbQueue.write { db in try db.execute("INSERT ...") // 1. didChange - throw SomeError() // 2. throw -} // 3. didRollback + throw SomeError() +} // 2. didRollback ``` -Database statements that are executed outside of a transaction do not drop off the radar: +Database statements that are executed outside of any transaction do not drop off the radar: ```swift try dbQueue.inDatabase { db in @@ -6113,6 +6128,7 @@ Here is an example of code that is vulnerable to SQL injection: ```swift // BAD BAD BAD +let id = 1 let name = textField.text try dbQueue.write { db in try db.execute("UPDATE students SET name = '\(name)' WHERE id = \(id)") @@ -6127,19 +6143,35 @@ DROP TABLE students; --' WHERE id = 1 ``` -To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) to your SQL queries: +To avoid those problems, **never embed raw values in your SQL queries**. The only correct technique is to provide [arguments](#executing-updates) to your raw SQL queries: ```swift -// Good let name = textField.text try dbQueue.write { db in + // Good try db.execute( "UPDATE students SET name = ? WHERE id = ?", arguments: [name, id]) + + // Just as good + try db.execute( + "UPDATE students SET name = :name WHERE id = :id", + arguments: ["name": name, "id": id]) } ``` -See [Executing Updates](#executing-updates) for more information on statement arguments. +When you use [records](#records) and the [query interface](#the-query-interface), GRDB always prevents SQL injection for you: + +```swift +let id = 1 +let name = textField.text +try dbQueue.write { db in + if var student = try Student.fetchOne(db, key: id) { + student.name = name + try student.update(db) + } +} +``` ## Error Handling From 543c361f87238702b2c8744005112b943f85265c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 09:06:29 +0200 Subject: [PATCH 164/348] Enhance documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eda94cb48..145531e45 100644 --- a/README.md +++ b/README.md @@ -3583,7 +3583,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions From c4bb84a88f0fa84a28f4c67a56763ada3235d0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 09:10:03 +0200 Subject: [PATCH 165/348] Fix outdated documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 145531e45..1f7d7991c 100644 --- a/README.md +++ b/README.md @@ -7231,7 +7231,7 @@ Database accesses that run in background threads postpone the closing of connect When you want to debug a request that does not deliver the expected results, you may want to print the SQL that is actually executed. -Use the `asSQLRequest` method: +You can turn your request into a `SQLRequest` instance: ```swift try dbQueue.read { db in @@ -7239,7 +7239,7 @@ try dbQueue.read { db in .filter(Column("origin") == "Burgundy") .order(Column("price") - let sqlRequest = try request.asSQLRequest(db) + let sqlRequest = try SQLRequest(db, request: request) print(sqlRequest.sql) // Prints SELECT * FROM wines WHERE origin = ? ORDER BY price print(sqlRequest.arguments) From 4754a9dbe034ddf4a2995c3cafa4efe90c405f77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 09:12:43 +0200 Subject: [PATCH 166/348] Minor --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1f7d7991c..b5da12fb4 100644 --- a/README.md +++ b/README.md @@ -7251,7 +7251,7 @@ Another option is to setup a tracing function that will print out all SQL reques ```swift var config = Configuration() -config.trace = { print("SQL: \($0)") } // Prints all SQL statements +config.trace = { print($0) } // Prints all SQL statements let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) try dbQueue.read { db in From bc57d67a91ea4849b412c4c5427c740d7a6e2ff4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 10:49:35 +0200 Subject: [PATCH 167/348] Rewrite usage section with details HTML tags --- README.md | 74 ++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index b5da12fb4..ce0c83afa 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,8 @@ More than a set of tools that leverage SQLite abilities, GRDB is also: ## Usage -Open a [connection](#database-connections) to the database: +
+ Connect to an SQLite database ```swift import GRDB @@ -84,8 +85,13 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") // Enhanced multithreading based on SQLite's WAL mode let dbPool = try DatabasePool(path: "/path/to/database.sqlite") ``` + +See [Database Connections](#database-connections). -[Execute SQL statements](#executing-updates): +
+ +
+ Execute SQL statements ```swift try dbQueue.write { db in @@ -107,10 +113,16 @@ try dbQueue.write { db in } ``` -[Fetch database rows and values](#fetch-queries): +See [Executing Updates](#executing-updates). + +
+ +
+ Fetch database rows and values ```swift try dbQueue.read { db in + // Fetch database rows let rows = try Row.fetchCursor(db, "SELECT * FROM places") while let row = try rows.next() { let title: String = row["title"] @@ -119,18 +131,23 @@ try dbQueue.read { db in latitude: row["latitude"], longitude: row["longitude"]) } - + + // Fetch values let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! // Int let placeTitles = try String.fetchAll(db, "SELECT title FROM places") // [String] } -// Extraction let placeCount = try dbQueue.read { db in try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! } ``` -Insert and fetch [records](#records): +See [Fetch Queries](#fetch-queries) + +
+ +
+ Store custom models aka "records" ```swift struct Place { @@ -144,6 +161,15 @@ struct Place { // provide fetching and persistence methods. try dbQueue.write { db in + // Create database table + try db.create(table: "places") { t in + t.column("id", .integer).primaryKey() + t.column("title", .text).notNull() + t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() + } + var berlin = Place( id: nil, title: "Berlin", @@ -155,40 +181,42 @@ try dbQueue.write { db in berlin.isFavorite = true try berlin.update(db) - - // Fetch [Place] from SQL - let places = try Place.fetchAll(db, "SELECT * FROM places") } ``` -Avoid SQL with the [query interface](#the-query-interface): +See [Records](#records). + +
+ +
+ Fetch records and values with the Swift query interface ```swift try dbQueue.write { db in - try db.create(table: "places") { t in - t.autoIncrementedPrimaryKey("id") - t.column("title", .text).notNull() - t.column("favorite", .boolean).notNull().defaults(to: false) - t.column("longitude", .double).notNull() - t.column("latitude", .double).notNull() - } - // Place? let paris = try Place.fetchOne(db, key: 1) // Place? - let titleColumn = Column("title") - let berlin = try Place.filter(titleColumn == "Berlin").fetchOne(db) + let berlin = try Place.filter(Column("title") == "Berlin").fetchOne(db) // [Place] - let favoriteColumn = Column("favorite") let favoritePlaces = try Place - .filter(favoriteColumn) - .order(titleColumn) + .filter(Column("favorite")) + .order(Column("title")) .fetchAll(db) + + // Int + let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) + + // SQL is always welcome + let places = try Place.fetchAll(db, "SELECT * FROM pointOfInterests") } ``` +See the [Query Interface](#the-query-interface). + +
+ Documentation ============= From 727491ca1a8b1e7f13499558d06fbdc4ba02371e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 10:57:42 +0200 Subject: [PATCH 168/348] New usage section: database observation --- README.md | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ce0c83afa..682d40574 100644 --- a/README.md +++ b/README.md @@ -201,7 +201,7 @@ try dbQueue.write { db in // [Place] let favoritePlaces = try Place - .filter(Column("favorite")) + .filter(Column("favorite") == true) .order(Column("title")) .fetchAll(db) @@ -217,6 +217,31 @@ See the [Query Interface](#the-query-interface). +
+ Be notified of database changes + +```swift +// Track query interface requests +Place.filter(key: 1) + .rx + .fetchOne(in: dbQueue) + .subscribe(onNext: { place: Place? in + print("Place 1 has changed") + }) + +// Track SQL requests +SQLRequest("SELECT * FROM places WHERE favorite ORDER BY title") + .rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { places: [Place] in + print("Favorite places have changed") + }) +``` + +See the [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). + +
+ Documentation ============= From 56d06d0889c9cdb1333ef44462838a8cfe8fe55e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 10:59:07 +0200 Subject: [PATCH 169/348] Honor #337 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 682d40574..671caafb4 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ struct Place { try dbQueue.write { db in // Create database table try db.create(table: "places") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) t.column("longitude", .double).notNull() @@ -4320,7 +4320,7 @@ Yet any kind of schema change is still possible. The SQLite documentation explai // Add a NOT NULL constraint on players.name: migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in try db.create(table: "new_players") { t in - t.column("id", .integer).primaryKey() + t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() } try db.execute("INSERT INTO new_players SELECT * FROM players") From 319baad70c0ecd7979ad1fd6eba554d45284ca8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 11:00:26 +0200 Subject: [PATCH 170/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 671caafb4..e6c7d7bee 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ try dbQueue.write { db in let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) // SQL is always welcome - let places = try Place.fetchAll(db, "SELECT * FROM pointOfInterests") + let places = try Place.fetchAll(db, "SELECT * FROM places") } ``` From 433f4e828f1791e1f7ac40512dd64954a3e0c9d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 11:06:19 +0200 Subject: [PATCH 171/348] TODO --- TODO.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index 22dea21ce..8b84dcdc9 100644 --- a/TODO.md +++ b/TODO.md @@ -26,7 +26,7 @@ GRDB 3.0 - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite - sync - ? -- [ ] Since associations prefer singular table names, provide a default implementation for TableRecord.databaseTableName +- [ ] filter(rowid:), filter(rowids:) Not sure From 7032bb64160c8da0048e0fa92390f1ef97cd81a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 11:28:43 +0200 Subject: [PATCH 172/348] Typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e6c7d7bee..bca4bbb53 100644 --- a/README.md +++ b/README.md @@ -409,7 +409,7 @@ let placeCount = try dbQueue.read { db in let newPlaceCount = try dbQueue.write { db -> Int in try Place(...).insert(db) - returns try Place.fetchCount(db) + return try Place.fetchCount(db) } ``` @@ -479,7 +479,7 @@ let placeCount = try dbPool.read { db in let newPlaceCount = try dbPool.write { db -> Int in try Place(...).insert(db) - returns try Place.fetchCount(db) + return try Place.fetchCount(db) } ``` From d09afc8929ae257382641ca35ab2112bf28a4f8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 25 Apr 2018 19:35:03 +0200 Subject: [PATCH 173/348] explicitely -> explicitly --- GRDB/QueryInterface/TableDefinition.swift | 2 +- README.md | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index d9168e733..1602b707e 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -255,7 +255,7 @@ public final class TableDefinition { /// } /// /// The auto-incremented primary key is an integer primary key that - /// automatically generates unused values when you do not explicitely + /// automatically generates unused values when you do not explicitly /// provide one, and prevents the reuse of ids over the lifetime of /// the database. /// diff --git a/README.md b/README.md index b9ef6cf7b..c25ec91b1 100644 --- a/README.md +++ b/README.md @@ -2291,7 +2291,7 @@ protocol TableRecord { The `databaseTableName` type property is the name of a database table. `databaseSelection` is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. -**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitely. For example: +**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. For example: ```swift extension Place : TableRecord { @@ -2983,7 +2983,7 @@ Each one of the three examples below is correct. You will pick one or the other } ``` -- **Example 2**: Define a plain struct and explicitely adopt each one of the [record protocols](#record-protocols-overview). +- **Example 2**: Define a plain struct and explicitly adopt each one of the [record protocols](#record-protocols-overview). ```swift struct Place { @@ -3636,7 +3636,7 @@ let request = RestrictedPlayer.all() let request = ExtendedPlayer.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitly declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky `SELECT *` requests. To verify your setup, see the [How do I print a request as SQL?](#how-do-i-print-a-request-as-sql) FAQ. ## Expressions @@ -5653,7 +5653,7 @@ class PureTransactionObserver: TransactionObserver { **You can specify how long an observer is notified of database changes and transactions.** -The `remove(transactionObserver:)` method explicitely stops notifications, at any time: +The `remove(transactionObserver:)` method explicitly stops notifications, at any time: ```swift // From a database queue or pool: @@ -6571,7 +6571,7 @@ Data protection can be enabled [globally](https://developer.apple.com/library/co You can also explicitly protect a database, by configuring its enclosing *directory*. This will not only protect the database file, but also all [temporary files](https://www.sqlite.org/tempfiles.html) created by SQLite (including the persistent `.shm` and `.wal` files created by [database pools](#database-pools)). -For example, to explicitely use [complete](https://developer.apple.com/reference/foundation/fileprotectiontype/1616200-complete) protection: +For example, to explicitly use [complete](https://developer.apple.com/reference/foundation/fileprotectiontype/1616200-complete) protection: ```swift // Paths From 66bd7cff779d1ca800669770cb6a64696fe2e1b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 06:40:26 +0200 Subject: [PATCH 174/348] Typo --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c25ec91b1..1f5d2dc8f 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,7 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") let dbPool = try DatabasePool(path: "/path/to/database.sqlite") ``` -See [Database Connections](#database-connections). +See [Database Connections](#database-connections) @@ -113,7 +113,7 @@ try dbQueue.write { db in } ``` -See [Executing Updates](#executing-updates). +See [Executing Updates](#executing-updates) @@ -184,7 +184,7 @@ try dbQueue.write { db in } ``` -See [Records](#records). +See [Records](#records) @@ -213,7 +213,7 @@ try dbQueue.write { db in } ``` -See the [Query Interface](#the-query-interface). +See the [Query Interface](#the-query-interface) @@ -238,7 +238,7 @@ SQLRequest("SELECT * FROM places WHERE favorite ORDER BY title") }) ``` -See the [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). +See [Database Changes Observation](#database-changes-observation), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) From 25748566eaa180156c87d4a054d0ddd9ce437b33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 07:14:57 +0200 Subject: [PATCH 175/348] No more obsolete string.characters in documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1f5d2dc8f..9bc533acc 100644 --- a/README.md +++ b/README.md @@ -1648,7 +1648,7 @@ let reverse = DatabaseFunction("reverse", argumentCount: 1, pure: true) { (value return nil } // ... and return reversed string: - return String(string.characters.reversed()) + return String(string.reversed()) } dbQueue.add(function: reverse) // Or dbPool.add(function: ...) @@ -1742,7 +1742,7 @@ struct MaxLength : DatabaseAggregate { return } // ... and update the result - let length = string.characters.count + let length = string.count if length > maxLength { maxLength = length } From 58edfcbc999729430f05cb9a7257bcc8fbea0d43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 07:18:02 +0200 Subject: [PATCH 176/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9bc533acc..ae68546bb 100644 --- a/README.md +++ b/README.md @@ -1868,7 +1868,7 @@ let row = try Row.fetchOne(db, "SELECT 0 AS a, 1 AS b, 2 AS c", adapter: adapter ### EmptyRowAdapter -`EmptyRowAdapter` hides all rows. +`EmptyRowAdapter` hides all columns. ```swift let adapter = EmptyRowAdapter() From af8801c28a788903cb4ae55420d52c380950c955 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 07:45:16 +0200 Subject: [PATCH 177/348] TODO --- TODO.md | 1 + 1 file changed, 1 insertion(+) diff --git a/TODO.md b/TODO.md index 8b84dcdc9..6200b7834 100644 --- a/TODO.md +++ b/TODO.md @@ -27,6 +27,7 @@ GRDB 3.0 - sync - ? - [ ] filter(rowid:), filter(rowids:) +- [ ] If required by associations, make reversed() make nothing when there is no alraedy applied ordering Not sure From 8d84050f77b223a0475176f9aeaf754c6f18285b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 07:58:06 +0200 Subject: [PATCH 178/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae68546bb..9c091f501 100644 --- a/README.md +++ b/README.md @@ -4303,7 +4303,7 @@ try migrator.migrate(dbQueue, upTo: "v1") Check if a migration has been applied: ```swift -let appliedMigrations = try migrator.appliedMigration(in: dbQueue) +let appliedMigrations = try migrator.appliedMigrations(in: dbQueue) if appliedMigrations.contains("v2") { // "v2" migration has been applied } From 6dea09ec24a96dbe2a418b4fa8b7474e57b069e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 08:05:57 +0200 Subject: [PATCH 179/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c091f501..5276d40da 100644 --- a/README.md +++ b/README.md @@ -5240,7 +5240,7 @@ let playerInfos = try dbQueue.read { db in The `PlayerInfo.fetchAll` method [above](#splitting-rows-the-record-way) directly fetches records. It's all good, but in order to profit from [database observation](#database-changes-observation) with [FetchedRecordsController](#fetchedrecordscontroller) or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB), you'll need a [custom request](#custom-requests) that defines a database query. -It is recommended that your read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above: +It is recommended that you read the previous paragraphs before you dive in this sample code. We start with the same PlayerInfo record as above: ```swift struct PlayerInfo { From 40cfbd8c9cf266497dd7c23a68b9f7fc5f91ae10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 08:26:39 +0200 Subject: [PATCH 180/348] Update Documentation for the implicit transactions opened by the `write` method --- README.md | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5276d40da..46f097d30 100644 --- a/README.md +++ b/README.md @@ -5406,18 +5406,17 @@ Database observation requires that a single [database queue](#database-queues) o ### After Commit Hook -**When your application needs to make sure a database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method.** +When your application needs to make sure a specific database transaction has been successfully committed before it executes some work, use the `Database.afterNextTransactionCommit(_:)` method. Its closure argument is called right after database changes have been successfully written to disk: ```swift -dbQueue.inTransaction { db in +dbQueue.write { db in db.afterNextTransactionCommit { db in print("success") } ... - return .commit // prints "success" -} +} // prints "success" ``` The closure runs in a protected dispatch queue, serialized with all database updates. @@ -5453,15 +5452,13 @@ func startMonitoring(_ db: Database, region: CLRegion) throws { The method above won't trigger the location manager if the transaction is eventually rollbacked (explicitly, or because of an error), as in the sample code below: ```swift -try dbQueue.inTransaction { db in +try dbQueue.write { db in // success try startMonitoring(db, region) // On error, the transaction is rollbacked, the region is not inserted, and // the location manager is not invoked. try failableMethod(db) - - return .commit } ``` From d8860d2527b9e009e795dd9b3ea3b7b700ddca37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 08:27:37 +0200 Subject: [PATCH 181/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 46f097d30..a9bf2a5bc 100644 --- a/README.md +++ b/README.md @@ -5411,7 +5411,7 @@ When your application needs to make sure a specific database transaction has bee Its closure argument is called right after database changes have been successfully written to disk: ```swift -dbQueue.write { db in +try dbQueue.write { db in db.afterNextTransactionCommit { db in print("success") } From 2ae93a2a0b23a40c24e37d95530adcb0c74b077f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 09:01:33 +0200 Subject: [PATCH 182/348] Honor #337 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a9bf2a5bc..b9e9d38c0 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ See [Database Connections](#database-connections) try dbQueue.write { db in try db.execute(""" CREATE TABLE places ( - id INTEGER PRIMARY KEY, + id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, favorite BOOLEAN NOT NULL DEFAULT 0, latitude DOUBLE NOT NULL, @@ -566,7 +566,7 @@ For example: try dbQueue.write { db in try db.execute(""" CREATE TABLE players ( - id INTEGER PRIMARY KEY, + id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score INT) """) From 26108badd47a729beab3388e862cfc7c9dd63e7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 12:51:29 +0200 Subject: [PATCH 183/348] request.reversed() has no effect when request is not already ordered --- GRDB/QueryInterface/QueryInterfaceQuery.swift | 70 ++++++++++--------- .../QueryInterfaceRequest.swift | 5 +- 2 files changed, 38 insertions(+), 37 deletions(-) diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 40319ee3b..2c3cfbec4 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -22,8 +22,7 @@ struct QueryInterfaceQuery { var source: SQLSource? var wherePromise: DatabasePromise var groupByExpressions: [SQLExpression] - var orderings: [SQLOrderingTerm] - var isReversed: Bool + var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? @@ -33,8 +32,7 @@ struct QueryInterfaceQuery { from source: SQLSource? = nil, filter whereExpression: SQLExpression? = nil, groupBy groupByExpressions: [SQLExpression] = [], - orderBy orderings: [SQLOrderingTerm] = [], - isReversed: Bool = false, + orderBy ordering: QueryOrdering = QueryOrdering(), having havingExpression: SQLExpression? = nil, limit: SQLLimit? = nil) { @@ -43,8 +41,7 @@ struct QueryInterfaceQuery { self.source = source self.wherePromise = DatabasePromise(value: whereExpression) self.groupByExpressions = groupByExpressions - self.orderings = orderings - self.isReversed = isReversed + self.ordering = ordering self.havingExpression = havingExpression self.limit = limit } @@ -81,7 +78,7 @@ struct QueryInterfaceQuery { sql += " HAVING " + havingExpression.expressionSQL(&arguments) } - let orderings = self.queryOrderings + let orderings = self.ordering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -116,7 +113,7 @@ struct QueryInterfaceQuery { } if let limit = limit { - let orderings = self.queryOrderings + let orderings = self.ordering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -133,35 +130,10 @@ struct QueryInterfaceQuery { return statement } - private var queryOrderings: [SQLOrderingTerm] { - if isReversed { - if orderings.isEmpty { - // https://www.sqlite.org/lang_createtable.html#rowid - // - // > The rowid value can be accessed using one of the special - // > case-independent names "rowid", "oid", or "_rowid_" in - // > place of a column name. If a table contains a user defined - // > column named "rowid", "oid" or "_rowid_", then that name - // > always refers the explicitly declared column and cannot be - // > used to retrieve the integer rowid value. - // - // Here we assume that rowid is not a custom column. - // TODO: support for user-defined rowid column. - // TODO: support for WITHOUT ROWID tables. - return [Column.rowID.desc] - } else { - return orderings.map { $0.reversed } - } - } else { - return orderings - } - } - /// Remove ordering var unorderedQuery: QueryInterfaceQuery { var query = self - query.isReversed = false - query.orderings = [] + query.ordering = QueryOrdering() return query } } @@ -261,6 +233,36 @@ extension QueryInterfaceQuery { } } +struct QueryOrdering { + private var orderings: [SQLOrderingTerm] + var isReversed: Bool + + init(orderings: [SQLOrderingTerm] = [], isReversed: Bool = false) { + self.orderings = orderings + self.isReversed = isReversed + } + + func reversed() -> QueryOrdering { + return QueryOrdering( + orderings: orderings, + isReversed: !isReversed) + } + + func appending(ordering: SQLOrderingTerm) -> QueryOrdering { + return QueryOrdering( + orderings: orderings + [ordering], + isReversed: isReversed) + } + + func resolve() -> [SQLOrderingTerm] { + if isReversed { + return orderings.map { $0.reversed } + } else { + return orderings + } + } +} + indirect enum SQLSource { case table(name: String, alias: String?) case query(query: QueryInterfaceQuery, alias: String?) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 833a2b7f5..ac29e72a4 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -137,8 +137,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .order([Column("name")]) public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { var query = self.query - query.orderings = orderings - query.isReversed = false + query.ordering = QueryOrdering(orderings: orderings) return QueryInterfaceRequest(query: query) } @@ -149,7 +148,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { var query = self.query - query.isReversed = !query.isReversed + query.ordering = query.ordering.reversed() return QueryInterfaceRequest(query: query) } From f4382e6bcb345dddd668cd74b3ed6564da478cf0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 12:52:01 +0200 Subject: [PATCH 184/348] Test that request.reversed() has no effect when request is not already ordered --- Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift | 2 +- Tests/GRDBTests/QueryInterfaceRequestTests.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift index bee0a4c0d..2a8318ae7 100644 --- a/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordDeleteTests.swift @@ -172,7 +172,7 @@ class MutablePersistableRecordDeleteTests: GRDBTestCase { XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2") try Person.limit(1, offset: 2).reversed().deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"rowid\" DESC LIMIT 1 OFFSET 2") + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" LIMIT 1 OFFSET 2") } } } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 754aa8057..8b28d4046 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -417,7 +417,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( sql(dbQueue, tableRequest.reversed()), - "SELECT * FROM \"readers\" ORDER BY \"rowid\" DESC") + "SELECT * FROM \"readers\"") XCTAssertEqual( sql(dbQueue, tableRequest.order(Col.age).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") From 0f21f886b4755b721566d548b55785b2e3e783ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 26 Apr 2018 12:54:28 +0200 Subject: [PATCH 185/348] Document that request.reversed() has no effect when request is not already ordered --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b9e9d38c0..9f01b480d 100644 --- a/README.md +++ b/README.md @@ -3547,10 +3547,10 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.order(scoreColumn.desc, nameColumn).reversed() ``` - If no ordering was specified, the result is ordered by rowID in reverse order. + If no ordering was already specified, this method has no effect: ```swift - // SELECT * FROM players ORDER BY _rowid_ DESC + // SELECT * FROM players Player.all().reversed() ``` @@ -3578,6 +3578,7 @@ Player // SELECT * FROM players .filter(nameColumn != nil) // WHERE (name IS NOT NULL) .filter(emailColumn != nil) // AND (email IS NOT NULL) .order(nameColumn) // - ignored - + .reversed() // - ignored - .order(scoreColumn) // ORDER BY score .limit(20, offset: 40) // - ignored - .limit(10) // LIMIT 10 From 175656aa26b7ee9df543f88ac542ca15e9683910 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 27 Apr 2018 09:01:13 +0200 Subject: [PATCH 186/348] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9f01b480d..22f2db351 100644 --- a/README.md +++ b/README.md @@ -400,7 +400,7 @@ try dbQueue.read { db in } ``` -Database access methods can return values, for easy extraction of database values: +Database access methods can return values: ```swift let placeCount = try dbQueue.read { db in @@ -470,7 +470,7 @@ try dbPool.read { db in } ``` -Database access methods can return values, for easy extraction of database values: +Database access methods can return values: ```swift let placeCount = try dbPool.read { db in From bf470b58709096771b00b8f671569d3f4d0f3a96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 27 Apr 2018 18:01:11 +0200 Subject: [PATCH 187/348] Documentation --- README.md | 291 +++++++++++++++++++++++++++++------------------------- 1 file changed, 157 insertions(+), 134 deletions(-) diff --git a/README.md b/README.md index 22f2db351..81cdae9db 100644 --- a/README.md +++ b/README.md @@ -2945,146 +2945,169 @@ try dbQueue.write { db in Each one of the three examples below is correct. You will pick one or the other depending on your personal preferences and the requirements of your application: -- **Example 1**: Define a Codable struct and adopt each one of the [record protocols](#record-protocols-overview). - - ```swift - struct Place: Codable { - var id: Int64? - var title: String - var favorite: Bool - var latitude: CLLocationDegrees - var longitude: CLLocationDegrees - - var coordinate: CLLocationCoordinate2D { - get { - return CLLocationCoordinate2D( - latitude: latitude, - longitude: longitude) - } - set { - latitude = newValue.latitude - longitude = newValue.longitude - } - } - } - - extension Place: TableRecord { - /// The table name - static let databaseTableName = "places" - } - - extension Place: FetchableRecord { } - - extension Place: MutablePersistableRecord { - /// Update record ID after a successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } - } - ``` +
+ Define a Codable struct, and adopt the record protocols you need -- **Example 2**: Define a plain struct and explicitly adopt each one of the [record protocols](#record-protocols-overview). - - ```swift - struct Place { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D - } - - extension Place: TableRecord { - /// The table name - static let databaseTableName = "places" - - /// The table columns - enum Columns: String, ColumnExpression { - case id, title, favorite, latitude, longitude - } - } - - extension Place: FetchableRecord { - /// Creates a record from a database row - init(row: Row) { - id = row[Columns.id] - title = row[Columns.title] - isFavorite = row[Columns.favorite] - coordinate = CLLocationCoordinate2D( - latitude: row[Columns.latitude], - longitude: row[Columns.longitude]) - } - } - - extension Place: MutablePersistableRecord { - /// The values persisted in the database - func encode(to container: inout PersistenceContainer) { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.favorite] = isFavorite - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } - - /// Update record ID after a successful insertion - mutating func didInsert(with rowID: Int64, for column: String?) { - id = rowID - } - } - ``` +This is the shortest way to define a record type. -- **Example 3**: Subclass the [Record class](#record-class). +See the [Record Protocols Overview](#record-protocols-overview), and [Codable Records](#codable-records) for more information. + +```swift +struct Place: Codable { + var id: Int64? + var title: String + var favorite: Bool + var latitude: CLLocationDegrees + var longitude: CLLocationDegrees - ```swift - class Place: Record { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D - - init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { - self.id = id - self.title = title - self.isFavorite = isFavorite - self.coordinate = coordinate - super.init() + var coordinate: CLLocationCoordinate2D { + get { + return CLLocationCoordinate2D( + latitude: latitude, + longitude: longitude) } - - /// The table name - override class var databaseTableName: String { - return "places" - } - - /// The table columns - enum Columns: String, ColumnExpression { - case id, title, favorite, latitude, longitude - } - - /// Creates a record from a database row - required init(row: Row) { - id = row[Columns.id] - title = row[Columns.title] - isFavorite = row[Columns.favorite] - coordinate = CLLocationCoordinate2D( - latitude: row[Columns.latitude], - longitude: row[Columns.longitude]) - super.init(row: row) - } - - /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.favorite] = isFavorite - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } - - /// Update record ID after a successful insertion - override func didInsert(with rowID: Int64, for column: String?) { - id = rowID + set { + latitude = newValue.latitude + longitude = newValue.longitude } } - ``` +} + +// SQL generation +extension Place: TableRecord { + /// The table name + static let databaseTableName = "places" +} + +// Fetching methods +extension Place: FetchableRecord { } + +// Persistence methods +extension Place: MutablePersistableRecord { + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ +
+ Define a plain struct, and adopt the record protocols you need + +See the [Record Protocols Overview](#record-protocols-overview) for more information. + +```swift +struct Place { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D +} + +// SQL generation +extension Place: TableRecord { + /// The table name + static let databaseTableName = "places" + + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } +} + +// Fetching methods +extension Place: FetchableRecord { + /// Creates a record from a database row + init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + } +} + +// Persistence methods +extension Place: MutablePersistableRecord { + /// The values persisted in the database + func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
+ +
+ Subclass the Record class + +See the [Record class](#record-class) for more information. + +```swift +class Place: Record { + var id: Int64? + var title: String + var isFavorite: Bool + var coordinate: CLLocationCoordinate2D + + init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { + self.id = id + self.title = title + self.isFavorite = isFavorite + self.coordinate = coordinate + super.init() + } + + /// The table name + override class var databaseTableName: String { + return "places" + } + + /// The table columns + enum Columns: String, ColumnExpression { + case id, title, favorite, latitude, longitude + } + + /// Creates a record from a database row + required init(row: Row) { + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.favorite] + coordinate = CLLocationCoordinate2D( + latitude: row[Columns.latitude], + longitude: row[Columns.longitude]) + super.init(row: row) + } + + /// The values persisted in the database + override func encode(to container: inout PersistenceContainer) { + container[Columns.id] = id + container[Columns.title] = title + container[Columns.favorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude + } + + /// Update record ID after a successful insertion + override func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +
## List of Record Methods From d6183a474575557011db8e1176912fc5bcdcf1b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 28 Apr 2018 10:29:56 +0200 Subject: [PATCH 188/348] Typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 81cdae9db..25b165c60 100644 --- a/README.md +++ b/README.md @@ -3716,7 +3716,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: // SELECT * FROM players WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) let conditions = [ verifiedColumn, - scoreColumn >=< 1000, + scoreColumn >= 1000, nameColumn != nil] Player.filter(conditions.joined(operator: .and)) ``` From df79bb8ed81e2a89b75a8b569c9a4c1d067e49ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 28 Apr 2018 10:36:58 +0200 Subject: [PATCH 189/348] whitespace --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 25b165c60..1e0990dbb 100644 --- a/README.md +++ b/README.md @@ -4237,7 +4237,7 @@ try request.fetchCursor(db) // A cursor of rows let playerRequest = ... // Some FetchRequest that fetches Player try request.fetchAll(db) // [Player] -let intRequest = ... // Some FetchRequest that fetches Int +let intRequest = ... // Some FetchRequest that fetches Int try request.fetchOne(db) // Int? ``` From 3e46942f302343402e9e6924682bc1bc2b8d3ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 18:16:39 +0200 Subject: [PATCH 190/348] Associations --- GRDB.xcodeproj/project.pbxproj | 180 +++ GRDB/Core/DatabaseValue.swift | 6 + .../Association/Association.swift | 232 +++ .../Association/AssociationMapping.swift | 23 + .../Association/AssociationQuery.swift | 139 ++ .../Association/AssociationRequest.swift | 56 + .../Association/BelongsToAssociation.swift | 71 + .../Association/ForeignKey.swift | 16 + .../Association/ForeignKeyRequest.swift | 86 + .../Association/HasManyAssociation.swift | 71 + .../Association/HasOneAssociation.swift | 71 + GRDB/QueryInterface/Column.swift | 18 +- .../FTS3+QueryInterfaceRequest.swift | 8 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 13 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 460 +++++- .../QueryInterfaceRequest+Association.swift | 139 ++ .../QueryInterfaceRequest.swift | 223 +-- GRDB/QueryInterface/RequestProtocols.swift | 105 +- .../SQLCollatedExpression.swift | 6 + .../SQLExpression+QueryInterface.swift | 56 + GRDB/QueryInterface/SQLExpression.swift | 16 + GRDB/QueryInterface/SQLOrdering.swift | 12 + .../SQLSelectable+QueryInterface.swift | 5 +- GRDB/QueryInterface/SQLSelectable.swift | 141 +- GRDB/Record/PersistableRecord.swift | 9 + GRDB/Record/TableRecord.swift | 5 +- GRDBCipher.xcodeproj/project.pbxproj | 216 +++ GRDBCustom.xcodeproj/project.pbxproj | 160 ++ ...ciationBelongsToDecodableRecordTests.swift | 111 ++ ...ciationBelongsToFetchableRecordTests.swift | 120 ++ .../AssociationBelongsToRowScopeTests.swift | 131 ++ ...sociationBelongsToSQLDerivationTests.swift | 406 +++++ .../AssociationBelongsToSQLTests.swift | 771 +++++++++ .../AssociationChainRowScopesTests.swift | 694 ++++++++ .../GRDBTests/AssociationChainSQLTests.swift | 557 +++++++ .../AssociationHasOneSQLDerivationTests.swift | 406 +++++ .../GRDBTests/AssociationHasOneSQLTests.swift | 769 +++++++++ ...ociationParallelDecodableRecordTests.swift | 237 +++ .../AssociationParallelRowScopesTests.swift | 1400 +++++++++++++++++ .../AssociationParallelSQLTests.swift | 272 ++++ .../AssociationRowScopeSearchTests.swift | 244 +++ .../AssociationTableAliasTestsSQLTests.swift | 340 ++++ 42 files changed, 8741 insertions(+), 260 deletions(-) create mode 100644 GRDB/QueryInterface/Association/Association.swift create mode 100644 GRDB/QueryInterface/Association/AssociationMapping.swift create mode 100644 GRDB/QueryInterface/Association/AssociationQuery.swift create mode 100644 GRDB/QueryInterface/Association/AssociationRequest.swift create mode 100644 GRDB/QueryInterface/Association/BelongsToAssociation.swift create mode 100644 GRDB/QueryInterface/Association/ForeignKey.swift create mode 100644 GRDB/QueryInterface/Association/ForeignKeyRequest.swift create mode 100644 GRDB/QueryInterface/Association/HasManyAssociation.swift create mode 100644 GRDB/QueryInterface/Association/HasOneAssociation.swift create mode 100644 GRDB/QueryInterface/QueryInterfaceRequest+Association.swift create mode 100644 Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift create mode 100644 Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift create mode 100644 Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift create mode 100644 Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift create mode 100644 Tests/GRDBTests/AssociationBelongsToSQLTests.swift create mode 100644 Tests/GRDBTests/AssociationChainRowScopesTests.swift create mode 100644 Tests/GRDBTests/AssociationChainSQLTests.swift create mode 100644 Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift create mode 100644 Tests/GRDBTests/AssociationHasOneSQLTests.swift create mode 100644 Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift create mode 100644 Tests/GRDBTests/AssociationParallelRowScopesTests.swift create mode 100644 Tests/GRDBTests/AssociationParallelSQLTests.swift create mode 100644 Tests/GRDBTests/AssociationRowScopeSearchTests.swift create mode 100644 Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 571eaeeb5..229b2acee 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -148,6 +148,64 @@ 564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C311F07611600877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */; }; + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */; }; + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB0920944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFA20944C7B00F46237 /* Association.swift */; }; + 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; }; + 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; + 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; + 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; + 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; + 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; + 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFF20944C7C00F46237 /* ForeignKey.swift */; }; + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; }; + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; 565490B41D5A4820005622CB /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B51D5A4827005622CB /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B61D5AE236005622CB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; @@ -809,6 +867,30 @@ 564E73DE203D50B9000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; + 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; @@ -1268,6 +1350,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1284,11 +1367,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EAF720944BC900F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1319,6 +1404,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EABF20944B1300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAD420944B4E00F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EACE20944B4D00F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EAC720944B4C00F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EAD120944B4E00F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */, + 5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */, + 5653EACA20944B4D00F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EACC20944B4D00F46237 /* AssociationHasOneSQLTests.swift */, + 5653EAD220944B4E00F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EACD20944B4D00F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EAD520944B4F00F46237 /* AssociationParallelSQLTests.swift */, + 5653EAC820944B4D00F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EACB20944B4D00F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; + 5653EAF720944BC900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EAFA20944C7B00F46237 /* Association.swift */, + 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */, + 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, + 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, + 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, + 5653EAFF20944C7C00F46237 /* ForeignKey.swift */, + 5653EAF920944C7B00F46237 /* ForeignKeyRequest.swift */, + 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */, + 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */, + ); + path = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -2191,6 +2313,7 @@ 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, + 5653EB0B20944C7C00F46237 /* Association.swift in Sources */, 56F5ABDA1D814330001F60CB /* NSData.swift in Sources */, 56D121601ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */, @@ -2198,6 +2321,7 @@ 5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */, 56CEB5671EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, + 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 565490B91D5AE236005622CB /* DatabasePool.swift in Sources */, 5674A6EF1F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift in Sources */, 565490D81D5AE252005622CB /* DatabaseMigrator.swift in Sources */, @@ -2207,12 +2331,14 @@ 565490D91D5AE252005622CB /* Migration.swift in Sources */, 56CEB5001EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD271DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, + 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */, C96C0F2D2084A45A006B2981 /* SQLiteDateParser.swift in Sources */, 566A841C2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 565490D51D5AE252005622CB /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 565490C51D5AE236005622CB /* SerializedDatabase.swift in Sources */, 56F3E7691E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 5698AC7E1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, + 5653EB1A20944C7C00F46237 /* ForeignKey.swift in Sources */, 5698AC3D1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */, 566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, @@ -2227,6 +2353,7 @@ 565490C31D5AE236005622CB /* RowAdapter.swift in Sources */, 5698AD3B1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, 5659F49E1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */, 565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */, 565490D01D5AE252005622CB /* NSString.swift in Sources */, @@ -2235,6 +2362,7 @@ 5674A6E81F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, 56873BF21F2CB400004D24B4 /* Fixits-1.2.swift in Sources */, 56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */, + 5653EB2320944C7C00F46237 /* HasOneAssociation.swift in Sources */, 565490C01D5AE236005622CB /* DatabaseWriter.swift in Sources */, 565490C41D5AE236005622CB /* SchedulingWatchdog.swift in Sources */, 566B91311FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, @@ -2242,6 +2370,7 @@ 565490CC1D5AE252005622CB /* (null) in Sources */, 56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, @@ -2267,13 +2396,16 @@ 56F5ABDD1D814330001F60CB /* UUID.swift in Sources */, 565490CB1D5AE252005622CB /* (null) in Sources */, 565490D61D5AE252005622CB /* StandardLibrary.swift in Sources */, + 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, + 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, 565490BA1D5AE236005622CB /* DatabaseQueue.swift in Sources */, 565490CD1D5AE252005622CB /* Date.swift in Sources */, + 5653EB0820944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2307,16 +2439,19 @@ 5605F18E1C6B1A8700235C62 /* SQLCollatedExpression.swift in Sources */, 566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */, 5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, + 5653EB0A20944C7C00F46237 /* Association.swift in Sources */, 56A2387E1B9C75030082EB20 /* Database.swift in Sources */, 56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */, 56CEB5481EAA359A00BFAF62 /* Column.swift in Sources */, + 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1641C672E4000235C62 /* Date.swift in Sources */, 566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, 56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5659F49B1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */, 569A98EE2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 56CEB51C1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 5698AC3A1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2325,6 +2460,7 @@ 563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7661E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, + 5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 56B964B41DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A81C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, 566A841B2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, @@ -2335,10 +2471,12 @@ 56A8C2331D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D321DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, + 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */, 566475BD1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56A238A51B9C753B0082EB20 /* Record.swift in Sources */, 5671FC231DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, + 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, @@ -2360,9 +2498,11 @@ 56A238881B9C75030082EB20 /* Row.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, + 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, + 5653EB1920944C7C00F46237 /* ForeignKey.swift in Sources */, 5659F4A31EA8D997004A4992 /* Result.swift in Sources */, 56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, 5605F1661C672E4000235C62 /* NSNull.swift in Sources */, @@ -2371,6 +2511,7 @@ 5698AC7B1DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D1215D1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, + 5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, @@ -2380,6 +2521,7 @@ 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 566475A51D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, + 5653EB0720944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5657AABC1D107001006283EF /* NSData.swift in Sources */, 31A778841C6A4E0600F507F6 /* FetchedRecordsController.swift in Sources */, 56A238861B9C75030082EB20 /* DatabaseValue.swift in Sources */, @@ -2434,6 +2576,7 @@ 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5698AC841DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */, 56A238541B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */, @@ -2448,12 +2591,14 @@ 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, + 5653EADD20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56300B621C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */, 567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 5657AB6A1D108BA9006283EF /* FoundationURLTests.swift in Sources */, + 5653EADF20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */, 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2472,6 +2617,7 @@ 560A37AC1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift in Sources */, 5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */, 5690C33B1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EAF320944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 565D5D721BBC694D00DC9BD4 /* Row+FoundationTests.swift in Sources */, 5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, 567A80571D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, @@ -2491,19 +2637,25 @@ 565B0FF01BBC7D980098DE03 /* FetchableRecordTests.swift in Sources */, 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, + 5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */, + 5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE720944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5695312A1C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EADB20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, 56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, 56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */, + 5653EAEF20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A2383C1B9C74A90082EB20 /* DatabaseErrorTests.swift in Sources */, 5690C32A1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, 5657AB3A1D108BA9006283EF /* FoundationDataTests.swift in Sources */, @@ -2519,17 +2671,21 @@ 568068351EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 565D5D751BBC70AE00DC9BD4 /* StatementArguments+FoundationTests.swift in Sources */, 5623931C1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EAD720944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 562393641DEE06D300A6B01F /* CursorTests.swift in Sources */, 5657AB5A1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56300B6C1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5674A7231F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56F0B9921B6001C600A2F135 /* FoundationNSDateTests.swift in Sources */, 56A238381B9C74A90082EB20 /* DatabaseTests.swift in Sources */, + 5653EAED20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56300B5F1C53C38F005A543B /* QueryInterfaceRequestTests.swift in Sources */, 5634B10A1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 560C97C81BFD0B8400BF8471 /* DatabaseFunctionTests.swift in Sources */, + 5653EAD920944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56A2383A1B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift in Sources */, 56A5E40A1BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift in Sources */, + 5653EAF520944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */, 5605F1881C69111300235C62 /* DatabaseRegionTests.swift in Sources */, @@ -2581,6 +2737,7 @@ 56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */, 56D496631D81304E008276D7 /* FoundationURLTests.swift in Sources */, 56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */, + 5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */, 56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */, 56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, 56D496AE1D813345008276D7 /* DatabasePoolCollationTests.swift in Sources */, @@ -2595,12 +2752,14 @@ 56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */, 5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, + 5653EADC20944B4F00F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */, 567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */, 56D4968D1D81316E008276D7 /* DatabaseFunctionTests.swift in Sources */, + 5653EADE20944B4F00F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 56D496661D813086008276D7 /* QueryInterfaceRequestTests.swift in Sources */, 56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */, 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */, @@ -2619,6 +2778,7 @@ 5698AC031D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56D496611D81304E008276D7 /* Row+FoundationTests.swift in Sources */, 56D496C41D813767008276D7 /* DatabaseQueueTests.swift in Sources */, + 5653EAF220944B4F00F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56D496851D813147008276D7 /* StatementArgumentsTests.swift in Sources */, 56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */, 56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */, @@ -2638,19 +2798,25 @@ 56176C5D1EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 56D496B21D8133CE008276D7 /* DatabaseQueueInMemoryTests.swift in Sources */, 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, + 5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */, + 5653EAE020944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, + 5653EAE620944B4F00F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */, 56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */, 56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */, 56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, + 5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */, 56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */, 56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, @@ -2666,17 +2832,21 @@ 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, 56D496951D81317B008276D7 /* MutablePersistableRecordTests.swift in Sources */, + 5653EAD620944B4F00F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5698AC801DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 56D496821D813131008276D7 /* TransactionObserverTests.swift in Sources */, 56D496941D81317B008276D7 /* SchedulingWatchdogTests.swift in Sources */, 5674A7201F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift in Sources */, 56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */, 56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, + 5653EAEC20944B4F00F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 5698ACB61DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 56D4965C1D81304E008276D7 /* FoundationNSNullTests.swift in Sources */, + 5653EAD820944B4F00F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56D4967F1D813131008276D7 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EAF420944B4F00F46237 /* AssociationParallelSQLTests.swift in Sources */, 56D496971D81317B008276D7 /* DatabaseReaderTests.swift in Sources */, 56D496911D81316E008276D7 /* RowFromStatementTests.swift in Sources */, 56071A411DB54ED000CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, @@ -2728,11 +2898,13 @@ 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F061E859064008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7631E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, + 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5605F1691C672E4000235C62 /* NSString.swift in Sources */, 560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */, 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */, @@ -2742,6 +2914,7 @@ 56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */, 56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, + 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, @@ -2763,12 +2936,16 @@ 5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, 5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D361DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, + 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */, 56193E8E1CD8A3E200F95862 /* FetchedRecordsController.swift in Sources */, 56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */, + 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */, 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */, 5605F1651C672E4000235C62 /* NSNull.swift in Sources */, 56CEB5191EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, + 5653EB1820944C7C00F46237 /* ForeignKey.swift in Sources */, 5674A6FB1F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */, + 5653EB0620944C7C00F46237 /* ForeignKeyRequest.swift in Sources */, 5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */, 56A2387D1B9C75030082EB20 /* Database.swift in Sources */, 566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */, @@ -2776,12 +2953,15 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, + 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, + 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */, 5657AAB91D107001006283EF /* NSData.swift in Sources */, 560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, 56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 7f4603cf4..258bdefe2 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -355,6 +355,12 @@ extension DatabaseValue { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return self } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // CustomStringConvertible diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift new file mode 100644 index 000000000..d0028c0ab --- /dev/null +++ b/GRDB/QueryInterface/Association/Association.swift @@ -0,0 +1,232 @@ +/// The base protocol for all associations that define a connection between two +/// Record types. +public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype LeftAssociated: TableRecord + associatedtype RightAssociated: TableRecord + + /// The association key defines how rows fetched from this association + /// should be consumed. + /// + /// For example: + /// + /// struct Player: TableRecord { + /// // The default key of this association is the name of the + /// // database table for teams, let's say "team": + /// static let team = belongsTo(Team.self) + /// } + /// print(Player.team.key) // Prints "team" + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["team"] // the association key + /// } + /// + /// The key can be redefined with the `forKey` method: + /// + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + var key: String { get } + + /// Creates an association with the given key. + /// + /// This new key impacts how rows fetched from this association + /// should be consumed: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // Consume rows: + /// let request = Player.including(required: Player.team.forKey("custom")) + /// for row in Row.fetchAll(db, request) { + /// let team: Team = row["custom"] + /// } + func forKey(_ key: String) -> Self + + /// :nodoc: + var request: AssociationRequest { get } + + /// :nodoc: + func associationMapping(_ db: Database) throws -> AssociationMapping + + /// :nodoc: + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self +} + +func defaultAssociationKey(for type: T.Type) -> String { + return T.databaseTableName +} + +extension Association { + /// Creates an association with a new net of selected columns. + /// + /// Any previous selection is replaced. + public func select(_ selection: [SQLSelectable]) -> Self { + return mapRequest { $0.select(selection) } + } + + /// Creates an association with the provided *predicate promise* added to + /// the eventual set of already applied predicates. + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { + return mapRequest { $0.filter(predicate) } + } + + /// Creates an association that matches nothing. + public func none() -> Self { + return mapRequest { $0.none() } + } + + /// Creates an association with the provided *orderings*. + /// + /// Any previous ordering is replaced. + public func order(_ orderings: [SQLOrderingTerm]) -> Self { + return mapRequest { $0.order(orderings) } + } + + /// Creates an association that reverses applied orderings. If no ordering + /// was applied, the returned request is identical. + public func reversed() -> Self { + return mapRequest { $0.reversed() } + } + + /// Creates an association with the given key. + /// + /// This new key helps Decodable records decode fetched rows: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// struct PlayerInfo: FetchableRecord, Decodable { + /// let player: Player + /// let team: Team + /// + /// static func all() -> AnyFetchRequest { + /// return Player + /// .including(required: Player.team.forKey(CodingKeys.team)) + /// .asRequest(of: PlayerInfo.self) + /// } + /// } + /// + /// let playerInfos = PlayerInfo.all().fetchAll(db) + /// print(playerInfos.first?.team) + public func forKey(_ codingKey: CodingKey) -> Self { + return forKey(codingKey.stringValue) + } + + /// Creates an association that allows you to define unambiguous expressions + /// based on the associated record. + /// + /// In the example below, the "team.color = 'red'" condition in the where + /// clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... + /// // WHERE team.color = 'red' + /// let teamAlias = TableAlias() + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(teamAlias[Column("color"] == "red") + /// + /// When you give a name to a table alias, you can reliably inject sql + /// snippets in your requests: + /// + /// // SELECT player.*, custom.* + /// // JOIN team custom ON ... + /// // WHERE custom.color = 'red' + /// let teamAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team.aliased(teamAlias)) + /// .filter(sql: "custom.color = ?", arguments: ["red") + public func aliased(_ alias: TableAlias) -> Self { + return mapRequest { $0.aliased(alias) } + } +} + +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// AssociationChainOperator is designed to be hierarchically nested, unlike +/// SQL join operators. +/// +/// Consider the following request for (A, B, C) tuples: +/// +/// let r = A.including(optional: A.b.including(required: B.c)) +/// +/// It chains three associations, the first optional, the second required. +/// +/// It looks like it means: "Give me all As, along with their Bs, granted those +/// Bs have their Cs. For As whose B has no C, give me a nil B". +/// +/// It can not be expressed as one left join, and a regular join, as below, +/// Because this would not honor the first optional: +/// +/// -- dubious +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// JOIN c ON ... +/// +/// Instead, it should: +/// - allow (A + missing (B + C)) +/// - prevent (A + (B + missing C)). +/// +/// This can be expressed in SQL with two left joins, and an extra condition: +/// +/// -- likely correct +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// LEFT JOIN c ON ... +/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C +/// +/// This is currently not implemented, and requires a little more thought. +/// I don't even know if inventing a whole new way to perform joins should even +/// be on the table. But we have a hierarchical way to express joined queries, +/// and they have a meaning: +/// +/// // what is my meaning? +/// A.including(optional: A.b.including(required: B.c)) +enum AssociationChainOperator { + case required, optional +} + +extension Association { + /// Creates an association that includes another one. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.optional, association) } + } + + /// Creates an association that includes another one. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.required, association) } + } + + /// Creates an association that joins another one. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.optional, association.select([])) } + } + + /// Creates an association that joins another one. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated + { + return mapRequest { $0.chain(.required, association.select([])) } + } +} diff --git a/GRDB/QueryInterface/Association/AssociationMapping.swift b/GRDB/QueryInterface/Association/AssociationMapping.swift new file mode 100644 index 000000000..a75c01494 --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationMapping.swift @@ -0,0 +1,23 @@ +public typealias AssociationMapping = (SQLTableQualifier, SQLTableQualifier) -> SQLExpression? + +enum AssociationMappingRequest { + case foreignKey(request: ForeignKeyRequest, originIsLeft: Bool) + + func fetch(_ db: Database) throws -> AssociationMapping { + switch self { + case .foreignKey(request: let foreignKeyRequest, originIsLeft: let originIsLeft): + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + return { (leftQualifier, rightQualifier) in + return columnMapping + .map { $0.right.qualifiedExpression(with: rightQualifier) == $0.left.qualifiedExpression(with: leftQualifier) } + .joined(operator: .and) + } + } + } +} diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift new file mode 100644 index 000000000..c89a1b25b --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -0,0 +1,139 @@ +struct AssociationQuery { + var source: SQLSource + var selection: [SQLSelectable] + var filterPromise: DatabasePromise + var ordering: QueryOrdering + var joins: [AssociationJoin] + + var qualifier: SQLTableQualifier? { + return source.qualifier + } + + var allQualifiers: [SQLTableQualifier] { + var qualifiers: [SQLTableQualifier] = [] + if let qualifier = qualifier { + qualifiers.append(qualifier) + } + qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) + return qualifiers + } + + var preparedQuery: AssociationQuery { + var qualifier = SQLTableQualifier(tableName: source.tableName!) + + var query = self + query.source = query.source.qualified(with: &qualifier) + query.selection = selection.map { $0.qualifiedSelectable(with: qualifier) } + query.filterPromise = filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } + query.ordering = ordering.qualified(with: qualifier) + query.joins = joins.map { + var join = $0 + join.rightQuery = join.rightQuery.preparedQuery + return join + } + return query + } + + var completeSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.rightQuery.completeSelection) + } + } + + var completeOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.rightQuery.completeOrdering) + } + } + + func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} + +extension AssociationQuery { + init(_ query: QueryInterfaceQuery) { + GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries") + GRDBPrecondition(query.groupByExpressions.isEmpty, "Can't join aggregated queries") + GRDBPrecondition(query.havingExpression == nil, "Can't join aggregated queries") + GRDBPrecondition(query.limit == nil, "Can't join limited queries") + + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } +} + +extension AssociationQuery { + func select(_ selection: [SQLSelectable]) -> AssociationQuery { + var query = self + query.selection = selection + return query + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationQuery { + var query = self + query.filterPromise = query.filterPromise.map { (db, filter) in + if let filter = filter { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } + } + return query + } + + func none() -> AssociationQuery { + var query = self + query.filterPromise = DatabasePromise(value: false.sqlExpression) + return query + } + + func order(_ orderings: [SQLOrderingTerm]) -> AssociationQuery { + return order(QueryOrdering(orderings: orderings)) + } + + func reversed() -> AssociationQuery { + return order(ordering.reversed) + } + + private func order(_ ordering: QueryOrdering) -> AssociationQuery { + var query = self + query.ordering = ordering + return query + } + + func joining(_ join: AssociationJoin) -> AssociationQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with qualifier: inout SQLTableQualifier) -> AssociationQuery { + var query = self + query.source = source.qualified(with: &qualifier) + return query + } +} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift new file mode 100644 index 000000000..0c8d54351 --- /dev/null +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -0,0 +1,56 @@ +/// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, +/// the AssociationRequest is (`b.*` + `b.name = 'foo'`). +public struct AssociationRequest { + let query: AssociationQuery + + init(query: AssociationQuery) { + self.query = query + } + + init(_ request: QueryInterfaceRequest) { + self.init(query: AssociationQuery(request.query)) + } +} + +extension AssociationRequest { + func select(_ selection: [SQLSelectable]) -> AssociationRequest { + return AssociationRequest(query: query.select(selection)) + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> AssociationRequest { + return AssociationRequest(query: query.filter(predicate)) + } + + func none() -> AssociationRequest { + return AssociationRequest(query: query.none()) + } + + func order(_ orderings: [SQLOrderingTerm]) -> AssociationRequest { + return AssociationRequest(query: query.order(orderings)) + } + + func reversed() -> AssociationRequest { + return AssociationRequest(query: query.reversed()) + } + + func aliased(_ alias: TableAlias) -> AssociationRequest { + let userProvidedAlias = alias.userProvidedAlias + defer { + // Allow user to explicitely rename (TODO: test) + alias.userProvidedAlias = userProvidedAlias + } + return AssociationRequest(query: query.qualified(with: &alias.qualifier)) + } + + func chain(_ chainOp: AssociationChainOperator, _ association: A) + -> AssociationRequest + where A.LeftAssociated == T + { + let join = AssociationJoin( + op: chainOp, + rightQuery: association.request.query, + key: association.key, + associationMapping: association.associationMapping) + return AssociationRequest(query: query.joining(join)) + } +} diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift new file mode 100644 index 000000000..fbcc82e8d --- /dev/null +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -0,0 +1,71 @@ +public struct BelongsToAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> BelongsToAssociation { + return BelongsToAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: true) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + return BelongsToAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func belongsTo( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: databaseTableName, + destinationTable: Right.databaseTableName, + foreignKey: foreignKey) + + return BelongsToAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func belongsTo( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> BelongsToAssociation + where Right: TableRecord + { + return belongsTo(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift new file mode 100644 index 000000000..c509202b7 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -0,0 +1,16 @@ +/// A Foreign Key that helps building associations. +public struct ForeignKey { + let originColumns: [String] + let destinationColumns: [String]? + + /// TODO + public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { + self.originColumns = originColumns + self.destinationColumns = destinationColumns + } + + /// TODO + public init(_ originColumns: [Column], to destinationColumns: [Column]? = nil) { + self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name }) + } +} diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift new file mode 100644 index 000000000..a7fb3a325 --- /dev/null +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -0,0 +1,86 @@ +/// ForeignKeyRequest looks for the foreign keys associations need to +/// join tables. +/// +/// Mappings come from foreign keys, when they exist in the database schema. +/// +/// When the schema does not define any foreign key, we can still infer complete +/// mappings from partial information and primary keys. +struct ForeignKeyRequest { + let originTable: String + let destinationTable: String + let originColumns: [String]? + let destinationColumns: [String]? + + init(originTable: String, destinationTable: String, foreignKey: ForeignKey?) { + self.originTable = originTable + self.destinationTable = destinationTable + + self.originColumns = foreignKey?.originColumns + self.destinationColumns = foreignKey?.destinationColumns + } + + func fetch(_ db: Database) throws -> ForeignKeyInfo { + if let originColumns = originColumns, let destinationColumns = destinationColumns { + // Total information: no need to query the database schema. + GRDBPrecondition(originColumns.count == destinationColumns.count, "Number of columns don't match") + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + + // Incomplete information: let's look for schema foreign keys + let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in + if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() { + return false + } + if let originColumns = originColumns { + let originColumns = Set(originColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() }) + if originColumns != foreignKeyColumns { + return false + } + } + // TODO: test + if let destinationColumns = destinationColumns { + let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() }) + let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() }) + if destinationColumns != foreignKeyColumns { + return false + } + } + return true + } + + // Matching foreign key(s) found + if let foreignKey = foreignKeys.first { + if foreignKeys.count == 1 { + // Non-ambiguous + // TODO: test + return foreignKey + } else { + // Ambiguous: can't choose + fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)") + } + } + + // No matching foreign key found: use the destination primary key + if let originColumns = originColumns { + let destinationColumns = try db.primaryKey(destinationTable).columns + if (originColumns.count == destinationColumns.count) { + // TODO: test + let mapping = zip(originColumns, destinationColumns).map { + (origin: $0, destination: $1) + } + return ForeignKeyInfo(destinationTable: destinationTable, mapping: mapping) + } + } + + fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)") + } +} + + +/// The (origin, destination) column pairs that join a left table to a right table. +/// :nodoc: +typealias ForeignKeyMapping = [(origin: String, destination: String)] diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift new file mode 100644 index 000000000..8653413c2 --- /dev/null +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -0,0 +1,71 @@ +public struct HasManyAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasManyAssociation { + return HasManyAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: false) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + return HasManyAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasMany( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasManyAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasMany( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasManyAssociation + where Right: TableRecord + { + return hasMany(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift new file mode 100644 index 000000000..0a7f4b85f --- /dev/null +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -0,0 +1,71 @@ +public struct HasOneAssociation : Association, TableRequest where + Left: TableRecord, + Right: TableRecord +{ + public typealias LeftAssociated = Left + public typealias RightAssociated = Right + + public var key: String + + // :nodoc: + public var databaseTableName: String { return RightAssociated.databaseTableName } + + // :nodoc: + public let request: AssociationRequest + + let foreignKeyRequest: ForeignKeyRequest + + public func forKey(_ key: String) -> HasOneAssociation { + return HasOneAssociation( + key: key, + request: request, + foreignKeyRequest: foreignKeyRequest) + } + + // :nodoc: + public func associationMapping(_ db: Database) throws -> AssociationMapping { + return try AssociationMappingRequest + .foreignKey(request: foreignKeyRequest, originIsLeft: false) + .fetch(db) + } + + // :nodoc: + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + return HasOneAssociation( + key: key, + request: transform(request), + foreignKeyRequest: foreignKeyRequest) + } +} + +extension TableRecord { + // TODO: Make it public if and only if we really want to build an association from any request + static func hasOne( + _ rightRequest: QueryInterfaceRequest, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + let foreignKeyRequest = ForeignKeyRequest( + originTable: Right.databaseTableName, + destinationTable: databaseTableName, + foreignKey: foreignKey) + + return HasOneAssociation( + key: key ?? defaultAssociationKey(for: Right.self), + request: AssociationRequest(rightRequest), + foreignKeyRequest: foreignKeyRequest) + } + + /// TODO + public static func hasOne( + _ right: Right.Type, + key: String? = nil, + using foreignKey: ForeignKey? = nil) + -> HasOneAssociation + where Right: TableRecord + { + return hasOne(Right.all(), key: key, using: foreignKey) + } +} diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index cd6ecb5c0..26010d442 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -37,6 +37,12 @@ extension ColumnExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return QualifiedColumn(name, qualifier: qualifier) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } /// A column in a database table. @@ -70,7 +76,7 @@ struct QualifiedColumn: ColumnExpression { } func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { + if let qualifierName = qualifier.qualifiedName { return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier @@ -80,6 +86,16 @@ struct QualifiedColumn: ColumnExpression { // Never requalify return self } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + guard + let container = context[qualifier], + let value = container.value(forCaseInsensitiveColumn: name) else + { + return self + } + return value + } } /// Support for column enums: diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 171b12868..6e2d37356 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -12,13 +12,7 @@ extension QueryInterfaceRequest { /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern ?? DatabaseValue.null)) - default: - // Programmer error - fatalError("fts3 match requires a table") - } + return filter(Column(query.source.qualifiedName).match(pattern)) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 0394a5450..fcc29e883 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -17,17 +17,10 @@ /// all requests by the `TableRecord.databaseSelection` property, or /// for individual requests with the `TableRecord.select` method. public func matching(_ pattern: FTS5Pattern?) -> QueryInterfaceRequest { - switch query.source { - case .table(let name, let alias)?: - if let pattern = pattern { - return filter(SQLExpressionBinary(.match, Column(alias ?? name), pattern)) - } else { - return filter(false) - } - default: - // Programmer error - fatalError("fts5 match requires a table") + guard let pattern = pattern else { + return none() } + return filter(SQLExpressionBinary(.match, Column(query.source.qualifiedName), pattern)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 2c3cfbec4..8999861c2 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -17,39 +17,36 @@ struct DatabasePromise { } struct QueryInterfaceQuery { + var source: SQLSource var selection: [SQLSelectable] var isDistinct: Bool - var source: SQLSource? - var wherePromise: DatabasePromise + var filterPromise: DatabasePromise var groupByExpressions: [SQLExpression] var ordering: QueryOrdering var havingExpression: SQLExpression? var limit: SQLLimit? + var joins: [AssociationJoin] init( - select selection: [SQLSelectable], + source: SQLSource, + selection: [SQLSelectable] = [], isDistinct: Bool = false, - from source: SQLSource? = nil, - filter whereExpression: SQLExpression? = nil, - groupBy groupByExpressions: [SQLExpression] = [], - orderBy ordering: QueryOrdering = QueryOrdering(), - having havingExpression: SQLExpression? = nil, - limit: SQLLimit? = nil) + filterPromise: DatabasePromise = DatabasePromise(value: nil), + groupByExpressions: [SQLExpression] = [], + ordering: QueryOrdering = QueryOrdering(), + havingExpression: SQLExpression? = nil, + limit: SQLLimit? = nil, + joins: [AssociationJoin] = []) { + self.source = source self.selection = selection self.isDistinct = isDistinct - self.source = source - self.wherePromise = DatabasePromise(value: whereExpression) + self.filterPromise = filterPromise self.groupByExpressions = groupByExpressions self.ordering = ordering self.havingExpression = havingExpression self.limit = limit - } - - func mapWhereExpression(_ transform: @escaping (Database, SQLExpression?) throws -> SQLExpression?) -> QueryInterfaceQuery { - var query = self - query.wherePromise = query.wherePromise.map(transform) - return query + self.joins = joins } func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { @@ -59,15 +56,18 @@ struct QueryInterfaceQuery { sql += " DISTINCT" } - assert(!selection.isEmpty) + let selection = completeSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) + sql += try " FROM " + source.sourceSQL(db, &arguments) + + for join in joins { + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier!) } - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&arguments) } if !groupByExpressions.isEmpty { @@ -78,7 +78,7 @@ struct QueryInterfaceQuery { sql += " HAVING " + havingExpression.expressionSQL(&arguments) } - let orderings = self.ordering.resolve() + let orderings = completeOrdering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -93,27 +93,35 @@ struct QueryInterfaceQuery { func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { guard groupByExpressions.isEmpty else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + fatalError("Can't delete query with GROUP BY clause") } guard havingExpression == nil else { // Programmer error - fatalError("Can't delete query with GROUP BY expression") + fatalError("Can't delete query with HAVING clause") } + guard joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + guard case .table = source else { + // Programmer error + fatalError("Can't delete without any database table") + } + var sql = "DELETE" var arguments: StatementArguments? = StatementArguments() - if let source = source { - sql += try " FROM " + source.sourceSQL(db, &arguments) - } + sql += try " FROM " + source.sourceSQL(db, &arguments) - if let whereExpression = try wherePromise.resolve(db) { - sql += " WHERE " + whereExpression.expressionSQL(&arguments) + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&arguments) } if let limit = limit { - let orderings = self.ordering.resolve() + let orderings = self.completeOrdering.resolve() if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") } @@ -136,15 +144,102 @@ struct QueryInterfaceQuery { query.ordering = QueryOrdering() return query } + + // MARK: Join Support + + var completeSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.rightQuery.completeSelection) + } + } + + var completeOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.rightQuery.completeOrdering) + } + } + + var qualifier: SQLTableQualifier? { + return source.qualifier + } + + var allQualifiers: [SQLTableQualifier] { + var qualifiers: [SQLTableQualifier] = [] + if let qualifier = source.qualifier { + qualifiers.append(qualifier) + } + qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) + return qualifiers + } } extension QueryInterfaceQuery { - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + private var preparedQuery: QueryInterfaceQuery { + var query = self + + if !joins.isEmpty { + var qualifier = SQLTableQualifier(tableName: query.source.tableName!) + query.source = source.qualified(with: &qualifier) + } + + if let qualifier = query.qualifier { + query.selection = query.selection.map { $0.qualifiedSelectable(with: qualifier) } + query.filterPromise = query.filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } + query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: qualifier) } + query.ordering = query.ordering.qualified(with: qualifier) + query.havingExpression = query.havingExpression?.qualifiedExpression(with: qualifier) + } + + query.joins = query.joins.map { + var join = $0 + join.rightQuery = join.rightQuery.preparedQuery + return join + } + + query.allQualifiers.resolveAmbiguities() + return query + } + + /// precondition: self is the result of preparedQuery + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { var arguments: StatementArguments? = StatementArguments() - let sql = try self.sql(db, &arguments) + let sql = try preparedQuery.sql(db, &arguments) let statement = try db.makeSelectStatement(sql) try statement.setArgumentsWithValidation(arguments!) - return (statement, nil) + return statement + } + + /// precondition: self is the result of preparedQuery + private func rowAdapter(_ db: Database) throws -> RowAdapter? { + if joins.isEmpty { + return nil + } + + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) + return adapter.addingScopes(scopes) + } + + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + let query = preparedQuery + return try (query.makeSelectStatement(db), query.rowAdapter(db)) } func fetchCount(_ db: Database) throws -> Int { @@ -154,16 +249,14 @@ extension QueryInterfaceQuery { /// The database region that the request looks into. func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let (statement, _) = try prepare(db) + let statement = try preparedQuery.makeSelectStatement(db) let region = statement.fetchedRegion // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard let source = source else { - return region - } - guard case .table(name: let tableName, alias: _) = source else { + guard joins.isEmpty, case .table(tableName: let tableName, qualifier: _) = source else { + // TODO: try harder return region } @@ -174,12 +267,12 @@ extension QueryInterfaceQuery { } // Give up unless there is a where clause - guard let whereExpression = try wherePromise.resolve(db) else { + guard let filter = try filterPromise.resolve(db) else { return region } - // The whereExpression knows better - guard let rowIds = whereExpression.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { return region } @@ -195,12 +288,12 @@ extension QueryInterfaceQuery { return trivialCountQuery } - guard let source = source, case .table = source else { - // SELECT ... FROM (something which is not a table) + guard joins.isEmpty, case .table = source else { + // SELECT ... FROM (something which is not a plain table) return trivialCountQuery } - assert(!selection.isEmpty) + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") if selection.count == 1 { guard let count = self.selection[0].count(distinct: isDistinct) else { return trivialCountQuery @@ -228,59 +321,290 @@ extension QueryInterfaceQuery { // SELECT COUNT(*) FROM (self) private var trivialCountQuery: QueryInterfaceQuery { return QueryInterfaceQuery( - select: [SQLExpressionCount(AllColumns())], - from: .query(query: unorderedQuery, alias: nil)) + source: .query(unorderedQuery), + selection: [SQLExpressionCount(AllColumns())]) } } +extension QueryInterfaceQuery { + func select(_ selection: [SQLSelectable]) -> QueryInterfaceQuery { + var query = self + query.selection = selection + return query + } + + func distinct() -> QueryInterfaceQuery { + var query = self + query.isDistinct = true + return query + } + + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceQuery { + var query = self + query.filterPromise = query.filterPromise.map { (db, filter) in + if let filter = filter { + return try filter && predicate(db) + } else { + return try predicate(db).sqlExpression + } + } + return query + } + + func none() -> QueryInterfaceQuery { + var query = self + query.filterPromise = DatabasePromise(value: false.sqlExpression) + return query + } + + func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery { + var query = self + query.groupByExpressions = expressions.map { $0.sqlExpression } + return query + } + + func having(_ predicate: SQLExpressible) -> QueryInterfaceQuery { + var query = self + if let havingExpression = query.havingExpression { + query.havingExpression = (havingExpression && predicate).sqlExpression + } else { + query.havingExpression = predicate.sqlExpression + } + return query + } + + func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceQuery { + return order(QueryOrdering(orderings: orderings)) + } + + func reversed() -> QueryInterfaceQuery { + return order(ordering.reversed) + } + + private func order(_ ordering: QueryOrdering) -> QueryInterfaceQuery { + var query = self + query.ordering = ordering + return query + } + + func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { + var query = self + query.limit = SQLLimit(limit: limit, offset: offset) + return query + } + + func joining(_ join: AssociationJoin) -> QueryInterfaceQuery { + var query = self + query.joins.append(join) + return query + } + + func qualified(with qualifier: inout SQLTableQualifier) -> QueryInterfaceQuery { + var query = self + query.source = source.qualified(with: &qualifier) + return query + } +} + +extension QueryInterfaceQuery { + init(_ query: AssociationQuery) { + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } +} + +// MARK: - AssociationJoin + +struct AssociationJoin { + var op: AssociationChainOperator + var rightQuery: AssociationQuery + var key: String + var associationMapping: (Database) throws -> AssociationMapping + + func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier) throws -> String { + var sql = "" + switch op { + case .optional: sql += "LEFT JOIN" + case .required: sql += "JOIN" + } + + let rightQualifier = rightQuery.qualifier! + + sql += try " " + rightQuery.source.sourceSQL(db, &arguments) + + let filters = try [ + associationMapping(db)(leftQualifier, rightQualifier), + rightQuery.filterPromise.resolve(db) + ].compactMap { $0 } + if !filters.isEmpty { + sql += " ON " + filters.joined(operator: .and).expressionSQL(&arguments) + } + + for join in rightQuery.joins { + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: rightQualifier) + } + + return sql + } +} + +// MARK: - QueryOrdering + struct QueryOrdering { - private var orderings: [SQLOrderingTerm] + private var elements: [Element] = [] var isReversed: Bool - init(orderings: [SQLOrderingTerm] = [], isReversed: Bool = false) { - self.orderings = orderings + private enum Element { + case orderingTerm(SQLOrderingTerm) + case queryOrdering(QueryOrdering) + + var reversed: Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.reversed) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.reversed) + } + } + + func qualified(with qualifier: SQLTableQualifier) -> Element { + switch self { + case .orderingTerm(let orderingTerm): + return .orderingTerm(orderingTerm.qualifiedOrdering(with: qualifier)) + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.qualified(with: qualifier)) + } + } + + func resolve() -> [SQLOrderingTerm] { + switch self { + case .orderingTerm(let orderingTerm): + return [orderingTerm] + case .queryOrdering(let queryOrdering): + return queryOrdering.resolve() + } + } + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements self.isReversed = isReversed } - func reversed() -> QueryOrdering { + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: [SQLOrderingTerm]) { + self.init( + elements: orderings.map { .orderingTerm($0) }, + isReversed: false) + } + + var reversed: QueryOrdering { return QueryOrdering( - orderings: orderings, + elements: elements, isReversed: !isReversed) } - func appending(ordering: SQLOrderingTerm) -> QueryOrdering { + func qualified(with qualifier: SQLTableQualifier) -> QueryOrdering { return QueryOrdering( - orderings: orderings + [ordering], + elements: elements.map { $0.qualified(with: qualifier) }, + isReversed: isReversed) + } + + func appending(_ ordering: QueryOrdering) -> QueryOrdering { + return QueryOrdering( + elements: elements + [.queryOrdering(ordering)], isReversed: isReversed) } func resolve() -> [SQLOrderingTerm] { if isReversed { - return orderings.map { $0.reversed } + return elements.flatMap { $0.reversed.resolve() } } else { - return orderings + return elements.flatMap { $0.resolve() } } } } -indirect enum SQLSource { - case table(name: String, alias: String?) - case query(query: QueryInterfaceQuery, alias: String?) +// MARK: - SQLSource + +enum SQLSource { + case table(tableName: String, qualifier: SQLTableQualifier?) + indirect case query(QueryInterfaceQuery) - func sourceSQL(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { + var qualifier: SQLTableQualifier? { switch self { - case .table(let table, let alias): - if let alias = alias { - return table.quotedDatabaseIdentifier + " AS " + alias.quotedDatabaseIdentifier + case .table(_, let qualifier): + return qualifier + case .query(let query): + return query.qualifier + } + } + + /// An alias or an actual table name + var qualifiedName: String { + switch self { + case .table(let tableName, let qualifier): + return qualifier?.qualifiedName ?? tableName + case .query(let query): + return query.source.qualifiedName + } + } + + /// An actual table name, not an alias + var tableName: String? { + switch self { + case .table(let tableName, _): + return tableName + case .query(let query): + return query.source.tableName + } + } + + func sourceSQL(_ db: Database,_ arguments: inout StatementArguments?) throws -> String { + switch self { + case .table(let tableName, let qualifier): + if let alias = qualifier?.alias, alias != tableName { + return "\(tableName.quotedDatabaseIdentifier) \(alias.quotedDatabaseIdentifier)" } else { - return table.quotedDatabaseIdentifier + return "\(tableName.quotedDatabaseIdentifier)" } - case .query(let query, let alias): - if let alias = alias { - return try "(" + query.sql(db, &arguments) + ") AS " + alias.quotedDatabaseIdentifier + case .query(let query): + return try "(\(query.sql(db, &arguments)))" + } + } + + func qualified(with qualifier: inout SQLTableQualifier) -> SQLSource { + switch self { + case .table(let tableName, let oldQualifier): + if let oldQualifier = oldQualifier { + qualifier = oldQualifier + return self + } else if let qualifierTableName = qualifier.tableName { + if qualifierTableName == tableName { // TODO: should this test be case-insensitive? + return .table( + tableName: tableName, + qualifier: qualifier) + } else { + // TODO: how to enter this branch? Is it useful? + return self + } } else { - return try "(" + query.sql(db, &arguments) + ")" + qualifier.tableName = tableName + return .table( + tableName: tableName, + qualifier: qualifier) } + case .query(let query): + return .query(query.qualified(with: &qualifier)) } } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift new file mode 100644 index 000000000..296d0bb19 --- /dev/null +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -0,0 +1,139 @@ +extension QueryInterfaceRequest where RowDecoder: TableRecord { + func chain(_ chainOp: AssociationChainOperator, _ association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + let join = AssociationJoin( + op: chainOp, + rightQuery: association.request.query, + key: association.key, + associationMapping: association.associationMapping) + return QueryInterfaceRequest(query: query.joining(join)) + } + + // MARK: - Associations + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public func including(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + return chain(.optional, association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public func including(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + return chain(.required, association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public func joining(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + return chain(.optional, association.select([])) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public func joining(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == RowDecoder + { + return chain(.required, association.select([])) + } +} + +extension Association where LeftAssociated: MutablePersistableRecord { + func request(from record: LeftAssociated) -> QueryInterfaceRequest { + var query = request.query.preparedQuery // make sure query has a qualifier + let qualifier = query.source.qualifier! + let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) + + query = query.filter { db in + let associationMapping = try self.associationMapping(db) + guard let filter = associationMapping(recordQualifier, qualifier) else { + fatalError("Can't request from record without association mapping") + } + let container = PersistenceContainer(record) + return filter.resolvedExpression(inContext: [recordQualifier: container]) + } + + return QueryInterfaceRequest(query: QueryInterfaceQuery(query)) + } +} + +extension MutablePersistableRecord { + /// Creates a request that fetches the associated record(s). + /// + /// For example: + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// let player: Player = ... + /// let request = player.request(for: Player.team) + /// let team = try request.fetchOne(db) // Team? + public func request(for association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return association.request(from: self) + } +} + +extension TableRecord { + + // MARK: - Associations + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association does not + /// require that the associated database table contains a matching row. + public static func including(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().including(optional: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are selected. The returned association requires + /// that the associated database table contains a matching row. + public static func including(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().including(required: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association does not + /// require that the associated database table contains a matching row. + public static func joining(optional association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().joining(optional: association) + } + + /// Creates a request that includes an association. The columns of the + /// associated record are not selected. The returned association requires + /// that the associated database table contains a matching row. + public static func joining(required association: A) + -> QueryInterfaceRequest + where A.LeftAssociated == Self + { + return all().joining(required: association) + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index ac29e72a4..7c3ee6d17 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -56,9 +56,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .select([Column("id")]) /// .select([Column("email")]) public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { - var query = self.query - query.selection = selection - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.select(selection)) } /// Creates a request which returns distinct rows. @@ -71,25 +69,17 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { - var query = self.query - query.isDistinct = true - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.distinct()) } - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM players WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - public func filter(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - if let expression = expression { - return expression && predicate.sqlExpression - } else { - return predicate.sqlExpression - } - }) + /// request = request.filter { db in true } + public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query.filter(predicate)) } /// Creates a request that matches nothing. @@ -98,28 +88,18 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.all() /// request = request.none() public func none() -> QueryInterfaceRequest { - var query = self.query - query.wherePromise = DatabasePromise(value: false.sqlExpression) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.none()) } /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest { - var query = self.query - query.groupByExpressions = expressions.map { $0.sqlExpression } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.group(expressions)) } /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest { - var query = self.query - if let havingExpression = query.havingExpression { - query.havingExpression = (havingExpression && predicate).sqlExpression - } else { - query.havingExpression = predicate.sqlExpression - } - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.having(predicate)) } /// Creates a request with the provided *orderings*. @@ -136,9 +116,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .reversed() /// .order([Column("name")]) public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { - var query = self.query - query.ordering = QueryOrdering(orderings: orderings) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.order(orderings)) } /// Creates a request sorted in reversed order. @@ -147,9 +125,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// var request = Player.all().order(Column("name")) /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { - var query = self.query - query.ordering = query.ordering.reversed() - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.reversed()) } /// Creates a request which fetches *limit* rows, starting at *offset*. @@ -160,127 +136,40 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// /// Any previous limit is replaced. public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { - var query = self.query - query.limit = SQLLimit(limit: limit, offset: offset) - return QueryInterfaceRequest(query: query) + return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) + } + + /// Creates a request that allows you to define unambiguous expressions + /// based on the fetched record. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + let userProvidedAlias = alias.userProvidedAlias + defer { + // Allow user to explicitely rename (TODO: test) + alias.userProvidedAlias = userProvidedAlias + } + return QueryInterfaceRequest(query: query.qualified(with: &alias.qualifier)) } } -extension QueryInterfaceRequest where T: TableRecord { - - // MARK: Request Derivation - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id = 1 - /// var request = Player.all() - /// request = request.filter(key: 1) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: PrimaryKeyType?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM players WHERE id IN (1, 2, 3) - /// var request = Player.all() - /// request = request.filter(keys: [1, 2, 3]) - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: Sequence) -> QueryInterfaceRequest where Sequence.Element: DatabaseValueConvertible { - let keys = Array(keys) - let makePredicate: (Column) -> SQLExpression - switch keys.count { - case 0: - return T.none() - case 1: - makePredicate = { $0 == keys[0] } - default: - makePredicate = { keys.contains($0) } - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let primaryKey = try db.primaryKey(T.databaseTableName) - GRDBPrecondition(primaryKey.columns.count == 1, "Requesting by key requires a single-column primary key in the table \(T.databaseTableName)") - let keysPredicate = makePredicate(Column(primaryKey.columns[0])) - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' - /// var request = Player.all() - /// request = request.filter(key: ["personId": 1, "countryCode": "FR"]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(key: [String: DatabaseValueConvertible?]?) -> QueryInterfaceRequest { - guard let key = key else { - return T.none() - } - - return filter(keys: [key]) - } - - /// Creates a request with the provided primary key *predicate*. - /// - /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... - /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) - /// - /// When executed, this request raises a fatal error if there is no unique - /// index on the key columns. - /// - /// The selection defaults to all columns. This default can be changed for - /// all requests by the `TableRecord.databaseSelection` property, or - /// for individual requests with the `TableRecord.select` method. - public func filter(keys: [[String: DatabaseValueConvertible?]]) -> QueryInterfaceRequest { - guard !keys.isEmpty else { - return T.none() - } - - return QueryInterfaceRequest(query: query.mapWhereExpression { (db, expression) in - let keyPredicates: [SQLExpression] = try keys.map { key in - // Prevent filter(keys: [["foo": 1, "bar": 2]]) where - // ("foo", "bar") is not a unique key (primary key or columns of a - // unique index) - guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: T.databaseTableName) else { - fatalError("table \(T.databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") - } - - let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } - let columnPredicates: [SQLExpression] = key - // Sort key columns in the same order as the unique index - .sorted { (kv1, kv2) in lowercaseOrderedColumns.index(of: kv1.0.lowercased())! < lowercaseOrderedColumns.index(of: kv2.0.lowercased())! } - .map { (column, value) in Column(column) == value } - return columnPredicates.joined(operator: .and) - } - - let keysPredicate = keyPredicates.joined(operator: .or) - - if let expression = expression { - return expression && keysPredicate - } else { - return keysPredicate - } - }) +extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { + // :nodoc: + public var databaseTableName: String { + return T.databaseTableName } } @@ -314,14 +203,14 @@ extension TableRecord { /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { let query = QueryInterfaceQuery( - select: databaseSelection, - from: .table(name: databaseTableName, alias: nil)) + source: .table(tableName: databaseTableName, qualifier: nil), + selection: databaseSelection) return QueryInterfaceRequest(query: query) } /// Creates a request which fetches no record. public static func none() -> QueryInterfaceRequest { - return filter(false) + return all().none() // don't laugh } /// Creates a request which selects *selection*. @@ -476,4 +365,24 @@ extension TableRecord { public static func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest { return all().limit(limit, offset: offset) } + + /// Creates a request that allows you to define unambiguous expressions + /// based on the fetched record. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + return all().aliased(alias) + } } diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 4fa777d9b..84d1ede7c 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -55,13 +55,13 @@ extension SelectionRequest { /// The protocol for all requests that can be filtered. public protocol FilteredRequest { - /// Creates a request with the provided *predicate* added to the + /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM players WHERE 1 /// var request = Player.all() - /// request = request.filter(Column("email") == "arthur@example.com") - func filter(_ predicate: SQLExpressible) -> Self + /// request = request.filter { db in true } + func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self /// Creates a request that matches nothing. /// @@ -72,6 +72,16 @@ public protocol FilteredRequest { } extension FilteredRequest { + /// Creates a request with the provided *predicate* added to the + /// eventual set of already applied predicates. + /// + /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// var request = Player.all() + /// request = request.filter(Column("email") == "arthur@example.com") + public func filter(_ predicate: SQLExpressible) -> Self { + return filter { _ in predicate } + } + /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// @@ -83,6 +93,93 @@ extension FilteredRequest { } } +// MARK: - TableRequest { + +/// The protocol for all requests that feed from a database table +public protocol TableRequest { + var databaseTableName: String { get } +} + +extension TableRequest where Self: FilteredRequest { + + /// Creates a request with the provided primary key *predicate*. + public func filter(key: PrimaryKeyType?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + public func filter(keys: Sequence) -> Self where Sequence.Element: DatabaseValueConvertible { + let keys = Array(keys) + let makePredicate: (Column) -> SQLExpression + switch keys.count { + case 0: + return none() + case 1: + makePredicate = { $0 == keys[0] } + default: + makePredicate = { keys.contains($0) } + } + + let databaseTableName = self.databaseTableName + return filter { db in + let primaryKey = try db.primaryKey(databaseTableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Requesting by key requires a single-column primary key in the table \(databaseTableName)") + return makePredicate(Column(primaryKey.columns[0])) + } + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(key: [String: DatabaseValueConvertible?]?) -> Self { + guard let key = key else { + return none() + } + return filter(keys: [key]) + } + + /// Creates a request with the provided primary key *predicate*. + /// + /// When executed, this request raises a fatal error if there is no unique + /// index on the key columns. + public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self { + guard !keys.isEmpty else { + return none() + } + + let databaseTableName = self.databaseTableName + return filter { db in + try keys + .map { key in + // Prevent filter(keys: [["foo": 1, "bar": 2]]) where + // ("foo", "bar") is not a unique key (primary key or columns of a + // unique index) + guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { + fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") + } + + let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } + return key + // Sort key columns in the same order as the unique index + .sorted { (kv1, kv2) in + let index1 = lowercaseOrderedColumns.index(of: kv1.key.lowercased())! + let index2 = lowercaseOrderedColumns.index(of: kv2.key.lowercased())! + return index1 < index2 + } + .map { (column, value) in Column(column) == value } + .joined(operator: .and) + } + .joined(operator: .or) + } + } +} + // MARK: - AggregatingRequest /// The protocol for all requests that can aggregate. diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 3266580c0..b976014b6 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -61,4 +61,10 @@ extension SQLCollatedExpression : SQLOrderingTerm { public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { return sqlExpression.orderingTermSQL(&arguments) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + return SQLCollatedExpression(expression.qualifiedExpression(with: qualifier), collationName: collationName) + } } diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index a7a7f8dcc..3248c9963 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -87,6 +87,12 @@ public struct SQLExpressionLiteral : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return self } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionUnary @@ -174,6 +180,12 @@ public struct SQLExpressionUnary : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionUnary(op, expression.qualifiedExpression(with: qualifier)) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context)) + } } // MARK: - SQLExpressionBinary @@ -322,6 +334,12 @@ public struct SQLExpressionBinary : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionBinary(op, lhs.qualifiedExpression(with: qualifier), rhs.qualifiedExpression(with: qualifier)) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) + } } // MARK: - SQLExpressionAnd @@ -349,6 +367,10 @@ struct SQLExpressionAnd : SQLExpression { return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) } + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) }) + } + func matchedRowIds(rowIdName: String?) -> Set? { let matchedRowIds = expressions.compactMap { $0.matchedRowIds(rowIdName: rowIdName) @@ -385,6 +407,10 @@ struct SQLExpressionOr : SQLExpression { return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) } + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) }) + } + func matchedRowIds(rowIdName: String?) -> Set? { if expressions.isEmpty { return [] @@ -462,6 +488,10 @@ struct SQLExpressionContains : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionContains(expression.qualifiedExpression(with: qualifier), collection, negated: isNegated) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) + } } // MARK: - SQLExpressionBetween @@ -505,6 +535,14 @@ struct SQLExpressionBetween : SQLExpression { upperBound.qualifiedExpression(with: qualifier), negated: isNegated) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionBetween( + expression.resolvedExpression(inContext: context), + lowerBound.resolvedExpression(inContext: context), + upperBound.resolvedExpression(inContext: context), + negated: isNegated) + } } // MARK: - SQLExpressionFunction @@ -599,6 +637,12 @@ public struct SQLExpressionFunction : SQLExpression { public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: qualifier) }) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// :nodoc: + public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) }) + } } // MARK: - SQLExpressionCount @@ -622,6 +666,10 @@ struct SQLExpressionCount : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCount(counted.qualifiedSelectable(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionCountDistinct @@ -644,6 +692,10 @@ struct SQLExpressionCountDistinct : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCountDistinct(counted.qualifiedExpression(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return self + } } // MARK: - SQLExpressionCollate @@ -673,4 +725,8 @@ struct SQLExpressionCollate : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionCollate(expression.qualifiedExpression(with: qualifier), collationName: collationName) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName) + } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index b41be52db..8f8ddecd1 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -63,6 +63,9 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -96,6 +99,15 @@ extension SQLExpression { public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { return qualifiedExpression(with: qualifier) } + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + /// + /// The default implementation returns qualifiedExpression(with:) + /// + /// :nodoc: + public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + return qualifiedExpression(with: qualifier) + } } // SQLExpression: SQLExpressible @@ -150,4 +162,8 @@ struct SQLExpressionNot : SQLExpression { func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { return SQLExpressionNot(expression.qualifiedExpression(with: qualifier)) } + + func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + return SQLExpressionNot(expression.resolvedExpression(inContext: context)) + } } diff --git a/GRDB/QueryInterface/SQLOrdering.swift b/GRDB/QueryInterface/SQLOrdering.swift index e3e8624ba..fec103e3f 100644 --- a/GRDB/QueryInterface/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQLOrdering.swift @@ -31,6 +31,9 @@ public protocol SQLOrderingTerm { /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, ?)" /// arguments // ["Anonymous"] func orderingTermSQL(_ arguments: inout StatementArguments?) -> String + + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm } // MARK: - SQLOrdering @@ -56,4 +59,13 @@ enum SQLOrdering : SQLOrderingTerm { return expression.expressionSQL(&arguments) + " DESC" } } + + func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + switch self { + case .asc(let expression): + return SQLOrdering.asc(expression.qualifiedExpression(with: qualifier)) + case .desc(let expression): + return SQLOrdering.desc(expression.qualifiedExpression(with: qualifier)) + } + } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 0e45abddd..4e5b17664 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -71,7 +71,7 @@ struct QualifiedAllColumns { extension QualifiedAllColumns : SQLSelectable { func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.name { + if let qualifierName = qualifier.qualifiedName { return qualifierName.quotedDatabaseIdentifier + ".*" } return "*" @@ -92,7 +92,8 @@ extension QualifiedAllColumns : SQLSelectable { } func columnCount(_ db: Database) throws -> Int { - return try db.columns(in: qualifier.tableName).count + assert(qualifier.tableName != nil, "Missing table name") + return try db.columns(in: qualifier.tableName!).count } } diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 48dd59720..0c0e48476 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -63,22 +63,147 @@ struct SQLSelectionLiteral : SQLSelectable { } } +// MARK: - TableAlias + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +public final class TableAlias { + var qualifier: SQLTableQualifier + + public init(name: String? = nil) { + self.qualifier = SQLTableQualifier(tableName: nil, userProvidedAlias: name) + } + + var userProvidedAlias: String? { + get { return qualifier.userProvidedAlias } + set { + // TODO: test + if let value = newValue { + qualifier.alias = value + qualifier.isUserProvided = true + } else { + qualifier.isUserProvided = false + } + } + } + + /// Returns a qualified value that is able to resolve ambiguities in + /// joined queries. + public subscript(_ selectable: SQLSelectable) -> SQLSelectable { + return selectable.qualifiedSelectable(with: qualifier) + } + + /// Returns a qualified expression that is able to resolve ambiguities in + /// joined queries. + public subscript(_ expression: SQLExpression) -> SQLExpression { + return expression.qualifiedExpression(with: qualifier) + } +} + // MARK: - SQLTableQualifier /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// :nodoc: -public class SQLTableQualifier { - var tableName: String - private var alias: String? - - init(tableName: String, alias: String?) { +public class SQLTableQualifier: Hashable { + var tableName: String? + var alias: String? + var isUserProvided: Bool + + init(tableName: String? = nil, userProvidedAlias: String? = nil) { self.tableName = tableName - self.alias = alias + self.alias = userProvidedAlias + self.isUserProvided = (userProvidedAlias != nil) } - var name: String? { - return alias + var qualifiedName: String? { + return alias ?? tableName + } + + var userProvidedAlias: String? { + return isUserProvided ? alias : nil + } + + /// :nodoc: + public var hashValue: Int { + return ObjectIdentifier(self).hashValue + } + + /// :nodoc: + public static func == (lhs: SQLTableQualifier, rhs: SQLTableQualifier) -> Bool { + return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) + } +} + +extension Array where Element == SQLTableQualifier { + /// Resolve ambiguities in qualifiers' names. + /// + /// Precondition: all qualifiers have a non-nil qualifiedName: + /// + /// var qualifier = SQLTableQualifier() // nil qualifiedName + /// let query = query.qualified(by: &leftQualifier) + /// // Now qualifier is guaranteed to have a non-nil qualifiedName. + func resolveAmbiguities() { + // Special case + guard let first = first else { + return + } + + // Special case for single qualifier: don't output any column name + if count == 1 { + if !first.isUserProvided { + first.alias = nil + first.tableName = nil + } + return + } + + // It is a programmer error to reuse the same (===) TableAlias for + // multiple tables. + GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") + + // Group qualifiers by lowercase name + let groups = Dictionary.init(grouping: self) { $0.qualifiedName!.lowercased() } + + var uniqueLowercaseNames: Set = [] + var ambiguousGroups: [[SQLTableQualifier]] = [] + + for (lowercaseName, group) in groups { + if group.count > 1 { + // It is a programmer error to reuse the same alias for multiple tables + GRDBPrecondition(group.filter({ $0.isUserProvided }).count < 2, "ambiguous alias: \(group[0].qualifiedName!)") + ambiguousGroups.append(group) + } else { + uniqueLowercaseNames.insert(lowercaseName) + } + } + + for group in ambiguousGroups { + var index = 1 + for qualifier in group { + if qualifier.isUserProvided { continue } + let radical = qualifier.qualifiedName!.databaseQualifierRadical + var alias: String + repeat { + alias = "\(radical)\(index)" + index += 1 + } while uniqueLowercaseNames.contains(alias.lowercased()) + uniqueLowercaseNames.insert(alias.lowercased()) + qualifier.alias = alias + } + } + } +} + +extension String { + /// "foo12" => "foo" + var databaseQualifierRadical: String { + let digits: ClosedRange = "0"..."9" + let radicalEndIndex = self // "foo12" + .reversed() // "21oof" + .prefix(while: { digits.contains($0) }) // "21" + .endIndex // reversed(foo^12) + .base // foo^12 + return String(prefix(upTo: radicalEndIndex)) } } diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 389035274..96a3f82b1 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -126,6 +126,15 @@ public struct PersistenceContainer { } } + // Returns nil if column is not defined + func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? { + let lowercaseColumn = column.lowercased() + for (key, value) in storage where key.lowercased() == lowercaseColumn { + return value?.databaseValue ?? .null + } + return nil + } + var isEmpty: Bool { return storage.isEmpty } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index db1483e0c..d1c4d424c 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -86,7 +86,7 @@ extension TableRecord { /// // SELECT "p".* FROM players AS p /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" public static func selectionSQL(alias: String? = nil) -> String { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: alias ?? databaseTableName) + let qualifier = SQLTableQualifier(tableName: databaseTableName, userProvidedAlias: alias) let selection = databaseSelection.map { $0.qualifiedSelectable(with: qualifier) } var arguments: StatementArguments? = nil return selection @@ -113,10 +113,9 @@ extension TableRecord { /// try Player.numberOfSelectedColumns(db) /// } public static func numberOfSelectedColumns(_ db: Database) throws -> Int { - let qualifier = SQLTableQualifier(tableName: databaseTableName, alias: nil) + let qualifier = SQLTableQualifier(tableName: databaseTableName) return try databaseSelection .map { try $0.qualifiedSelectable(with: qualifier).columnCount(db) } .reduce(0, +) } } - diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 1f5d77772..8b911d1ec 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -195,6 +195,82 @@ 564F9C241F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; + 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */; }; + 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; + 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */; }; + 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; + 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8720961FBF00F46237 /* AssociationQuery.swift */; }; + 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; + 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */; }; + 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; + 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8920961FBF00F46237 /* ForeignKey.swift */; }; + 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */; }; + 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; + 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; + 5653EB9D20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; + 5653EB9E20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; + 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; + 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */; }; + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -885,6 +961,30 @@ 564E73EB203DA29B000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB8720961FBF00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EB8920961FBF00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EB8C20961FBF00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1317,6 +1417,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EBA420961FD300F46237 /* Association */, 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1333,11 +1434,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB8420961FBF00F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1368,6 +1471,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB8420961FBF00F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, + 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, + 5653EB8920961FBF00F46237 /* ForeignKey.swift */, + 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, + 5653EB8C20961FBF00F46237 /* Association.swift */, + 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EBA420961FD300F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EBA920961FE700F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EBB020961FE700F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EBAE20961FE700F46237 /* AssociationChainRowScopesTests.swift */, + 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */, + 5653EBAD20961FE700F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EBAB20961FE700F46237 /* AssociationHasOneSQLTests.swift */, + 5653EBA820961FE600F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EBAF20961FE700F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */, + 5653EBAC20961FE700F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EBAA20961FE700F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1996,15 +2136,18 @@ 56BB6EAA1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910A1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91241FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB9B20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5121EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4911EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842920413D6F00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F21EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 560FC51C1CB003810014AA8E /* QueryInterfaceRequest.swift in Sources */, 560FC51D1CB003810014AA8E /* SQLCollatedExpression.swift in Sources */, + 5653EB9920961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91341FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215B1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D41D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9120961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5621EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD361DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2020,6 +2163,7 @@ 5698AC381D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -2027,6 +2171,7 @@ 567404891CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */, 560FC5241CB003810014AA8E /* DatabaseWriter.swift in Sources */, + 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD191DAAD17B0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7641E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B21DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2053,6 +2198,8 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, + 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */, + 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2071,7 +2218,9 @@ 566AD8B31D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD221DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 560FC53C1CB003810014AA8E /* DatabaseQueue.swift in Sources */, + 5653EB9720961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9520961FC000F46237 /* HasManyAssociation.swift in Sources */, 560FC53D1CB003810014AA8E /* NSNumber.swift in Sources */, 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, @@ -2079,6 +2228,7 @@ 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9D20961FC000F46237 /* Association.swift in Sources */, 5657AABA1D107001006283EF /* NSData.swift in Sources */, 560FC5421CB003810014AA8E /* StatementColumnConvertible.swift in Sources */, 56CEB5541EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2097,6 +2247,7 @@ 5698ACD81DA925420056AF8C /* RowTestCase.swift in Sources */, 56A8C2411D1918EE0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 562EA8301F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC020961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206031E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 5657AB571D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448841EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2115,6 +2266,7 @@ 562393191DECC02000A6B01F /* RowFetchTests.swift in Sources */, 560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */, 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, + 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, @@ -2123,11 +2275,14 @@ 56B021CA1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, 562205F61E420E48005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 560FC5741CB00B880014AA8E /* DatabasePoolFunctionTests.swift in Sources */, + 5653EBDC20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 560FC5761CB00B880014AA8E /* RowCopiedFromStatementTests.swift in Sources */, 560FC5771CB00B880014AA8E /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCC20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756441E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AF746C1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56B14E801D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, + 5653EBE420961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206051E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206041E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C611EACCCC7000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2155,6 +2310,7 @@ 560FC57F1CB00B880014AA8E /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5698ACB71DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 5672DE5A1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE820961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C601EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73EF203DA2A2000C443C /* JoinSupportTests.swift in Sources */, 5674A7111F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2165,8 +2321,10 @@ 567E55ED1D2BDD3D00CC6F79 /* EncryptionTests.swift in Sources */, 56741EA91E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C641EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 560FC5841CB00B880014AA8E /* PersistableRecordTests.swift in Sources */, 560FC5871CB00B880014AA8E /* RecordSubClassTests.swift in Sources */, + 5653EBBC20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 560FC5891CB00B880014AA8E /* TransactionObserverTests.swift in Sources */, 5674A72C1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 56C3F7541CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, @@ -2179,8 +2337,10 @@ 56071A4E1DB54ED200CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 56A4CDB11D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 567156141CB141D0007DC145 /* DatabaseQueueInMemoryTests.swift in Sources */, + 5653EBEC20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 560FC58E1CB00B880014AA8E /* RecordPrimaryKeyRowIDTests.swift in Sources */, 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, + 5653EBD020961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2188,9 +2348,12 @@ 560FC5921CB00B880014AA8E /* FetchableRecordTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5657AB371D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD820961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 560FC5941CB00B880014AA8E /* DatabaseValueConvertibleSubclassTests.swift in Sources */, + 5653EBC820961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 565EFAEF1D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, 560FC5961CB00B880014AA8E /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EBC420961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 560FC5971CB00B880014AA8E /* DatabaseErrorTests.swift in Sources */, 560FC5991CB00B880014AA8E /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 564F9C1F1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2222,6 +2385,7 @@ 5698AC8A1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC041D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 5690C3381D23E7D200E59934 /* FoundationDateTests.swift in Sources */, + 5653EBD420961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF811E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060B1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F41E420E48005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2244,6 +2408,7 @@ 5698ACD91DA925420056AF8C /* RowTestCase.swift in Sources */, 567156221CB16729007DC145 /* StatementColumnConvertibleFetchTests.swift in Sources */, 562EA8311F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC120961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 562206001E420EA3005860AC /* DatabasePoolBackupTests.swift in Sources */, 567156231CB16729007DC145 /* RecordPrimaryKeyNoneTests.swift in Sources */, 564448851EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2262,6 +2427,7 @@ 5623931A1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */, 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, + 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, @@ -2270,11 +2436,14 @@ 56B14E811D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 562205F91E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */, 566AD8C81D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EBDD20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 567156321CB16729007DC145 /* DatabasePoolFunctionTests.swift in Sources */, 567156341CB16729007DC145 /* RowCopiedFromStatementTests.swift in Sources */, + 5653EBCD20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756451E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 56AF746D1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, + 5653EBE520961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 562206021E420EA3005860AC /* DatabasePoolReadOnlyTests.swift in Sources */, 562206011E420EA3005860AC /* DatabasePoolConcurrencyTests.swift in Sources */, 56176C671EACCCC8000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2302,6 +2471,7 @@ 5671563F1CB16729007DC145 /* RecordCopyTests.swift in Sources */, 5698ACB81DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, 567156401CB16729007DC145 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, + 5653EBE920961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56176C661EACCCC8000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F0203DA2A3000C443C /* JoinSupportTests.swift in Sources */, 5674A7131F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2312,8 +2482,10 @@ 5690C3391D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 56741EAA1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, 56176C6A1EACCCC8000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, + 5653EBB920961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 567156461CB16729007DC145 /* TransactionObserverTests.swift in Sources */, 567A80551D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBBD20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 567156481CB16729007DC145 /* DatabaseValueTests.swift in Sources */, 5674A72E1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, 5671564A1CB16729007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */, @@ -2326,8 +2498,10 @@ 56071A4F1DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, 5671564D1CB16729007DC145 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 5671564E1CB16729007DC145 /* DatabaseReaderTests.swift in Sources */, + 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5671564F1CB16729007DC145 /* RecordEditedTests.swift in Sources */, 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EBD120961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 567156511CB16729007DC145 /* FetchableRecordTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2335,9 +2509,12 @@ 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A5EF111EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, 5690C3281D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, + 5653EBD920961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5657AB381D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBC920961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 561667031D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift in Sources */, 565EFAF01D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */, + 5653EBC520961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 567156551CB16729007DC145 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 567156561CB16729007DC145 /* DatabaseErrorTests.swift in Sources */, 564F9C201F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2369,6 +2546,7 @@ 5698AC8B1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, 5698AC051D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 567156621CB16729007DC145 /* CGFloatTests.swift in Sources */, + 5653EBD520961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF821E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 5622060A1E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */, 562205F71E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */, @@ -2391,15 +2569,18 @@ 56BB6EAD1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, 566B910D1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91271FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */, 56CEB5151EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4941EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842A20413D8500E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F51EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56AFC9F11CB1A8BB00F48B96 /* QueryInterfaceRequest.swift in Sources */, 56AFC9F21CB1A8BB00F48B96 /* SQLCollatedExpression.swift in Sources */, + 5653EB9A20961FC000F46237 /* ForeignKeyRequest.swift in Sources */, 566B91371FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215E1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D71D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB9220961FC000F46237 /* HasOneAssociation.swift in Sources */, 56CEB5651EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FE1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -2415,6 +2596,7 @@ 5698AC3B1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -2422,6 +2604,7 @@ 5674048B1CEF84C8003ED5CC /* RowAdapter.swift in Sources */, 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */, 56AFC9F91CB1A8BB00F48B96 /* DatabaseWriter.swift in Sources */, + 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, 5698AD1A1DAAD17C0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, 56B964B51DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, @@ -2448,6 +2631,8 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, + 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */, + 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, @@ -2466,7 +2651,9 @@ 566AD8B61D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD251DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, 56AFCA121CB1A8BB00F48B96 /* NSNumber.swift in Sources */, + 5653EB9820961FC000F46237 /* ForeignKey.swift in Sources */, 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB9620961FC000F46237 /* HasManyAssociation.swift in Sources */, 56AFCA141CB1A8BB00F48B96 /* StandardLibrary.swift in Sources */, 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, @@ -2474,6 +2661,7 @@ 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB9E20961FC000F46237 /* Association.swift in Sources */, 56AFCA181CB1A8BB00F48B96 /* FetchedRecordsController.swift in Sources */, 56AFCA191CB1A8BB00F48B96 /* DatabaseValue.swift in Sources */, 56CEB5571EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2492,6 +2680,7 @@ 56AFCA311CB1AA9900F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA321CB1AA9900F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8341F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC220961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD31DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA331CB1AA9900F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448881EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2510,6 +2699,7 @@ 56AFCA3B1CB1AA9900F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, + 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, @@ -2518,11 +2708,14 @@ 56AFCA441CB1AA9900F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 562393351DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDE20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDC1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA451CB1AA9900F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 5653EBCE20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756481E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA461CB1AA9900F48B96 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 56AFCA471CB1AA9900F48B96 /* RowFromStatementTests.swift in Sources */, + 5653EBE620961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */, 5672DE6B1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, 56176C731EACCCCA000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2550,6 +2743,7 @@ 56AFCA521CB1AA9900F48B96 /* PersistableRecordTests.swift in Sources */, 56AFCA531CB1AA9900F48B96 /* DatabaseValueConversionTests.swift in Sources */, 5657AB531D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 5653EBEA20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9B1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C721EACCCCA000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F1203DA2A3000C443C /* JoinSupportTests.swift in Sources */, @@ -2560,8 +2754,10 @@ 56AFCA561CB1AA9900F48B96 /* DatabasePoolConcurrencyTests.swift in Sources */, 56AFCA571CB1AA9900F48B96 /* TransactionObserverTests.swift in Sources */, 56741EAD1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBA20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C761EACCCCA000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5623935C1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, + 5653EBBE20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC851DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5698AC451DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 5674A72B1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2574,8 +2770,10 @@ 56A4CDB51D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56AFCA5B1CB1AA9900F48B96 /* DatabaseValueTests.swift in Sources */, 56AFCA5C1CB1AA9900F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, + 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCA5D1CB1AA9900F48B96 /* DatabaseReaderTests.swift in Sources */, 56A8C2491D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EBD220961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 56AFCA5E1CB1AA9900F48B96 /* FetchableRecordTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, @@ -2583,9 +2781,12 @@ 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */, 56AFCA621CB1AA9900F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 56A5EF141EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDA20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931D1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCA20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCA631CB1AA9900F48B96 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5698AC8E1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC620961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCA641CB1AA9900F48B96 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A8C24A1D1918F10096E9D4 /* FoundationUUIDTests.swift in Sources */, 56AFCA651CB1AA9900F48B96 /* DatabaseErrorTests.swift in Sources */, @@ -2617,6 +2818,7 @@ 56AFCA731CB1AA9900F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCA741CB1AA9900F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 567A80581D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, + 5653EBD620961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF851E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AFCA751CB1AA9900F48B96 /* CGFloatTests.swift in Sources */, 562393531DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, @@ -2639,6 +2841,7 @@ 56AFCA8A1CB1ABC800F48B96 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56AFCA8B1CB1ABC800F48B96 /* DatabaseQueueConcurrencyTests.swift in Sources */, 562EA8351F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EBC320961FE800F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 5698ACD41DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 56AFCA8C1CB1ABC800F48B96 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 564448891EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2657,6 +2860,7 @@ 56AFCA911CB1ABC800F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */, 56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */, 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, + 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, @@ -2665,11 +2869,14 @@ 5657AB5C1D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 56AFCA981CB1ABC800F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 562393361DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 5653EBDF20961FE800F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698ACDD1DA925430056AF8C /* RowTestCase.swift in Sources */, 56AFCA9A1CB1ABC800F48B96 /* StatementColumnConvertibleTests.swift in Sources */, + 5653EBCF20961FE800F46237 /* AssociationHasOneSQLTests.swift in Sources */, 562756491E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56AFCA9B1CB1ABC800F48B96 /* DatabasePoolFunctionTests.swift in Sources */, 5672DE5E1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, + 5653EBE720961FE800F46237 /* AssociationChainSQLTests.swift in Sources */, 56AFCA9D1CB1ABC800F48B96 /* RowCopiedFromStatementTests.swift in Sources */, 56AFCA9E1CB1ABC800F48B96 /* DatabaseQueueSchemaCacheTests.swift in Sources */, 56176C791EACCCCB000F3F2B /* FTS5RecordTests.swift in Sources */, @@ -2697,6 +2904,7 @@ 56A8C24B1D1918F10096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 56AFCAAB1CB1ABC800F48B96 /* PersistableRecordTests.swift in Sources */, 56FF45461D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */, + 5653EBEB20961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5698AC9C1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56176C781EACCCCB000F3F2B /* FTS5PatternTests.swift in Sources */, 564E73F2203DA2A4000C443C /* JoinSupportTests.swift in Sources */, @@ -2707,8 +2915,10 @@ 5657AB441D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 5623935D1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56741EAE1E66A8B3003E422D /* FetchRequestTests.swift in Sources */, + 5653EBBB20961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */, 56176C7C1EACCCCB000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */, 5698AC861DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 5653EBBF20961FE800F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC461DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 56AF74711D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 5674A7281F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2721,8 +2931,10 @@ 56A4CDB61D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 5657AB4C1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 56AFCAB31CB1ABC800F48B96 /* RecordSubClassTests.swift in Sources */, + 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 56AFCAB41CB1ABC800F48B96 /* DatabaseValueTests.swift in Sources */, 5657AB3C1D108BA9006283EF /* FoundationDataTests.swift in Sources */, + 5653EBD320961FE800F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, @@ -2730,9 +2942,12 @@ 56AFCAB71CB1ABC800F48B96 /* FetchableRecordTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, + 5653EBDB20961FE800F46237 /* AssociationChainRowScopesTests.swift in Sources */, 5623931E1DECC02000A6B01F /* RowFetchTests.swift in Sources */, + 5653EBCB20961FE800F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, 56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AC8F1DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 5653EBC720961FE800F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, 56AFCAB91CB1ABC800F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */, 56AFCABB1CB1ABC800F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, @@ -2764,6 +2979,7 @@ 56AFCACC1CB1ABC800F48B96 /* DatabaseQueueInMemoryTests.swift in Sources */, 56AFCACD1CB1ABC800F48B96 /* RecordWithColumnNameManglingTests.swift in Sources */, 56AFCACE1CB1ABC800F48B96 /* CGFloatTests.swift in Sources */, + 5653EBD720961FE800F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, 6340BF861E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 567A80591D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 562393541DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index ecf88c2b8..9f2aa8291 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -51,6 +51,54 @@ 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */; }; 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */; }; + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; + 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */; }; + 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; + 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3820961F6000F46237 /* HasOneAssociation.swift */; }; + 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; + 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3920961F6000F46237 /* AssociationQuery.swift */; }; + 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; + 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */; }; + 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; + 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3B20961F6000F46237 /* ForeignKey.swift */; }; + 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; + 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */; }; + 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; + 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; + 5653EB4F20961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; + 5653EB5020961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; + 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; + 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */; }; + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */; }; + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */; }; + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */; }; + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */; }; + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */; }; + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */; }; + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */; }; + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */; }; + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */; }; + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */; }; + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -586,6 +634,30 @@ 564E73E7203DA278000C443C /* JoinSupportTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JoinSupportTests.swift; sourceTree = ""; }; 564F9C1D1F069B4E00877A00 /* DatabaseAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAggregateTests.swift; sourceTree = ""; }; 564F9C2C1F075DD200877A00 /* DatabaseFunction.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunction.swift; sourceTree = ""; }; + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BelongsToAssociation.swift; sourceTree = ""; }; + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; + 5653EB3920961F6000F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; + 5653EB3B20961F6000F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; + 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; + 5653EB3E20961F6100F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; + 5653EB3F20961F6100F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelDecodableRecordTests.swift; sourceTree = ""; }; + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationTableAliasTestsSQLTests.swift; sourceTree = ""; }; + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLTests.swift; sourceTree = ""; }; + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRowScopeSearchTests.swift; sourceTree = ""; }; + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneSQLDerivationTests.swift; sourceTree = ""; }; + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainRowScopesTests.swift; sourceTree = ""; }; + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelRowScopesTests.swift; sourceTree = ""; }; + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = ""; }; + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; + 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; + 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -991,6 +1063,7 @@ 56300B5C1C53C38F005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, @@ -1007,11 +1080,13 @@ 56300B6D1C53F592005A543B /* QueryInterface */ = { isa = PBXGroup; children = ( + 5653EB3620961F6000F46237 /* Association */, 56CEB5401EAA359A00BFAF62 /* Column.swift */, 56CEB5101EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift */, 56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */, 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, + 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1042,6 +1117,43 @@ name = DatabaseQueue; sourceTree = ""; }; + 5653EB3620961F6000F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, + 5653EB3920961F6000F46237 /* AssociationQuery.swift */, + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, + 5653EB3B20961F6000F46237 /* ForeignKey.swift */, + 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, + 5653EB3E20961F6100F46237 /* Association.swift */, + 5653EB3F20961F6100F46237 /* AssociationMapping.swift */, + ); + path = Association; + sourceTree = ""; + }; + 5653EB5620961F8900F46237 /* Association */ = { + isa = PBXGroup; + children = ( + 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */, + 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */, + 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */, + 5653EB5B20961FB100F46237 /* AssociationBelongsToSQLDerivationTests.swift */, + 5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */, + 5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */, + 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */, + 5653EB5F20961FB100F46237 /* AssociationHasOneSQLDerivationTests.swift */, + 5653EB5D20961FB100F46237 /* AssociationHasOneSQLTests.swift */, + 5653EB5A20961FB100F46237 /* AssociationParallelDecodableRecordTests.swift */, + 5653EB6120961FB100F46237 /* AssociationParallelRowScopesTests.swift */, + 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */, + 5653EB5E20961FB100F46237 /* AssociationRowScopeSearchTests.swift */, + 5653EB5C20961FB100F46237 /* AssociationTableAliasTestsSQLTests.swift */, + ); + name = Association; + sourceTree = ""; + }; 5659F4861EA8D94E004A4992 /* Utils */ = { isa = PBXGroup; children = ( @@ -1699,15 +1811,18 @@ F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */, 566B910E1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91281FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5161EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4951EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842E20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4C20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215F1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D81D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4420961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5661EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1723,6 +1838,7 @@ F3BA80101CFB2876003DC1BA /* DatabaseReader.swift in Sources */, 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -1730,6 +1846,7 @@ 566475D11D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759F1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA802B1CFB289B003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD171DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7681E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -1756,6 +1873,8 @@ F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, + 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */, + 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA80231CFB288C003DC1BA /* NSString.swift in Sources */, @@ -1774,7 +1893,9 @@ 566AD8B71D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA802C1CFB289B003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4A20961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4820961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA80301CFB289F003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, @@ -1782,6 +1903,7 @@ 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB5020961F6100F46237 /* Association.swift in Sources */, F3BA800E1CFB2876003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80191CFB2876003DC1BA /* Statement.swift in Sources */, 56CEB5581EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -1800,6 +1922,7 @@ F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */, F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 562EA8361F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6D20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, F3BA80DD1CFB300E003DC1BA /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 5644488A1EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, F3BA80521CFB2B59003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, @@ -1818,6 +1941,7 @@ F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, F3BA81221CFB3063003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, + 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, @@ -1826,11 +1950,14 @@ 5623935E1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */, 566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, + 5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, 5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */, + 5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80CF1CFB2FEA003DC1BA /* SchedulingWatchdogTests.swift in Sources */, F3BA80E71CFB3016003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA812A1CFB3063003DC1BA /* RecordSubClassTests.swift in Sources */, + 5653EB7F20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, 6340BF871E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, 56AF74721D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, F3BA80D21CFB2FF3003DC1BA /* PersistableRecordTests.swift in Sources */, @@ -1858,6 +1985,7 @@ F3BA81151CFB305E003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA80DC1CFB300E003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, 5698AD021DAA8ACB0056AF8C /* FTS5CustomTokenizerTests.swift in Sources */, + 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56B964CA1DA521450002DA19 /* FTS5PatternTests.swift in Sources */, 564E73F4203DA2AD000C443C /* JoinSupportTests.swift in Sources */, 5674A70E1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -1868,8 +1996,10 @@ F3BA80F11CFB3019003DC1BA /* DatabaseSavepointTests.swift in Sources */, 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, F3BA81031CFB303D003DC1BA /* FetchedRecordsControllerTests.swift in Sources */, + 5653EB6920961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80B71CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, 5698ACCC1DA62A2D0056AF8C /* FTS5TokenizerTests.swift in Sources */, + 5653EB6B20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5690C33E1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, 5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -1882,8 +2012,10 @@ F3BA80BD1CFB2FD1003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, F3BA81261CFB3063003DC1BA /* RecordCopyTests.swift in Sources */, 56A8C24D1D1918F30096E9D4 /* FoundationNSUUIDTests.swift in Sources */, + 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, 5698AC471DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, + 5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -1891,9 +2023,12 @@ F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80DA1CFB300E003DC1BA /* DatabaseTimestampTests.swift in Sources */, + 5653EB7920961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA81201CFB3063003DC1BA /* RecordPrimaryKeyMultipleTests.swift in Sources */, + 5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */, 5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, + 5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */, 56A8C24E1D1918F30096E9D4 /* FoundationUUIDTests.swift in Sources */, 564F9C251F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -1925,6 +2060,7 @@ F3BA80501CFB2B59003DC1BA /* DatabasePoolSchemaCacheTests.swift in Sources */, F3BA80BB1CFB2FD1003DC1BA /* DatabasePoolConcurrencyTests.swift in Sources */, F3BA81141CFB305E003DC1BA /* QueryInterfaceRequestTests.swift in Sources */, + 5653EB7720961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA81271CFB3063003DC1BA /* RecordEditedTests.swift in Sources */, 56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, F3BA80C51CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, @@ -1947,15 +2083,18 @@ F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */, 566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */, 566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */, + 5653EB4D20961F6100F46237 /* AssociationRequest.swift in Sources */, 56CEB5131EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */, F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */, + 5653EB4B20961F6100F46237 /* ForeignKeyRequest.swift in Sources */, 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */, 56D1215C1ED34978001347D2 /* Fixits-0.109.0.swift in Sources */, 566475D51D981D5E00FF74B8 /* SQLOperators.swift in Sources */, + 5653EB4320961F6100F46237 /* HasOneAssociation.swift in Sources */, 56CEB5631EAA359A00BFAF62 /* SQLSelectable.swift in Sources */, 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */, 5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */, @@ -1971,6 +2110,7 @@ F3BA806C1CFB2E55003DC1BA /* DatabaseReader.swift in Sources */, 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, + 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */, 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, @@ -1978,6 +2118,7 @@ 566475CE1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */, 5664759C1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */, + 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */, F3BA80871CFB2E70003DC1BA /* QueryInterfaceRequest.swift in Sources */, 5698AD161DAAD16F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56F3E7651E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */, @@ -2004,6 +2145,8 @@ F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, + 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */, + 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */, @@ -2022,7 +2165,9 @@ 566AD8B41D5318F4002EC1A8 /* TableDefinition.swift in Sources */, 5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */, F3BA80881CFB2E70003DC1BA /* SQLCollatedExpression.swift in Sources */, + 5653EB4920961F6100F46237 /* ForeignKey.swift in Sources */, 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */, + 5653EB4720961F6100F46237 /* HasManyAssociation.swift in Sources */, F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */, F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, @@ -2030,6 +2175,7 @@ 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, + 5653EB4F20961F6100F46237 /* Association.swift in Sources */, F3BA806A1CFB2E55003DC1BA /* DatabaseQueue.swift in Sources */, F3BA80751CFB2E55003DC1BA /* Statement.swift in Sources */, 56CEB5551EAA359A00BFAF62 /* SQLExpression.swift in Sources */, @@ -2048,6 +2194,7 @@ F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */, 5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */, + 5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */, 56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */, 5657AB591D108BA9006283EF /* FoundationNSStringTests.swift in Sources */, 564448861EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */, @@ -2066,6 +2213,7 @@ 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */, F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, + 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, @@ -2074,11 +2222,14 @@ 567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */, F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */, + 5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */, F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */, + 5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */, F3BA80D31CFB2FF4003DC1BA /* MutablePersistableRecordTests.swift in Sources */, 562393751DEE104400A6B01F /* MapCursorTests.swift in Sources */, F3BA80D01CFB2FEC003DC1BA /* SchedulingWatchdogTests.swift in Sources */, + 5653EB7E20961FB200F46237 /* AssociationChainSQLTests.swift in Sources */, F3BA80EC1CFB3017003DC1BA /* RowCopiedFromStatementTests.swift in Sources */, F3BA80D41CFB2FF4003DC1BA /* PersistableRecordTests.swift in Sources */, 6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */, @@ -2106,6 +2257,7 @@ F3BA811C1CFB305F003DC1BA /* QueryInterfaceExpressionsTests.swift in Sources */, 5698ACD11DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */, 562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */, + 5653EB8020961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 564E73F3203DA2AC000C443C /* JoinSupportTests.swift in Sources */, 5674A70C1F3087710095F066 /* DatabaseValueConvertibleEncodableTests.swift in Sources */, @@ -2116,8 +2268,10 @@ F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */, 5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, F3BA80E21CFB300F003DC1BA /* DatabaseValueConvertibleFetchTests.swift in Sources */, + 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */, F3BA80F21CFB301A003DC1BA /* DatabaseSavepointTests.swift in Sources */, F3BA80B81CFB2FCD003DC1BA /* DatabaseErrorTests.swift in Sources */, + 5653EB6A20961FB200F46237 /* AssociationBelongsToFetchableRecordTests.swift in Sources */, 5698AC061D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */, 5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */, @@ -2130,8 +2284,10 @@ F3BA80C01CFB2FD2003DC1BA /* DatabasePoolCollationTests.swift in Sources */, 5698ACA11DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */, F3BA80C31CFB2FD2003DC1BA /* DatabasePoolFunctionTests.swift in Sources */, + 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */, F3BA80D51CFB2FFB003DC1BA /* DatabaseReaderTests.swift in Sources */, F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, @@ -2139,9 +2295,12 @@ F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, F3BA80B21CFB2FC5003DC1BA /* DatabaseTests.swift in Sources */, + 5653EB7820961FB200F46237 /* AssociationChainRowScopesTests.swift in Sources */, F3BA80AE1CFB2FA6003DC1BA /* DatabaseRegionTests.swift in Sources */, + 5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */, F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */, 5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, + 5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */, F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */, 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 564F9C211F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */, @@ -2173,6 +2332,7 @@ F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */, F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */, F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */, + 5653EB7620961FB200F46237 /* AssociationHasOneSQLDerivationTests.swift in Sources */, F3BA80C91CFB2FD8003DC1BA /* DatabaseQueueBackupTests.swift in Sources */, 56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */, 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */, diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift new file mode 100644 index 000000000..dc2815443 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -0,0 +1,111 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let team = Player.belongsTo(Team.self) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: Decodable, FetchableRecord { + var player: Player + var team: Team + static let team = Player.team.forKey(CodingKeys.team) +} + +private struct PlayerWithOptionalTeam: Decodable, FetchableRecord { + var player: Player + var team: Team? + static let team = Player.team.forKey(CodingKeys.team) +} + +/// Test support for Decodable records +class AssociationBelongsToDecodableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: PlayerWithRequiredTeam.team) + .asRequest(of: PlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: PlayerWithOptionalTeam.team) + .asRequest(of: PlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift new file mode 100644 index 000000000..db5411021 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToFetchableRecordTests.swift @@ -0,0 +1,120 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let teamScope = "team" + static let team = Player.belongsTo(Team.self, key: teamScope) + var id: Int64 + var teamId: Int64? + var name: String +} + +private struct PlayerWithRequiredTeam: FetchableRecord { + var player: Player + var team: Team + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +private struct PlayerWithOptionalTeam: FetchableRecord { + var player: Player + var team: Team? + + init(row: Row) { + player = Player(row: row) + team = row[Player.teamScope] + } +} + +/// Test support for FetchableRecord records +class AssociationBelongsToFetchableRecordTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: Player.team) + .asRequest(of: PlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } + + func testIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(optional: Player.team) + .asRequest(of: PlayerWithOptionalTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(records.count, 2) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team!.id, 1) + XCTAssertEqual(records[0].team!.name, "Reds") + XCTAssertEqual(records[1].player.id, 2) + XCTAssertNil(records[1].player.teamId) + XCTAssertEqual(records[1].player.name, "Barbara") + XCTAssertNil(records[1].team) + } + + func testJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 1) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + } + + func testJoiningsOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.team) + let players = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(players.count, 2) + XCTAssertEqual(players[0].id, 1) + XCTAssertEqual(players[0].teamId, 1) + XCTAssertEqual(players[0].name, "Arthur") + XCTAssertEqual(players[1].id, 2) + XCTAssertNil(players[1].teamId) + XCTAssertEqual(players[1].name, "Barbara") + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift new file mode 100644 index 000000000..5f23e36a6 --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -0,0 +1,131 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct Team: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "teams" + var id: Int64 + var name: String +} + +private struct Player: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "players" + static let defaultTeam = belongsTo(Team.self) + static let customTeam = belongsTo(Team.self, key: "customTeam") + var id: Int64 + var teamId: Int64? + var name: String +} + +/// Test row scopes +class AssociationBelongsToRowScopeTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "teams") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "players") { t in + t.column("id", .integer).primaryKey() + t.column("teamId", .integer).references("teams") + t.column("name", .text) + } + + try Team(id: 1, name: "Reds").insert(db) + try Player(id: 1, teamId: 1, name: "Arthur").insert(db) + try Player(id: 2, teamId: nil, name: "Barbara").insert(db) + } + } + + func testDefaultScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + } + + func testDefaultScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["teams"]) + XCTAssertEqual(rows[0].scopes["teams"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["teams"]) + XCTAssertEqual(rows[1].scopes["teams"]!, ["id":nil, "name":nil]) + } + + func testDefaultScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testDefaultScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.defaultTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + } + + func testCustomScopeIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.including(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"]) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customTeam"]) + XCTAssertEqual(rows[1].scopes["customTeam"]!, ["id":nil, "name":nil]) + } + + func testCustomScopeJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(required: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 1) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + + func testCustomScopeJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player.joining(optional: Player.customTeam) + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1, "name":"Arthur"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + XCTAssertEqual(rows[1].unscoped, ["id":2, "teamId":nil, "name":"Barbara"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift new file mode 100644 index 000000000..4bf1c848f --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let restrictedB = belongsTo(RestrictedB.self) + static let extendedB = belongsTo(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationBelongsToSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."id" = "a"."bid") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."id" = "a"."bid") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() }, + { (r: BelongsToAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("id")) }, + { (r: HasOneAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."id" = "a"."bid") \ + JOIN "a" "aba" ON ("aba"."bid" = "ab"."id") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.belongsTo(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."id" = "a"."bid") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift new file mode 100644 index 000000000..3e781f56c --- /dev/null +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -0,0 +1,771 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationBelongsToSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"rowid\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentId"] = 1 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1Id"] = 1 + container["parent2Id"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parentA"] = 1 + container["parentB"] = 2 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord, MutablePersistableRecord { + static let databaseTableName = "children" + func encode(to container: inout PersistenceContainer) { + container["parent1A"] = 1 + container["parent1B"] = 2 + container["parent2A"] = 3 + container["parent2B"] = 4 + } + } + + struct Parent : TableRecord { + static let databaseTableName = "parents" + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + do { + let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Child.including(required: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.including(optional: association), """ + SELECT "children".*, "parents".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(required: association), """ + SELECT "children".* \ + FROM "children" \ + JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child.joining(optional: association), """ + SELECT "children".* \ + FROM "children" \ + LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) + """) + try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + static let parent1 = belongsTo(Parent.self, using: ForeignKeys.parent1) + static let parent2 = belongsTo(Parent.self, using: ForeignKeys.parent2) + } + } +} diff --git a/Tests/GRDBTests/AssociationChainRowScopesTests.swift b/Tests/GRDBTests/AssociationChainRowScopesTests.swift new file mode 100644 index 000000000..a05e58cdb --- /dev/null +++ b/Tests/GRDBTests/AssociationChainRowScopesTests.swift @@ -0,0 +1,694 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + var id: Int64 + var bid: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultC = hasOne(C.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + static let defaultD = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationChainRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try A(id: 1, bid: 1, name: "a1").insert(db) + try A(id: 2, bid: 2, name: "a2").insert(db) + try A(id: 3, bid: nil, name: "a3").insert(db) + try D(id: 1, name: "d1").insert(db) + try C(id: 1, bid: 1, did: 1, name: "c1").insert(db) + try C(id: 2, bid: 1, did: nil, name: "c2").insert(db) + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.including(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, ["id":nil, "name":nil]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.including(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = A.including(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.including(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.including(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes["b"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertTrue(rows[3].scopes["b"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + } + do { + let request = B.including(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.including(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.including(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + XCTAssertTrue(rows[1].scopes["c"]!.scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertTrue(rows[2].scopes["c"]!.scopes.names.isEmpty) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + } + do { + let request = A.joining(required: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.including(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.including(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!, ["id":1, "bid":1, "did":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["b"]!.scopes["c"]!, ["id":2, "bid":1, "did":nil, "name":"c2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "bid":2, "name":"a2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":3, "bid":nil, "name":"a3"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[3].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["b"]!.scopes["c"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = B.joining(required: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.including(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.including(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[1].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[2].scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["c"]!.scopes["d"]!, ["id":nil, "name":nil]) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = A.joining(optional: A.defaultB.joining(required: B.defaultC)).order(sql: "a.id, b.id, c.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = A.joining(optional: A.defaultB.joining(optional: B.defaultC)).order(sql: "a.id, b.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "bid":2, "name":"a2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3], ["id":3, "bid":nil, "name":"a3"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + // TODO: chainOptionalRequired +// let request = B.joining(optional: B.defaultC.joining(required: C.defaultD)).order(sql: "b.id, c.id, d.id") +// let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + } + do { + let request = B.joining(optional: B.defaultC.joining(optional: C.defaultD)).order(sql: "b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1], ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2], ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.including(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.including(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"], ["id":1, "bid":1, "did":1, "name":"c1"]) + XCTAssertTrue(rows[0].scopes["b"]!.scopes["c"]!.scopes.names.isEmpty) + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.including(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.unscoped, [:]) + XCTAssertEqual(Set(rows[0].scopes["b"]!.scopes["c"]!.scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["b"]!.scopes["c"]!.scopes["d"]!, ["id":1, "name":"d1"]) + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + let request = A.joining(required: A.defaultB.joining(required: B.defaultC.joining(required: C.defaultD))).order(sql: "a.id, b.id, c.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 1) + + XCTAssertEqual(rows[0], ["id":1, "bid":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + } +} diff --git a/Tests/GRDBTests/AssociationChainSQLTests.swift b/Tests/GRDBTests/AssociationChainSQLTests.swift new file mode 100644 index 000000000..f604ace52 --- /dev/null +++ b/Tests/GRDBTests/AssociationChainSQLTests.swift @@ -0,0 +1,557 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) +} + +private struct B: TableRecord { + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct D: TableRecord { + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationChainSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + } + } + + func testChainOfTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.including(required: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "c".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c)), "") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c)), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(required: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.including(required: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.including(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.including(optional: B.c.joining(optional: C.d)), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c)), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(required: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.including(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.including(optional: C.d)), """ + SELECT "b".*, "d".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c)), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c)), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(required: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, B.joining(required: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, B.joining(optional: B.c.joining(required: C.d)), "TODO") + try assertEqualSQL(db, B.joining(optional: B.c.joining(optional: C.d)), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeIncludingJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.including(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.including(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(required: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "c".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(required: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.including(required: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(required: B.c.joining(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.including(optional: B.c.joining(optional: C.d))), """ + SELECT "a".*, "c".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(required: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.including(optional: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.including(optional: C.d))), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } + + func testChainOfThreeJoiningJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(required: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + JOIN "d" ON ("d"."id" = "c"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b.joining(required: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(required: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + // TODO: chainOptionalRequired +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(required: C.d))), "TODO") +// try assertEqualSQL(db, A.joining(optional: A.b.joining(required: B.c.joining(optional: C.d))), "TODO) +// try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(required: C.d))), "TODO") + try assertEqualSQL(db, A.joining(optional: A.b.joining(optional: B.c.joining(optional: C.d))), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") \ + LEFT JOIN "d" ON ("d"."id" = "c"."did") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift new file mode 100644 index 000000000..d15bbd908 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -0,0 +1,406 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A <- B +private struct A : TableRecord { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let restrictedB = hasOne(RestrictedB.self) + static let extendedB = hasOne(ExtendedB.self) +} + +private struct B : TableRecord { + static let a = belongsTo(A.self) + static let databaseTableName = "b" +} + +private struct RestrictedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [Column("name")] +} + +private struct ExtendedB : TableRecord { + static let databaseTableName = "b" + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +/// Test SQL generation +class AssociationHasOneSQLDerivationTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("name", .text) + } + } + } + + func testDefaultSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.restrictedB), """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + try assertEqualSQL(db, A.including(required: A.extendedB), """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + + func testCustomSelection() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b + .select(Column("name"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let request = A.including(required: A.b + .select( + AllColumns(), + Column.rowID)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".*, "b"."rowid" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select( + Column("name"), + (Column("id") + aAlias[Column("id")]).aliased("foo"))) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", ("b"."id" + "a"."id") AS "foo" \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") + """) + } + } + } + + func testFilteredAssociationImpactsJoinOnClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let request = A.including(required: A.b.filter(Column("name") != nil)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) + """) + } + do { + let request = A.including(required: A.b.filter(key: 1)) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [1, 2, 3])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" IN (1, 2, 3))) + """) + } + do { + let request = A.including(required: A.b.filter(key: ["id": 1])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."id" = 1)) + """) + } + do { + let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON (("b"."aid" = "a"."id") AND (("b"."id" = 1) OR ("b"."id" = 2))) + """) + } + do { + let bAlias = TableAlias(name: "customB") + let request = A.including(required: A.b + .aliased(bAlias) + .filter(sql: "customB.name = ?", arguments: ["foo"])) + try assertEqualSQL(db, request, """ + SELECT "a".*, "customB".* \ + FROM "a" \ + JOIN "b" "customB" ON (("customB"."aid" = "a"."id") AND (customB.name = 'foo')) + """) + } + } + } + + func testFilterAssociationInWhereClause() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."aid" = "a"."id") \ + WHERE ("b"."name" IS NOT NULL) + """) + } + } + + func testAssociationOrderBubbleUp() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aBase = A.all().aliased(TableAlias(name: "a")) + let abBase = A.b.aliased(TableAlias(name: "ab")) + let abaBase = B.a.aliased(TableAlias(name: "aba")) + + let aTransforms = [ + { (r: QueryInterfaceRequest) in return r }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() }, + ] + let abTransforms = [ + { (r: HasOneAssociation) in return r }, + { (r: HasOneAssociation) in return r.order(Column("name"), Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).order(Column("id").desc) }, + { (r: HasOneAssociation) in return r.order(Column("name")).reversed() }, + { (r: HasOneAssociation) in return r.reversed() }, + ] + let abaTransforms = [ + { (r: BelongsToAssociation) in return r }, + { (r: BelongsToAssociation) in return r.order(Column("id")) }, + { (r: BelongsToAssociation) in return r.order(Column("id")).reversed() }, + ] + + var sqls: [String] = [] + for aTransform in aTransforms { + for abTransform in abTransforms { + for abaTransform in abaTransforms { + let request = aTransform(aBase) + .including(required: abTransform(abBase) + .including(required: abaTransform(abaBase))) + let sqlRequest = try SQLRequest(db, request: request) + sqls.append(sqlRequest.sql) + } + } + } + + let prefix = """ + SELECT "a".*, "ab".*, "aba".* \ + FROM "a" \ + JOIN "b" "ab" ON ("ab"."aid" = "a"."id") \ + JOIN "a" "aba" ON ("aba"."id" = "ab"."aid") + """ + let orderClauses = sqls.map { sql -> String in + let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) + return String(sql.suffix(from: prefixEndIndex)) + } + XCTAssertEqual(orderClauses, [ + // a: { (r: QueryInterfaceRequest) in return r }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + "", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")) }, + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\", \"aba\".\"id\"", + + + // a: { (r: QueryInterfaceRequest) in return r.order(Column("id")).reversed() } + // ab: { (r: BelongsToAssociation) in return r } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name"), Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).order(Column("id").desc) } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", + + // ab: { (r: BelongsToAssociation) in return r.order(Column("name")).reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", + + // ab: { (r: BelongsToAssociation) in return r.reversed() } + // aba: { (r: HasOneAssociation) in return r } + " ORDER BY \"a\".\"id\" DESC", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")) } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", + // aba: { (r: HasOneAssociation) in return r.order(Column("id")).reversed() } + " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", + ]) + } + } + + // TODO: Test if and only if we really want to build an association from any request +// func testAssociationFromRequest() throws { +// let dbQueue = try makeDatabaseQueue() +// try dbQueue.inDatabase { db in +// do { +// let bRequest = B +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b".* \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = RestrictedB +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// do { +// let bRequest = ExtendedB +// .select([Column("name")]) +// .filter(Column("name") != nil) +// .order(Column("id")) +// let association = A.hasOne(bRequest) +// let request = A.including(required: association) +// try assertEqualSQL(db, request, """ +// SELECT "a".*, "b"."name" \ +// FROM "a" \ +// JOIN "b" ON (("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL)) \ +// ORDER BY "b"."id" +// """) +// } +// } +// } +} diff --git a/Tests/GRDBTests/AssociationHasOneSQLTests.swift b/Tests/GRDBTests/AssociationHasOneSQLTests.swift new file mode 100644 index 000000000..182502be4 --- /dev/null +++ b/Tests/GRDBTests/AssociationHasOneSQLTests.swift @@ -0,0 +1,769 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +/// Test SQL generation +class AssociationHasOneSQLTests: GRDBTestCase { + + func testSingleColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + container["rowid"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer) + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."rowid") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 2)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parentId", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parentId" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parentId\" = 1)") + } + } + } + + func testSingleColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["id"] = 1 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "children") { t in + t.column("parent1Id", .integer).references("parents") + t.column("parent2Id", .integer).references("parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent1Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent1Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON ("children"."parent2Id" = "parents"."id") + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE (\"parent2Id\" = 1)") + } + } + } + + func testCompoundColumnNoForeignKeyNoPrimaryKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnNoForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSingleForeignKey() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parentA", .integer) + t.column("parentB", .integer) + t.foreignKey(["parentA", "parentB"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parentA" = "parents"."a") AND ("children"."parentB" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parentA\" = 1) AND (\"parentB\" = 2))") + } + } + } + + func testCompoundColumnSeveralForeignKeys() throws { + struct Child : TableRecord { + static let databaseTableName = "children" + } + + struct Parent : TableRecord, MutablePersistableRecord { + static let databaseTableName = "parents" + func encode(to container: inout PersistenceContainer) { + container["a"] = 1 + container["b"] = 2 + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.create(table: "parents") { t in + t.column("a", .integer) + t.column("b", .integer) + t.primaryKey(["a", "b"]) + } + try db.create(table: "children") { t in + t.column("parent1A", .integer) + t.column("parent1B", .integer) + t.column("parent2A", .integer) + t.column("parent2B", .integer) + t.foreignKey(["parent1A", "parent1B"], references: "parents") + t.foreignKey(["parent2A", "parent2B"], references: "parents") + } + } + + try dbQueue.inDatabase { db in + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent1A" = "parents"."a") AND ("children"."parent1B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent1A\" = 1) AND (\"parent1B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + do { + let association = Parent.hasOne(Child.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) + try assertEqualSQL(db, Parent.all().including(required: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().including(optional: association), """ + SELECT "parents".*, "children".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(required: association), """ + SELECT "parents".* \ + FROM "parents" \ + JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent.all().joining(optional: association), """ + SELECT "parents".* \ + FROM "parents" \ + LEFT JOIN "children" ON (("children"."parent2A" = "parents"."a") AND ("children"."parent2B" = "parents"."b")) + """) + try assertEqualSQL(db, Parent().request(for: association), "SELECT * FROM \"children\" WHERE ((\"parent2A\" = 1) AND (\"parent2B\" = 2))") + } + } + } + + func testForeignKeyDefinitionFromColumn() { + // This test pass if code compiles + struct Parent : TableRecord { + static let databaseTableName = "parents" + enum Columns { + static let id = Column("id") + } + static let child1 = hasOne(Child.self, using: Child.ForeignKeys.parent1) + static let child2 = hasOne(Child.self, using: Child.ForeignKeys.parent2) + } + + struct Child : TableRecord { + static let databaseTableName = "children" + enum Columns { + static let parentId = Column("parentId") + } + enum ForeignKeys { + static let parent1 = ForeignKey([Columns.parentId]) + static let parent2 = ForeignKey([Columns.parentId], to: [Parent.Columns.id]) + } + } + } +} diff --git a/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift new file mode 100644 index 000000000..4795ac7e0 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelDecodableRecordTests.swift @@ -0,0 +1,237 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +private struct AWithRequiredBD: Decodable, FetchableRecord { + var a: A + var b: B + var d: D + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +private struct AWithOptionalBD: Decodable, FetchableRecord { + var a: A + var b: B? + var d: D? + static let b = A.b.forKey(CodingKeys.b) + static let d = A.d.forKey(CodingKeys.d) +} + +/// Test support for Decodable records +class AssociationParallelDecodableRecordTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + } + } + + func testParallelTwoIncludingRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(required: AWithRequiredBD.b) + .including(required: AWithRequiredBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithRequiredBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b.id, 1) + XCTAssertEqual(records[0].b.name, "b1") + XCTAssertEqual(records[0].d.id, 1) + XCTAssertEqual(records[0].d.name, "d1") + + XCTAssertEqual(records[1].a.id, 3) + XCTAssertEqual(records[1].a.bid, 2) + XCTAssertEqual(records[1].a.did, 1) + XCTAssertEqual(records[1].a.name, "a3") + XCTAssertEqual(records[1].b.id, 2) + XCTAssertEqual(records[1].b.name, "b2") + XCTAssertEqual(records[1].d.id, 1) + XCTAssertEqual(records[1].d.name, "d1") + } + + func testParallelTwoIncludingOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .including(optional: AWithOptionalBD.b) + .including(optional: AWithOptionalBD.d) + .order(sql: "a.id, b.id, d.id") + .asRequest(of: AWithOptionalBD.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].a.id, 1) + XCTAssertEqual(records[0].a.bid, 1) + XCTAssertEqual(records[0].a.did, 1) + XCTAssertEqual(records[0].a.name, "a1") + XCTAssertEqual(records[0].b!.id, 1) + XCTAssertEqual(records[0].b!.name, "b1") + XCTAssertEqual(records[0].d!.id, 1) + XCTAssertEqual(records[0].d!.name, "d1") + + XCTAssertEqual(records[1].a.id, 2) + XCTAssertEqual(records[1].a.bid, 1) + XCTAssertEqual(records[1].a.did, nil) + XCTAssertEqual(records[1].a.name, "a2") + XCTAssertEqual(records[1].b!.id, 1) + XCTAssertEqual(records[1].b!.name, "b1") + XCTAssertNil(records[1].d) + + XCTAssertEqual(records[2].a.id, 3) + XCTAssertEqual(records[2].a.bid, 2) + XCTAssertEqual(records[2].a.did, 1) + XCTAssertEqual(records[2].a.name, "a3") + XCTAssertEqual(records[2].b!.id, 2) + XCTAssertEqual(records[2].b!.name, "b2") + XCTAssertEqual(records[2].d!.id, 1) + XCTAssertEqual(records[2].d!.name, "d1") + + XCTAssertEqual(records[3].a.id, 4) + XCTAssertEqual(records[3].a.bid, 2) + XCTAssertEqual(records[3].a.did, nil) + XCTAssertEqual(records[3].a.name, "a4") + XCTAssertEqual(records[3].b!.id, 2) + XCTAssertEqual(records[3].b!.name, "b2") + XCTAssertNil(records[3].d) + + XCTAssertEqual(records[4].a.id, 5) + XCTAssertEqual(records[4].a.bid, nil) + XCTAssertEqual(records[4].a.did, 1) + XCTAssertEqual(records[4].a.name, "a5") + XCTAssertNil(records[4].b) + XCTAssertEqual(records[4].d!.id, 1) + XCTAssertEqual(records[4].d!.name, "d1") + + XCTAssertEqual(records[5].a.id, 6) + XCTAssertEqual(records[5].a.bid, nil) + XCTAssertEqual(records[5].a.did, nil) + XCTAssertEqual(records[5].a.name, "a6") + XCTAssertNil(records[5].b) + XCTAssertNil(records[5].d) + } + + func testParallelTwoJoiningRequired() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(required: A.b) + .joining(required: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 2) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 3) + XCTAssertEqual(records[1].bid, 2) + XCTAssertEqual(records[1].did, 1) + XCTAssertEqual(records[1].name, "a3") + } + + func testParallelTwoJoiningOptional() throws { + let dbQueue = try makeDatabaseQueue() + let request = A + .joining(optional: A.b) + .joining(optional: A.d) + .order(sql: "a.id, b.id, d.id") + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + + XCTAssertEqual(records.count, 6) + + XCTAssertEqual(records[0].id, 1) + XCTAssertEqual(records[0].bid, 1) + XCTAssertEqual(records[0].did, 1) + XCTAssertEqual(records[0].name, "a1") + + XCTAssertEqual(records[1].id, 2) + XCTAssertEqual(records[1].bid, 1) + XCTAssertEqual(records[1].did, nil) + XCTAssertEqual(records[1].name, "a2") + + XCTAssertEqual(records[2].id, 3) + XCTAssertEqual(records[2].bid, 2) + XCTAssertEqual(records[2].did, 1) + XCTAssertEqual(records[2].name, "a3") + + XCTAssertEqual(records[3].id, 4) + XCTAssertEqual(records[3].bid, 2) + XCTAssertEqual(records[3].did, nil) + XCTAssertEqual(records[3].name, "a4") + + XCTAssertEqual(records[4].id, 5) + XCTAssertEqual(records[4].bid, nil) + XCTAssertEqual(records[4].did, 1) + XCTAssertEqual(records[4].name, "a5") + + XCTAssertEqual(records[5].id, 6) + XCTAssertEqual(records[5].bid, nil) + XCTAssertEqual(records[5].did, nil) + XCTAssertEqual(records[5].name, "a6") + } +} + diff --git a/Tests/GRDBTests/AssociationParallelRowScopesTests.swift b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift new file mode 100644 index 000000000..f833518a5 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelRowScopesTests.swift @@ -0,0 +1,1400 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "a" + static let defaultB = belongsTo(B.self) + static let defaultD = belongsTo(D.self) + static let customB = belongsTo(B.self, key: "customB") + static let customD = belongsTo(D.self, key: "customD") + var id: Int64 + var bid: Int64? + var did: Int64? + var name: String +} + +private struct B: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let defaultC = hasOne(C.self) + static let customA = hasOne(A.self, key: "customA") + static let customC = hasOne(C.self, key: "customC") + static let databaseTableName = "b" + var id: Int64 + var name: String +} + +private struct C: Codable, FetchableRecord, PersistableRecord { + static let databaseTableName = "c" + var id: Int64 + var bid: Int64? + var name: String +} + +private struct D: Codable, FetchableRecord, PersistableRecord { + static let defaultA = hasOne(A.self) + static let customA = hasOne(A.self, key: "customA") + static let databaseTableName = "d" + var id: Int64 + var name: String +} + +/// Test row scopes +class AssociationParallelRowScopesTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text) + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + t.column("name", .text) + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("name", .text) + } + + try B(id: 1, name: "b1").insert(db) + try B(id: 2, name: "b2").insert(db) + try B(id: 3, name: "b3").insert(db) + try D(id: 1, name: "d1").insert(db) + try A(id: 1, bid: 1, did: 1, name: "a1").insert(db) + try A(id: 2, bid: 1, did: nil, name: "a2").insert(db) + try A(id: 3, bid: 2, did: 1, name: "a3").insert(db) + try A(id: 4, bid: 2, did: nil, name: "a4").insert(db) + try A(id: 5, bid: nil, did: 1, name: "a5").insert(db) + try A(id: 6, bid: nil, did: nil, name: "a6").insert(db) + try C(id: 1, bid: 1, name: "c1").insert(db) + } + } + + func testDefaultScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b", "d"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a", "c"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["b"]) + XCTAssertEqual(rows[0].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["b"]) + XCTAssertEqual(rows[1].scopes["b"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["b"]) + XCTAssertEqual(rows[2].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["b"]) + XCTAssertEqual(rows[3].scopes["b"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["b"]) + XCTAssertEqual(rows[4].scopes["b"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["b"]) + XCTAssertEqual(rows[5].scopes["b"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["a"]) + XCTAssertEqual(rows[0].scopes["a"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["a"]) + XCTAssertEqual(rows[1].scopes["a"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["a"]) + XCTAssertEqual(rows[2].scopes["a"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["a"]) + XCTAssertEqual(rows[3].scopes["a"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["a"]) + XCTAssertEqual(rows[4].scopes["a"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.defaultB).including(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.defaultB).including(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["d"]) + XCTAssertEqual(rows[0].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["d"]) + XCTAssertEqual(rows[1].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["d"]) + XCTAssertEqual(rows[2].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["d"]) + XCTAssertEqual(rows[3].scopes["d"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["d"]) + XCTAssertEqual(rows[4].scopes["d"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["d"]) + XCTAssertEqual(rows[5].scopes["d"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.defaultA).including(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.defaultA).including(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["c"]) + XCTAssertEqual(rows[0].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["c"]) + XCTAssertEqual(rows[1].scopes["c"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["c"]) + XCTAssertEqual(rows[2].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["c"]) + XCTAssertEqual(rows[3].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["c"]) + XCTAssertEqual(rows[4].scopes["c"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testDefaultScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(required: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.defaultB).joining(optional: A.defaultD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(required: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.defaultA).joining(optional: B.defaultC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } + + func testCustomScopeParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.including(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB", "customD"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.including(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.including(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA", "customC"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.including(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + } + do { + let request = A.including(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = A.including(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customB"]) + XCTAssertEqual(rows[0].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customB"]) + XCTAssertEqual(rows[1].scopes["customB"]!, ["id":1, "name":"b1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customB"]) + XCTAssertEqual(rows[2].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customB"]) + XCTAssertEqual(rows[3].scopes["customB"]!, ["id":2, "name":"b2"]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customB"]) + XCTAssertEqual(rows[4].scopes["customB"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customB"]) + XCTAssertEqual(rows[5].scopes["customB"]!, ["id":nil, "name":nil]) + } + do { + let request = B.including(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + } + do { + let request = B.including(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + } + do { + let request = B.including(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customA"]) + XCTAssertEqual(rows[0].scopes["customA"]!, ["id":1, "bid":1, "did":1, "name":"a1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customA"]) + XCTAssertEqual(rows[1].scopes["customA"]!, ["id":2, "bid":1, "did":nil, "name":"a2"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customA"]) + XCTAssertEqual(rows[2].scopes["customA"]!, ["id":3, "bid":2, "did":1, "name":"a3"]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customA"]) + XCTAssertEqual(rows[3].scopes["customA"]!, ["id":4, "bid":2, "did":nil, "name":"a4"]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customA"]) + XCTAssertEqual(rows[4].scopes["customA"]!, ["id":nil, "bid":nil, "did":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(required: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = A.joining(optional: A.customB).including(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + } + do { + let request = A.joining(optional: A.customB).including(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customD"]) + XCTAssertEqual(rows[0].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customD"]) + XCTAssertEqual(rows[1].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customD"]) + XCTAssertEqual(rows[2].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customD"]) + XCTAssertEqual(rows[3].scopes["customD"]!, ["id":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customD"]) + XCTAssertEqual(rows[4].scopes["customD"]!, ["id":1, "name":"d1"]) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertEqual(Set(rows[5].scopes.names), ["customD"]) + XCTAssertEqual(rows[5].scopes["customD"]!, ["id":nil, "name":nil]) + } + do { + let request = B.joining(required: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(required: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + do { + let request = B.joining(optional: B.customA).including(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + } + do { + let request = B.joining(optional: B.customA).including(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[0].scopes.names), ["customC"]) + XCTAssertEqual(rows[0].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertEqual(Set(rows[1].scopes.names), ["customC"]) + XCTAssertEqual(rows[1].scopes["customC"]!, ["id":1, "bid":1, "name":"c1"]) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[2].scopes.names), ["customC"]) + XCTAssertEqual(rows[2].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertEqual(Set(rows[3].scopes.names), ["customC"]) + XCTAssertEqual(rows[3].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertEqual(Set(rows[4].scopes.names), ["customC"]) + XCTAssertEqual(rows[4].scopes["customC"]!, ["id":nil, "bid":nil, "name":nil]) + } + } + + func testCustomScopeParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + do { + let request = A.joining(required: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = A.joining(required: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(required: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 3) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + } + do { + let request = A.joining(optional: A.customB).joining(optional: A.customD).order(sql: "a.id, b.id, d.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 6) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "bid":1, "did":1, "name":"a1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":2, "bid":1, "did":nil, "name":"a2"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":3, "bid":2, "did":1, "name":"a3"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":4, "bid":2, "did":nil, "name":"a4"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":5, "bid":nil, "did":1, "name":"a5"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + + XCTAssertEqual(rows[5].unscoped, ["id":6, "bid":nil, "did":nil, "name":"a6"]) + XCTAssertTrue(rows[5].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(required: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 4) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(required: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 2) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + } + do { + let request = B.joining(optional: B.customA).joining(optional: B.customC).order(sql: "b.id, a.id, c.id") + let rows = try dbQueue.inDatabase { try request.asRequest(of: Row.self).fetchAll($0) } + + XCTAssertEqual(rows.count, 5) + + XCTAssertEqual(rows[0].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[0].scopes.names.isEmpty) + + XCTAssertEqual(rows[1].unscoped, ["id":1, "name":"b1"]) + XCTAssertTrue(rows[1].scopes.names.isEmpty) + + XCTAssertEqual(rows[2].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[2].scopes.names.isEmpty) + + XCTAssertEqual(rows[3].unscoped, ["id":2, "name":"b2"]) + XCTAssertTrue(rows[3].scopes.names.isEmpty) + + XCTAssertEqual(rows[4].unscoped, ["id":3, "name":"b3"]) + XCTAssertTrue(rows[4].scopes.names.isEmpty) + } + } +} + diff --git a/Tests/GRDBTests/AssociationParallelSQLTests.swift b/Tests/GRDBTests/AssociationParallelSQLTests.swift new file mode 100644 index 000000000..db57c3f06 --- /dev/null +++ b/Tests/GRDBTests/AssociationParallelSQLTests.swift @@ -0,0 +1,272 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> B <- C +// A -> D +private struct A: TableRecord { + static let databaseTableName = "a" + static let b = belongsTo(B.self) + static let d = belongsTo(D.self) +} + +private struct B: TableRecord { + static let a = hasOne(A.self) + static let c = hasOne(C.self) + static let databaseTableName = "b" +} + +private struct C: TableRecord { + static let databaseTableName = "c" + static let b = belongsTo(B.self) +} + +private struct D: TableRecord { + static let a = hasOne(A.self) + static let databaseTableName = "d" +} + +/// Test SQL generation +class AssociationParallelSQLTests: GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + t.column("did", .integer).references("d") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + } + } + + func testParallelTwoIncludingIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(required: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "b".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(required: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "a".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoIncludingJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(required: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(required: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.including(optional: A.b).joining(optional: A.d), """ + SELECT "a".*, "b".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(required: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(required: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.including(optional: B.a).joining(optional: B.c), """ + SELECT "b".*, "a".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningIncluding() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(required: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).including(optional: A.d), """ + SELECT "a".*, "d".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(required: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).including(optional: B.c), """ + SELECT "b".*, "c".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } + + func testParallelTwoJoiningJoining() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.joining(required: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(required: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(required: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, A.joining(optional: A.b).joining(optional: A.d), """ + SELECT "a".* \ + FROM "a" \ + LEFT JOIN "b" ON ("b"."id" = "a"."bid") \ + LEFT JOIN "d" ON ("d"."id" = "a"."did") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(required: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(required: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + JOIN "c" ON ("c"."bid" = "b"."id") + """) + try assertEqualSQL(db, B.joining(optional: B.a).joining(optional: B.c), """ + SELECT "b".* \ + FROM "b" \ + LEFT JOIN "a" ON ("a"."bid" = "b"."id") \ + LEFT JOIN "c" ON ("c"."bid" = "b"."id") + """) + } + } +} diff --git a/Tests/GRDBTests/AssociationRowScopeSearchTests.swift b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift new file mode 100644 index 000000000..6e1f1f8b9 --- /dev/null +++ b/Tests/GRDBTests/AssociationRowScopeSearchTests.swift @@ -0,0 +1,244 @@ +import XCTest +#if GRDBCIPHER + @testable import GRDBCipher +#elseif GRDBCUSTOMSQLITE + @testable import GRDBCustomSQLite +#else + @testable import GRDB +#endif + +// a -> b* -> c +// -> d* +// -> c* +private struct A: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let c = hasOne(C.self) + var id: Int64 +} +private struct B: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "b" + static let c = hasOne(C.self) + static let d = hasOne(D.self) + var id: Int64 + var aid: Int64 +} +private struct C: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "c" + var id: Int64 + var aid: Int64? + var bid: Int64? +} +private struct D: TableRecord, FetchableRecord, Decodable { + static let databaseTableName = "d" + var id: Int64 + var bid: Int64 +} + +class AssociationRowScopeSearchTests: GRDBTestCase { + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + // 1. Prepare data + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + } + try db.create(table: "c") { t in + t.column("id", .integer).primaryKey() + t.column("aid", .integer).references("a") + t.column("bid", .integer).references("b") + } + try db.create(table: "d") { t in + t.column("id", .integer).primaryKey() + t.column("bid", .integer).references("b") + } + try db.execute("INSERT INTO a (id) VALUES (1)") + try db.execute("INSERT INTO b (id, aid) VALUES (2, 1)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (3, NULL, 2)") + try db.execute("INSERT INTO c (id, aid, bid) VALUES (4, 1, NULL)") + try db.execute("INSERT INTO d (id, bid) VALUES (5, 2)") + } + } + + private let testedRequest = A + .including(required: A.b + .including(required: B.c) + .including(required: B.d) + ) + .including(required: A.c) + + func testTestedRequest() throws { + // Assert that we fetch the expected nested scopes before we start testing breadth-first lookup + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rows = try testedRequest.asRequest(of: Row.self).fetchAll(db) + + XCTAssertEqual(rows.count, 1) + let row = rows[0] + + XCTAssertEqual(row.unscoped, ["id": 1]) + XCTAssertEqual(row.scopes["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopes["b"]!.scopes["c"]!, ["id": 3, "aid": nil, "bid": 2]) + XCTAssertEqual(row.scopes["b"]!.scopes["d"]!, ["id": 5, "bid": 2]) + XCTAssertEqual(row.scopes["c"]!, ["id": 4, "aid": 1, "bid": nil]) + } + } + + func testBreadthFirstScopeLookup() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let row = try testedRequest.asRequest(of: Row.self).fetchOne(db)! + XCTAssertEqual(row.scopesTree["b"]!.unscoped, ["id": 2, "aid": 1]) + XCTAssertEqual(row.scopesTree["c"]!, ["id": 4, "aid": 1, "bid": nil]) + XCTAssertEqual(row.scopesTree["d"]!, ["id": 5, "bid": 2]) + } + } + + func testFetchableRecordDecoding() throws { + struct Record: FetchableRecord { + var a: A + var b: B + var c: C + var d: D + init(row: Row) { + a = A(row: row) + b = row["b"] + c = row["c"] + d = row["d"] + } + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testFlatDecodableRecordDecoding() throws { + struct Record: FetchableRecord, Decodable { + var a: A + var b: B + var c: C + var d: D + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + } + } + + func testNestedDecodableRecordDecoding() throws { + struct NestedB: Decodable { + var b: B + var c: C + var d: D + } + struct Record: FetchableRecord, Decodable { + var a: A + var b: NestedB + var c: C + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.b.b.id, 2) + XCTAssertEqual(record.b.b.aid, 1) + XCTAssertEqual(record.b.c.id, 3) + XCTAssertNil(record.b.c.aid) + XCTAssertEqual(record.b.c.bid, 2) + XCTAssertEqual(record.b.d.id, 5) + XCTAssertEqual(record.b.d.bid, 2) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + } + } + + func testDecodableWithCustomRowDecoding() throws { + struct CustomA: FetchableRecord, Decodable { + var id: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + custom = true + } + } + struct CustomB: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + custom = true + } + } + struct CustomC: FetchableRecord, Decodable { + var id: Int64 + var aid: Int64? + var bid: Int64? + var custom: Bool? + init(row: Row) { + id = row["id"] + aid = row["aid"] + bid = row["bid"] + custom = true + } + } + struct CustomD: FetchableRecord, Decodable { + var id: Int64 + var bid: Int64 + var custom: Bool? + init(row: Row) { + id = row["id"] + bid = row["bid"] + custom = true + } + } + struct Record: FetchableRecord, Decodable { + var a: CustomA + var b: CustomB + var c: CustomC + var d: CustomD + } + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let record = try testedRequest.asRequest(of: Record.self).fetchOne(db)! + XCTAssertEqual(record.a.id, 1) + XCTAssertEqual(record.a.custom, true) + XCTAssertEqual(record.b.id, 2) + XCTAssertEqual(record.b.aid, 1) + XCTAssertEqual(record.b.custom, true) + XCTAssertEqual(record.c.id, 4) + XCTAssertEqual(record.c.aid, 1) + XCTAssertNil(record.c.bid) + XCTAssertEqual(record.c.custom, true) + XCTAssertEqual(record.d.id, 5) + XCTAssertEqual(record.d.bid, 2) + XCTAssertEqual(record.d.custom, true) + } + } +} diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift new file mode 100644 index 000000000..c3d3041bf --- /dev/null +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -0,0 +1,340 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +// A -> A +// A -> B1 +// A -> B2 +private struct A : TableRecord { + static let databaseTableName = "a" + static let parent = belongsTo(A.self) + static let child = hasOne(A.self) + static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) + static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) +} +private struct B : TableRecord { + static let databaseTableName = "b" + static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) + static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) +} + +/// Tests for table name conflicts, recursive associations, +/// user-defined table aliases, and expressions that involve several tables. +class AssociationTableAliasTestsSQLTests : GRDBTestCase { + + override func setup(_ dbWriter: DatabaseWriter) throws { + try dbWriter.write { db in + try db.create(table: "b") { t in + t.column("id", .integer).primaryKey() + } + try db.create(table: "a") { t in + t.column("id", .integer).primaryKey() + t.column("bid1", .integer).references("b") + t.column("bid2", .integer).references("b") + t.column("parentId", .integer).references("a") + t.column("name", .text) + } + } + } + + func testTableAliasBasics() throws { + // A table reference qualifies all unqualified selectables, expressions, and orderings + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let alias = TableAlias() + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "name" \ + FROM "a" \ + WHERE (("id" = 1) AND (("name" IS NOT NULL) AND ("name" = 'foo'))) \ + GROUP BY "name" \ + HAVING "name" \ + ORDER BY "name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + do { + let alias = TableAlias(name: "customA") + let name = Column("name") + let condition = name != nil && alias[name] == "foo" + + let expectedSQL = """ + SELECT "customA"."name" \ + FROM "a" "customA" \ + WHERE (("customA"."id" = 1) AND (("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo'))) \ + GROUP BY "customA"."name" \ + HAVING "customA"."name" \ + ORDER BY "customA"."name" + """ + + do { + let request = A + .aliased(alias) + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(name) + .filter(key: 1) + .filter(condition) + .group(name) + .having(name) + .order(name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + } + + func testRecursiveRelationDepth1() throws { + // A.include(A.parent) + // A.include(A.child) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try assertEqualSQL(db, A.including(required: A.parent), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."id" = "a1"."parentId") + """) + try assertEqualSQL(db, A.including(required: A.child), """ + SELECT "a1".*, "a2".* \ + FROM "a" "a1" \ + JOIN "a" "a2" ON ("a2"."parentId" = "a1"."id") + """) + } + } + + func testRecursiveRelationDepth2() throws { + // A.include(B1).include(A) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b".*, "a2".* \ + FROM "a" "a1" \ + JOIN "b" ON ("b"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b"."id") + """) + } + } + + func testMultipleForeignKeys() throws { + // A + // .include(B1) + // .include(B2) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1) + .including(required: A.b2) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b1".*, "b2".* \ + FROM "a" \ + JOIN "b" "b1" ON ("b1"."id" = "a"."bid1") \ + JOIN "b" "b2" ON ("b2"."id" = "a"."bid2") + """) + } + } + + func testRecursiveThroughMultipleForeignKeys() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = A + .including(required: A.b1 + .including(required: B.a2)) + .including(required: A.b2 + .including(required: B.a1)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") + """) + } + } + + func testUserDefinedAlias() throws { + // A + // .aliased("customA") + // .include(B1.aliased("customB")) + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let aAlias1 = TableAlias(name: "customA1") // On TableMapping and QueryInterfaceRequest + let bAlias = TableAlias(name: "customB") // On BelongsToAssociation + let aAlias2 = TableAlias(name: "customA2") // On HasOneAssociation + + let expectedSQL = """ + SELECT "customA1".*, "customB".*, "customA2".* \ + FROM "a" "customA1" \ + JOIN "b" "customB" ON ("customB"."id" = "customA1"."bid1") \ + JOIN "a" "customA2" ON ("customA2"."bid2" = "customB"."id") + """ + + do { + // Alias first + let request = A + .aliased(aAlias1) + .including(required: A.b1 + .aliased(bAlias) + .including(required: B.a2 + .aliased(aAlias2))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Alias last + let request = A + .including(required: A.b1 + .including(required: B.a2 + .aliased(aAlias2)) + .aliased(bAlias)) + .aliased(aAlias1) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + + func testUserInducedNameConflict() throws { + // A.include(B1.aliased("a")) + // A.aliased("b").include(B1) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let bAlias = TableAlias(name: A.databaseTableName.lowercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "a".* \ + FROM "a" "a1" \ + JOIN "b" "a" ON ("a"."id" = "a1"."bid1") + """) + } + do { + let bAlias = TableAlias(name: A.databaseTableName.uppercased()) + let request = A.including(required: A.b1.aliased(bAlias)) + try assertEqualSQL(db, request, """ + SELECT "a1".*, "A".* \ + FROM "a" "a1" \ + JOIN "b" "A" ON ("A"."id" = "a1"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.lowercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "b".*, "b1".* \ + FROM "a" "b" \ + JOIN "b" "b1" ON ("b1"."id" = "b"."bid1") + """) + } + do { + let aAlias = TableAlias(name: B.databaseTableName.uppercased()) + let request = A.aliased(aAlias).including(required: A.b1) + try assertEqualSQL(db, request, """ + SELECT "B".*, "b1".* \ + FROM "a" "B" \ + JOIN "b" "b1" ON ("b1"."id" = "B"."bid1") + """) + } + } + } + + func testCrossTableExpressions() throws { + // A + // .include(B1.include(A)) + // .include(B2.include(A)) + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let rootA = TableAlias() + let A1 = TableAlias() + let A2 = TableAlias() + let name = Column("name") + + let condition = name != nil && rootA[name] > A1[name] && A2[name] == "foo" + + let expectedSQL = """ + SELECT "a1".*, "b1".*, "a2".*, "b2".*, "a3".* \ + FROM "a" "a1" \ + JOIN "b" "b1" ON ("b1"."id" = "a1"."bid1") \ + JOIN "a" "a2" ON ("a2"."bid2" = "b1"."id") \ + JOIN "b" "b2" ON ("b2"."id" = "a1"."bid2") \ + JOIN "a" "a3" ON ("a3"."bid1" = "b2"."id") \ + WHERE ((("a1"."name" IS NOT NULL) AND ("a1"."name" > "a3"."name")) AND ("a2"."name" = 'foo')) + """ + + do { + // Filter first + let request = A + .filter(condition) + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + try assertEqualSQL(db, request, expectedSQL) + } + + do { + // Filter last + let request = A + .aliased(rootA) + .including(required: A.b1 + .including(required: B.a2.aliased(A2))) + .including(required: A.b2 + .including(required: B.a1.aliased(A1))) + .filter(condition) + try assertEqualSQL(db, request, expectedSQL) + } + } + } +} From a16bd6b54e0f5441557505df710726745820982c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 18:18:33 +0200 Subject: [PATCH 191/348] Associations Documentation --- Documentation/AssociationsBasics.md | 1375 +++++++++++++++++ .../Associations2/AmbiguousForeignKeys.svg | 154 ++ .../Images/Associations2/Associations.sketch | Bin 0 -> 406782 bytes .../Images/Associations2/BelongsToSchema.svg | 133 ++ .../Images/Associations2/HasManySchema.svg | 135 ++ .../Associations2/HasManyThroughSchema.svg | 185 +++ .../Images/Associations2/HasOneSchema.svg | 153 ++ .../Associations2/HasOneThroughSchema.svg | 198 +++ Documentation/Images/Associations2/Makefile | 3 + .../Images/Associations2/RecursiveSchema.svg | 91 ++ .../Associations2/TreeOfAssociationKeys.svg | 110 ++ .../TreeOfAssociationKeysMapping.svg | 130 ++ 12 files changed, 2667 insertions(+) create mode 100644 Documentation/AssociationsBasics.md create mode 100644 Documentation/Images/Associations2/AmbiguousForeignKeys.svg create mode 100644 Documentation/Images/Associations2/Associations.sketch create mode 100644 Documentation/Images/Associations2/BelongsToSchema.svg create mode 100644 Documentation/Images/Associations2/HasManySchema.svg create mode 100644 Documentation/Images/Associations2/HasManyThroughSchema.svg create mode 100644 Documentation/Images/Associations2/HasOneSchema.svg create mode 100644 Documentation/Images/Associations2/HasOneThroughSchema.svg create mode 100644 Documentation/Images/Associations2/Makefile create mode 100644 Documentation/Images/Associations2/RecursiveSchema.svg create mode 100644 Documentation/Images/Associations2/TreeOfAssociationKeys.svg create mode 100644 Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md new file mode 100644 index 000000000..d85dbc48c --- /dev/null +++ b/Documentation/AssociationsBasics.md @@ -0,0 +1,1375 @@ +GRDB Associations +================= + +- [Associations Benefits] +- [The Types of Associations] + - [BelongsTo] + - [HasOne] + - [HasMany] + - [Choosing Between BelongsTo and HasOne] + - [Self Joins] +- [Associations and the Database Schema] + - [Convention for Database Table Names] + - [Convention for the BelongsTo Association] + - [Convention for the HasOne Association] + - [Convention for the HasMany Association] + - [Foreign Keys] +- [Building Requests from Associations] + - [Requesting Associated Records] + - [Joining Methods] + - [Combining Associations] + - [Filtering Associations] + - [Sorting Associations] + - [Columns Selected by an Association] + - [Table Aliases] +- [Fetching Values from Associations] + - [The Structure of a Joined Request] + - [Decoding a Joined Request with a Decodable Record] + - [Decoding a Joined Request with FetchableRecord] +- [Known Issues] +- [Future Directions] + + +## Associations Benefits + +**An association is a connection between two [Record] types.** + +Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book: + +```swift +struct Author: TableRecord, FetchableRecord { + var id: Int64 + var name: String +} + +struct Book: TableRecord, FetchableRecord { + var id: Int64 + var authorId: Int64? + var title: String +} +``` + +Now, suppose we wanted to load all books from an existing author. We'd need to do something like this: + +```swift +let author: Author = ... +let books = try Book + .filter(Column("authorId") == author.id) + .fetchAll(db) +``` + +Or, loading all pairs of books along with their authors: + +```swift +struct BookInfo { + var book: Book + var author: Author? +} + +let books = try Book.fetchAll(db) +let bookInfos = books.map { book -> BookInfo in + let author = try Author.fetchOne(key: book.authorId) + return BookInfo(book: book, author: author) +} +``` + +With GRDB associations, we can streamline these operations (and others), by declaring the connections between books and authors. Here is how we define associations, and properties that access them: + +```swift +extension Author { + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +extension Book { + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} +``` + +Loading all books from an existing author is now easier: + +```swift +let books = try author.books.fetchAll(db) +``` + +As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*: + +```swift +struct BookInfo: FetchableRecord, Codable { + let book: Book + let author: Author? +} + +let request = Book.including(optional: Book.author) +let bookInfos = BookInfo.fetchAll(db, request) +``` + + +The Types of Associations +========================= + +GRDB handles three types of associations: + +- **BelongsTo** +- **HasOne** +- **HasMany** + +An association declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods. + +Each one of the three types of associations is appropriate for a particular database situation. + +- [BelongsTo] +- [HasOne] +- [HasMany] +- [Choosing Between BelongsTo and HasOne] +- [Self Joins] + + +## BelongsTo + +The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such as each instance of the declaring record "belongs to" an instance of the other record. + +For example, if your application includes authors and books, and each book is assigned its author, you'd declare the association this way: + +```swift +struct Book: TableRecord { + static let author = belongsTo(Author.self) + ... +} + +struct Author: TableRecord { + ... +} +``` + +The **BelongsTo** association between a book and its author needs that the database table for books has a column that points to the table for authors: + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +See [Convention for the BelongsTo Association] for some sample code that defines the database schema for such an association. + + +## HasOne + +The **HasOne** association also sets up a one-to-one connection from a record type to another record type, but with different semantics, and underlying database schema. It is usually used when an entity has been denormalized into two database tables. + +For example, if your application has one database table for countries, and another for their demographic profiles, you'd declare the association this way: + +```swift +struct Country: TableRecord { + static let demographics = hasOne(Demographics.self) + ... +} + +struct Demographics: TableRecord { + ... +} +``` + +The **HasOne** association between a country and its demographics needs that the database table for demographics has a column that points to the table for countries: + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +See [Convention for the HasOne Association] for some sample code that defines the database schema for such an association. + + +## HasMany + +The **HasMany** association indicates a one-to-many connection between two record types, such as each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association. + +For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the association this way: + +```swift +struct Author: TableRecord { + static let books = hasMany(Book.self) +} + +struct Book: TableRecord { + ... +} +``` + +The **HasMany** association between an author and its books needs that the database table for books has a column that points to the table for authors: + +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) + +See [Convention for the HasMany Association] for some sample code that defines the database schema for such an association. + + +## Choosing Between BelongsTo and HasOne + +When you want to set up a one-to-one relationship between two record types, you'll need to add a **BelongsTo** association to one, and a **HasOne** association to the other. How do you know which is which? + +The distinction is in where you place the database foreign key. The record that points to the other one has the **BelongsTo** association. The other record has the **HasOne** association: + +A country **has one** demographic profile, a demographic profile **belongs to** a country: + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +```swift +struct Country: TableRecord, FetchableRecord { + static let demographics = hasOne(Demographics.self) + ... +} + +struct Demographics: TableRecord, FetchableRecord { + static let country = belongsTo(Demographics.self) + ... +} +``` + +## Self Joins + +When designing your data model, you will sometimes find a record that should have a relation to itself. For example, you may want to store all employees in a single database table, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations: + +```swift +struct Employee { + static let subordinates = hasMany(Employee.self) + static let manager = belongsTo(Employee.self) +} +``` + +![RecursiveSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/RecursiveSchema.svg) + +The matching [migration] would look like: + +```swift +migrator.registerMigration("Employees") { db in + try db.create(table: "employee") { t in + t.autoIncrementedPrimaryKey("id") + t.column("managerId", .integer) + .indexed() + .references("employee", onDelete: .restrict) + t.column("name", .text) + } +} +``` + + +Associations and the Database Schema +==================================== + +**Associations are grounded in the database schema, the way database tables are defined.** + +For example, a **[BelongsTo]** association between a book and its author needs that the database table for books has a column that points to the table for authors. + +GRDB also comes with several *conventions* for defining your database schema. + +Those conventions help associations be convenient and, generally, "just work". When you can't, or don't want to follow conventions, you will have to override the expected defaults in your Swift code. + +- [Convention for Database Table Names] +- [Convention for the BelongsTo Association] +- [Convention for the HasOne Association] +- [Convention for the HasMany Association] +- [Foreign Keys] + + +## Convention for Database Table Names + +**Database table names should be singular and camel-cased.** + +This is the same convention as Swift identifiers for variables and properties. For example: `book`, `author`, `postalAddress`. + +This convention helps fetching values from associations. It is used, for example, in the sample code below, where we load all pairs of books along with their authors: + +```swift +// The Book record +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" + static let author = belongsTo(Author.self) + ... +} + +// The Author record +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" + ... +} + +// A pair made of a book and its author +struct BookInfo: FetchableRecord, Codable { + let book: Book + let author: Author? +} + +let request = Book.including(optional: Book.author) +let bookInfos = BookInfo.fetchAll(db, request) +``` + +This sample code only works if the database table for authors is called "author". This name "author" is the key that helps BookInfo initialize its `author` property. + +If the database schema does not follow this convention, and has, for example, database tables named with plural names (`authors` and `books`), you can still use associations. But you need to help row consumption by providing the required key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self).forKey("author") // <- +} +``` + +See [The Structure of a Joined Request] for more information. + + +## Convention for the BelongsTo Association + +**[BelongsTo] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Books and Authors") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") // (1) + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer) // (2) + .notNull() // (3) + .indexed() // (4) + .references("author", onDelete: .cascade) // (5) + t.column("title", .text) + } +} +``` + +1. The `author` table has a primary key. +2. The `book.authorId` column is used to link a book to the author it belongs to. +3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. +4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. +5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. + +The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" + static let author = belongsTo(Author.self) +} + +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use **BelongsTo** associations. But your help is needed to define the missing foreign key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Convention for the HasOne Association + +**[HasOne] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Countries") { db in + try db.create(table: "country") { t in + t.column("code", .text).primaryKey() // (1) + t.column("name", .text) + } + try db.create(table: "demographics") { t in + t.autoIncrementedPrimaryKey("id") + t.column("countryCode", .text) // (2) + .notNull() // (3) + .unique() // (4) + .references("country", onDelete: .cascade) // (5) + t.column("population", .integer) + t.column("density", .double) + } +} +``` + +1. The `country` table has a primary key. +2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. +3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country. +4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile. +5. Create a foreign key from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information. + +The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Country: FetchableRecord, TableRecord { + static let databaseTableName = "country" + static let demographics = hasOne(Demographics.self) +} + +struct Demographics: FetchableRecord, TableRecord { + static let databaseTableName = "demographics" +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use HasOne associations. But your help is needed to define the missing foreign key: + +```swift +struct Book: FetchableRecord, TableRecord { + static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Convention for the HasMany Association + +**[HasMany] associations should be supported by an SQLite foreign key.** + +Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. + +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) + +The matching [migration] could look like: + +```swift +migrator.registerMigration("Books and Authors") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") // (1) + t.column("name", .text) + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer) // (2) + .notNull() // (3) + .indexed() // (4) + .references("author", onDelete: .cascade) // (5) + t.column("title", .text) + } +} +``` + +1. The `author` table has a primary key. +2. The `book.authorId` column is used to link a book to the author it belongs to. +3. Make the `book.authorId` column not null if you want SQLite to guarantee that all books have an author. +4. Create an index on the `book.authorId` column in order to ease the selection of an author's books. +5. Create a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book refers to a missing author. The `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. + +The example above uses auto-incremented primary keys. But generally speaking, all primary keys are supported. + +Following this convention lets you write, for example: + +```swift +struct Book: FetchableRecord, TableRecord { + static let databaseTableName = "book" +} + +struct Author: FetchableRecord, TableRecord { + static let databaseTableName = "author" + static let books = hasMany(Book.self) +} +``` + +If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use **HasMany** associations. But your help is needed to define the missing foreign key: + +```swift +struct Author: FetchableRecord, TableRecord { + static let books = hasMany(Book.self, using: ForeignKey(...)) +} +``` + +See [Foreign Keys] for more information. + + +## Foreign Keys + +**Associations can automatically infer the foreign keys that define how two database tables are linked together.** + +In the example below, the `book.authorId` column is automatically used to link a book to its author: + +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) + +```swift +struct Book: TableRecord { + static let author = belongsTo(Author.self) +} + +struct Author: TableRecord { + static let books = hasMany(Book.self) +} +``` + +But this requires the database schema to define a foreign key between the book and author database tables (see [Convention for the BelongsTo Association]). + +Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. + +![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) + +When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to author", or "Could not infer foreign key from book to author". + +Your help is needed. You have to instruct GRDB which foreign key to use: + +```swift +struct Book: TableRecord { + // Define foreign keys + static let authorForeignKey = ForeignKey(["authorId"])) + static let translatorForeignKey = ForeignKey(["translatorId"])) + + // Use foreign keys to define associations: + static let author = belongsTo(Person.self, using: authorForeignKey) + static let translator = belongsTo(Person.self, using: translatorForeignKey) +} +``` + +Foreign keys are always defined from the table that contains the columns at the origin of the foreign key. Person's symmetric **HasMany** associations reuse Book's foreign keys: + +```swift +struct Person: TableRecord { + static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey) + static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey) +} +``` + +Foreign keys can also be defined from `Column`: + +```swift +struct Book: TableRecord { + static let authorId = Column("authorId") + static let translatorId = Column("translatorId") + + static let authorForeignKey = ForeignKey([authorId])) + static let translatorForeignKey = ForeignKey([translatorId])) +} +``` + +When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key: + +```swift +struct Book: TableRecord { + static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) + static let author = belongsTo(Person.self, using: authorForeignKey) +} +``` + + +Building Requests from Associations +=================================== + +**Once you have defined associations, you can define fetch request that involve several record types.** + +> :point_up: **Note**: Those requests are executed by SQLite as *SQL joined queries*. In all examples below, we'll show the SQL queries executed by our association-based requests. You can ignore them if you are not familiar with SQL. + +Fetch requests do not visit the database until you fetch values from them. This will be covered in [Fetching Values from Associations]. But before you can fetch anything, you have to describe what you want to fetch. This is the topic of this chapter. + +- [Requesting Associated Records] +- [Joining Methods] +- [Combining Associations] +- [Filtering Associations] +- [Sorting Associations] +- [Columns Selected by an Association] +- [Table Aliases] + + +## Requesting Associated Records + +**You can use associations to build requests for associated records.** + +For example, given a `Book.author` **[BelongsTo]** association, you can build a request for the author of a book. In the example below, we return this request from the `Book.author` property: + +```swift +struct Book: PersistableRecord { + static let author = belongsTo(Author.self) + + /// The request for a book's author + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} +``` + +This request can fetch a book's author: + +```swift +let book: Book = ... +let author = try book.author.fetchOne(db) // Author? +``` + +**[HasOne]** and **[HasMany]** associations can also build requests for associated records. For example: + +```swift +struct Author: PersistableRecord { + static let books = hasMany(Book.self) + + /// The request for an author's books + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +let author: Author = ... +let books = try author.books.fetchAll(db) // [Book] +``` + +Those requests can also turn out useful when you want to track their changes with database observation tools like [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): + +```swift +// Track changes in the author's books: +let author: Author = ... +author.books.rx + .fetchAll(in: dbQueue) + .subscribe(onNext: { (books: [Book]) in + print("Author's book have changed") + }) +``` + + +## Joining Methods + +**You build requests that involve several records with the four "joining methods":** + +- `including(optional: association)` +- `including(required: association)` +- `joining(optional: association)` +- `joining(required: association)` + +Before we describe them in detail, let's see a few requests they can build: + +```swift +/// All books with their respective authors +let request = Book + .including(required: Book.author) + +/// All books with their respective authors, sorted by title +let request = Book + .order(Column("title")) + .including(required: Book.author) + +/// All books written by a French author +let request = Book + .joining(required: Book.author.filter(Column("countryCode") == "FR")) +``` + +The pattern is always the same: you start from a base request, that you extend with one of the joining methods. + +**To choose the joining method you need, you ask yourself two questions:** + +1. Should the associated records be fetched along with the base records? + + If yes, use `including(...)`. Otherwise, use `joining(...)`. + + For example, to load all books with their respective authors, you want authors to be fetched, and you use `including`: + + ```swift + /// All books with their respective authors + let request = Book + .including(required: Book.author) + ``` + + On the other side, to load all books written by a French author, you sure need to filter authors, but you don't need them to be present in the fetched results. You prefer `joining`: + + ```swift + /// All books written by a French author + let request = Book + .joining(required: Book.author.filter(Column("countryCode") == "FR")) + ``` + +2. Should the request allow missing associated records? + + If yes, choose the `optional` variant. Otherwise, choose `required`. + + For example, to load all books with their respective authors, even if the book has no recorded author, you'd use `including(optional:)`: + + ```swift + /// All books with their respective (eventual) authors + /// (One Thousand and One Nights should be there) + let request = Book + .including(optional: Book.author) + ``` + + You can remember to use `optional` when the fetched associated records should feed optional Swift values, of type `Author?`. Conversely, when the fetched results feed non-optional values of type `Author`, prefer `required`. + + Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through. + + For example, consider this request: + + ```swift + let request = Book + .joining(optional: Book.author.filter(Column("countryCode") == "FR")) + ``` + + It fetches books that have a French author, but also those who don't :sweat_smile:. It's just another way to tell `Book.all()`. But we'll see below that such join can turn out useful. + + Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins. + + +## Combining Associations + +**Associations can be combined in order to build more complex requests.** + +You can join several associations in parallel: + +```swift +// SELECT book.*, person1.*, person2.* +// FROM book +// JOIN person person1 ON person1.id = book.authorId +// LEFT JOIN person person2 ON person2.id = book.translatorId +let request = Book + .including(required: Book.author) + .including(optional: Book.translator) +``` + +The request above fetches all books, along with their author and eventual translator. + +You can chain associations in order to jump from a record to another: + +```swift +// SELECT book.*, person.*, country.* +// FROM book +// JOIN person ON person.id = book.authorId +// LEFT JOIN country ON country.code = person.countryCode +let request = Book + .including(required: Book.author + .including(optional: Person.country)) +``` + +The request above fetches all books, along with their author, and their author's country. + +When you chain associations, you can avoid fetching intermediate values by replacing the `including` method with `joining`: + +```swift +// SELECT book.*, country.* +// FROM book +// LEFT JOIN person ON person.id = book.authorId +// LEFT JOIN country ON country.code = person.countryCode +let request = Book + .joining(optional: Book.author + .including(optional: Person.country)) +``` + +The request above fetches all books, along with their author's country. + +> :warning: **Warning**: you can not currently chain a required association behind an optional association: +> +> ```swift +> // Not implemented +> let request = Book +> .joining(optional: Book.author +> .including(required: Person.country)) +> ``` +> +> This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests. + + +## Filtering Associations + +**You can filter associated records.** + +The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can filter associated records as well: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// AND person.countryCode = 'FR' +let frenchAuthor = Book.author.filter(Column("countryCode") == "FR") +let request = Book.joining(required: frenchAuthor) +``` + +The request above fetches all books written by a French author. + +**There are more filtering options:** + +- Filtering on conditions that involve several tables. +- Filtering in the WHERE clause instead of the ON clause (can be useful when you are skilled enough in SQL to make the difference). + +Those extra filtering options require **[Table Aliases]**, introduced below. + + +## Sorting Associations + +**You can sort fetched results according to associated records.** + +The `order()` method, that you already know for [sorting simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can sort associated records as well: + +```swift +// SELECT book.*, person.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY person.name +let sortedAuthor = Book.author.order(Column("name")) +let request = Book.including(required: sortedAuthor) +``` + +When you sort both the base record on the associated record, the request is sorted on the base record first, and on the associated record next: + +```swift +// SELECT book.*, person.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY book.publishDate DESC, person.name +let sortedAuthor = Book.author.order(Column("name")) +let request = Book + .including(required: sortedAuthor) + .order(Column("publishDate").desc) +``` + +**There are more sorting options:** + +- Sorting on expressions that involve several tables. +- Changing the order of the sorting terms (such as sorting on author name first, and then publish date). + +Those extra sorting options require **[Table Aliases]**, introduced below. + + +## Columns Selected by an Association + +By default, associated records include all their columns: + +```swift +// SELECT book.*, author.* +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.author) +``` + +**The selection can be changed for each individual request, or for all requests including a given type.** + +To specify the selection of an associated record in a specific request, use the `select` method: + +```swift +// SELECT book.*, author.id, author.name +// FROM book +// JOIN author ON author.id = book.authorId +let restrictedAuthor = Book.author.select(Column("id"), Column("name")) +let request = Book.including(required: restrictedAuthor) +``` + +To specify the default selection for all inclusions of a given type, define the `databaseSelection` property: + +```swift +struct RestrictedAuthor: TableRecord { + static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] +} + +struct ExtendedAuthor: TableRecord { + static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] +} + +extension Book { + static let restrictedAuthor = belongsTo(RestrictedAuthor.self) + static let extendedAuthor = belongsTo(ExtendedAuthor.self) +} + +// SELECT book.*, author.id, author.name +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.restrictedAuthor) + +// SELECT book.*, author.*, author.rowid +// FROM book +// JOIN author ON author.id = book.authorId +let request = Book.including(required: Book.extendedAuthor) +``` + +Modifying `databaseSelection` not only affects joined requests, but all requests built from the modified record. This is how records make sure they are always fed with the columns they need, no more, no less: + +```swift +// SELECT id, name FROM author +let request = RestrictedAuthor.all() +``` + +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#columns-selected-by-a-request) for further information. + + +## Table Aliases + +In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example. + +Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author eventual death date. + +Let's first see a wrong way to do it: + +```swift +// A wrong request: +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// WHERE book.publishDate >= book.deathDate +let request = Book + .joining(required: Book.author) + .filter(Column("publishDate") >= Column("deathDate")) +``` + +When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate". + +That is because the "deathDate" column has been used for filtering books, when it is defined on the person database table. + +To fix this error, we need a **table alias**: + +```swift +let authorAlias = TableAlias() +``` + +We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// WHERE book.publishDate >= person.deathDate +let request = Book + .joining(required: Book.author.aliased(authorAlias)) + .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) +``` + +**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first: + +```swift +// SELECT book.* +// FROM book +// JOIN person ON person.id = book.authorId +// ORDER BY person.name, book.publishDate +let request = Book + .joining(required: Book.author.aliased(authorAlias)) + .order(authorAlias[Column("name")], Column("publishDate")) +``` + +**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it: + +```swift +// SELECT myBook.* +// FROM book myBook +// JOIN person myAuthor ON myAuthor.id = myBook.authorId +// AND myAuthor.countryCode = 'FR' +// WHERE myBook.publishDate >= myAuthor.deathDate +let bookAlias = TableAlias(name: "myBook") +let authorAlias = TableAlias(name: "myAuthor") +let request = Book.aliased(bookAlias) + .joining(required: Book.author.aliased(authorAlias) + .filter(sql: "myAuthor.countryCode = ?", arguments: ["FR"])) + .filter(sql: "myBook.publishDate >= myAuthor.deathDate") +``` + + +Fetching Values from Associations +================================= + +We have seen in [Building Requests from Associations] how to define requests that involve several records by the mean of [Joining Methods]. + +If your application needs to display a list of books with information about their author, country, and cover image, you may build the following joined request: + +```swift +// SELECT book.*, author.*, country.*, coverImage.* +// FROM book +// JOIN author ON author.id = book.authorId +// LEFT JOIN country ON country.code = author.countryCode +// LEFT JOIN coverImage ON coverImage.bookId = book.id +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +**Now is the time to tell how joined requests should be consumed.** + +As always in GRDB, requests can be consumed as raw database rows, or as well-structured and convenient records. + +The request above can be consumed into the following record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +If we consume raw rows, we start to see what's happening under the hood: + +```swift +let row = try Row.fetchOne(db, request)! // Row +print(row.debugDescription) +// ▿ [id:1, authorId:2, title:"Moby-Dick"] +// unadapted: [id:1, authorId:2, title:"Moby-Dick", id:2, name:"Herman Melville", countryCode:"US", code:"US", name:"United States of America", id:42, imageId:1, path:"moby-dick.jpg"] +// - author: [id:2, name:"Herman Melville", countryCode:"US"] +// - country: [code:"US", name:"United States of America"] +// - coverImage: [id:42, imageId:1, path:"moby-dick.jpg"] +``` + +- [The Structure of a Joined Request] +- [Decoding a Joined Request with a Decodable Record] +- [Decoding a Joined Request with FetchableRecord] + + +## The Structure of a Joined Request + +**Joined request define a tree of associated records identified by "association keys".** + +Below, author and cover image are both associated to book, and country is associated to author: + +```swift +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +This request builds the following **tree of association keys**: + +![TreeOfAssociationKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeys.svg) + +**Association keys** are strings. They are the names of the database tables of associated records (unless you specify otherwise, as we'll see below). + +Those keys are associated with slices in the fetched rows: + +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) + +We'll see below how this tree of association keys and row slices can feed a Decodable record type. We'll then add some details by using FetchableRecord without Decodable support. + + +## Decoding a Joined Request with a Decodable Record + +When **association keys** match the property names of a Decodable record, you get free decoding of joined requests into this record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +We see that a hierarchical tree has been flattened in the `BookInfo` record. + +This flattening is made possible because the BookInfo initializer generated by the Decodable protocol matches **coding keys** with **association keys** by performing a breadth-first search in the tree of association keys. + +This deserves a little explanation: + +You known that the Decodable protocol feeds a value's properties by looking for **coding keys**. For example, the standard built-in JSONDecoder matches those coding keys with dictionary keys in a JSON object. The GRDB record decoder also matches coding keys, but with association keys: + +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) + +Practically speaking, the BookInfo initializer first looks for the "book" coding key. This key is not found anywhere in the tree of association keys, so the book property is initialized from the row slice associated with the root of the tree, which contains book columns. + +The BookInfo initializer then looks for the "author", "country", and "coverImage" coding keys. All those are found in the tree of association keys, and each property is initialized from its matching row slice. + +The key lookup digs into the tree of association keys, and stops as soon as a key as been found, digging into deep tree levels only if the key was not found in higher levels (that's called a "breadth-first search"). This is how we can decode a hierarchical tree into a flat record. + +But sometimes your decoded records will have better reflect the hierarchical structure of the request: + + +### Decoding a Hierarchical Decodable Record + +Some requests are better decoded with a Decodable record that reflects the hierarchical structure of the request. + +```swift +let request = Book + .including(optional: Bool.coverImage) + .including(required: Book.author + .including(optional: Person.country)) + .including(optional: Book.translator + .including(optional: Person.country)) +``` + +This requests for all books, with their cover images, and their authors and translators. Those people are themselves decorated with their respective nationalities. + +We plan to decode this request into is the following record: + +```swift +struct BookInfo: FetchableRecord, Decodable { + struct AuthorInfo: Decodable { + var author: Author + var country: Country? + } + var book: Book + var authorInfo: AuthorInfo + var translatorInfo: AuthorInfo? + var coverImage: CoverImage? +} +``` + +This request needs a little preparation: we need **association keys** that match the **coding keys** for the authorInfo and translatorInfo properties. + +And who is the most able to know those coding keys? BookInfo itself, thanks to its `CodingKeys` enum that was automatically generated by the Swift compiler. We thus define the `BookInfo.all()` method that builds our request: + +```swift +extension BookInfo { + static func all() -> QueryInterfaceRequest { + return Book + .including(optional: Bool.coverImage) + .including(required: Book.author + .forKey(CodingKeys.authorInfo) // (1) + .including(optional: Person.country)) + .including(optional: Book.translator + .forKey(CodingKeys.translatorInfo) // (1) + .including(optional: Person.country)) + .asRequest(of: BookInfo.self) // (2) + } +} + +let bookInfos = try BookInfo.all().fetchAll(db, request) // [BookInfo] +``` + +1. The `forKey(_:)` method changes the association key, so that the associated records can feed their target properties. +2. The `asRequest(of:)` method turns the request into a request of BookInfo. See [Custom Requests] for more information. + + +### Debugging Joined Request Decoding + +When you have difficulties building a Decodable record that successfully decodes a joined request, we advise to temporarily decode raw database rows, and inspect them. + +```swift +let request = Book + .including(required: Book.author + .including(optional: Author.country)) + .including(optional: Bool.coverImage) + +let rows = try Row.fetchAll(db, request) +print(rows[0]) +// Prints: +// ▿ [id:1, authorId:2, title:"Moby-Dick"] +// unadapted: [id:1, authorId:2, title:"Moby-Dick", id:2, name:"Herman Melville", countryCode:"US", code:"US", name:"United States of America", id:NULL, imageId:NULL, path:NULL] +// - person: [id:2, name:"Herman Melville", countryCode:"US"] +// - country: [code:"US", name:"United States of America"] +// - coverImage: [id:NULL, imageId:NULL, path:NULL] +``` + +There are two important things to look into the row debugging description: + +- the **association keys**: "person", "country", and "coverImage" in our example +- associated rows that contain only null values (coverImage). + +The associated rows that contain only null values are easy to deal with: null rows loaded from optional associated records should be decoded into Swift optionals: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author // .including(required: Book.author) + var country: Country? // .including(optional: Author.country) + var coverImage: CoverImage? // .including(optional: Bool.coverImage) +} +``` + +**Association keys** may not match the property names of your Decodable record. In this case, use the `forKey(_:)` method. + +This can be done at the request level: + +```swift +struct BookInfo: FetchableRecord, Decodable { + var book: Book + var author: Author // Expect "author" association key + var country: Country? + var coverImage: CoverImage? +} + +let request = Book + .including(required: Book.author + .forKey("author") // Change association key + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +Association keys can also be defined right into the definition of the association: + +```swift +struct Book { + static let author = belongsTo(Person.self).forKey("author") +} + +let request = Book + .including(required: Book.author // "author" association key + .including(optional: Author.country)) + .including(optional: Bool.coverImage) +``` + +The best choice is up to you and the structure of your application. See also [Decoding a Hierarchical Decodable Record] for further discussion about decoding keys. + + +## Decoding a Joined Request with FetchableRecord + +When [Dedocable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding. + +The `init(row:)` initializer of the FetchableRecord protocol is what you look after: + +```swift +struct BookInfo: FetchableRecord { + var book: Book + var author: Author + var country: Country? + var coverImage: CoverImage? + + init(row: Row) { + book = Book(row: row) + author = row["author"] + country = row["country"] + coverImage = row["coverImage"] + } +} + +let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] +``` + +You are already familiar with row subscripts to decode [database values](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#column-values): + +```swift +let name: String = row["name"] +``` + +When you extract a record instead of a value from a row, GRDB perfoms a breadth-first search in the tree of **association keys** defined by the joined request. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil: + +```swift +let author: Author = row["author"] +let country: Country? = row["country"] +``` + +You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information. + + +## Known Issues + +**You can't chain a required association on an optional association.** + +```swift +// NOT IMPLEMENTED +let request = Book + .joining(optional: Book.author + .including(required: Person.country)) +``` + +This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests. + +**Joining two associations with the same association key at the same level is undefined behavior.** + +Since [association keys](#the-structure-of-a-joined-request) are the names of the joined tables unless specified otherwise, this exceptional condition is unfortunately easy to trigger: + +```swift +// UNDEFINED BEHAVIOR +let request = Book + .including(Book.author) // key "author" + .including(Book.author) // key "author" +``` + +This code currently compiles, and generates valid SQL. But GRDB may change the generated SQL in the future. + +To join the same table twice, and make sure GRDB does not modify the fetched results in some future release, make sure no two associations have the same name on a given level: + +```swift +// OK +let request = Book + .including(Book.author.forKey("firstAuthor")) + .including(Book.author.forKey("secondAuthor")) +``` + + +## Future Directions + +The APIs that have been described above do not cover the whole topic of joined requests. Among the biggest omissions, there is: + +- One can not yet join two tables without a foreign key. One can not build the plain `SELECT * FROM a JOIN b`, for example. + +- One can not yet express requests such as "all authors with all their books". + +- A common use case of associations is aggregations, such as fetching all authors with the number of books they have written: + + ```swift + let request = Author.annotate(with: Author.books.count) + ``` + +- There's no HasOneThrough and HasManyThrough association, which would allow to skip intermediate bridge records when building requests. + +Those features are not present yet because they hide several very tough challenges. Come [discuss](http://twitter.com/groue) for more information, or if you wish to help turning those features into reality. + + +--- + +This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors. + +--- + +### LICENSE + +**GRDB** + +Copyright (C) 2018 Gwendal Roué + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +**Ruby on Rails documentation** + +Copyright (c) 2005-2018 David Heinemeier Hansson + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +[Associations Benefits]: #associations-benefits +[BelongsTo]: #belongsto +[HasOne]: #hasone +[HasMany]: #hasmany +[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone +[Self Joins]: #self-joins +[The Types of Associations]: #the-types-of-associations +[Codable]: https://developer.apple.com/documentation/swift/codable +[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#fetchablerecord-protocols +[migration]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#migrations +[Record]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#records +[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions +[Associations and the Database Schema]: #associations-and-the-database-schema +[Convention for Database Table Names]: #convention-for-database-table-names +[Convention for the BelongsTo Association]: #convention-for-the-belongsto-association +[Convention for the HasOne Association]: #convention-for-the-hasone-association +[Convention for the HasMany Association]: #convention-for-the-hasmany-association +[Foreign Keys]: #foreign-keys +[Building Requests from Associations]: #building-requests-from-associations +[Fetching Values from Associations]: #fetching-values-from-associations +[Combining Associations]: #combining-associations +[Requesting Associated Records]: #requesting-associated-records +[Joining Methods]: #joining-methods +[Filtering Associations]: #filtering-associations +[Sorting Associations]: #sorting-associations +[Columns Selected by an Association]: #columns-selected-by-an-association +[Table Aliases]: #table-aliases +[The Structure of a Joined Request]: #the-structure-of-a-joined-request +[Decoding a Joined Request with a Decodable Record]: #decoding-a-joined-request-with-a-decodable-record +[Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record +[Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord +[Custom Requests]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#custom-requests +[Known Issues]: #known-issues +[Future Directions]: #future-directions +[Row Adapters]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#row-adapters \ No newline at end of file diff --git a/Documentation/Images/Associations2/AmbiguousForeignKeys.svg b/Documentation/Images/Associations2/AmbiguousForeignKeys.svg new file mode 100644 index 000000000..67ac61af5 --- /dev/null +++ b/Documentation/Images/Associations2/AmbiguousForeignKeys.svg @@ -0,0 +1,154 @@ + + + + AmbiguousForeignKeys + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + translatorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + person + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/Associations.sketch b/Documentation/Images/Associations2/Associations.sketch new file mode 100644 index 0000000000000000000000000000000000000000..561df5fc63bc33e6de919f451adf119e2b19552b GIT binary patch literal 406782 zcmcfobC4%N1GR~^ZQHhOYudJL+qP}nw!5co8`H+Le(m0Q-+S+Ozuk@4h~3!Tip+?t zO4L795htH>Qc)HZ3=Ieb2ny&wS2T;$04g*PkRcur5d6P;QwI|_J2QJ%25T1w`x~uI z`|U}TuQb@cJ*p8k6ws5R>>A4`4(cdv3gN+7GBXC8XcTh9&pVa6v33-4&fj^!e~7{0 zIDM+>dHky7m%m${sV94%yPxaP(}yS$qPw3VatdSuu)*C7hJc09-s%gh?aC`&wt{P; zZt^D&X)Q$>)=$mUksXn>qpaDU&SHLxX6Tw@XUj~3P=cGOt8+blOmNn9J`AIA^7WN> zVM;bo3~)TXZCG*a-dtRqo&pjSD(EF>86&mtuzYt_(e0fhSl`95ZV>VSX6R*3%v)#v zS$Qw>y?&~3mwp&}5KZ#EG%$#u&RQ$_+G6NDj$o1XeF6YjtSE}2U8fCjP2*$tRqR_F1h;8UT=nWK4T(rf*#5x7Qt=C*t(zL=t#rqwz#YhB2LJ0 z-4!9y4iJ1U)u=%QTyIk48o%@vmX~TH3Nw8+LmZs90U0`^4lmR)WZ8S)4e7drm2VIP^X5`X zb=?ZNLGWx5X4#iMfFnYC)R!>*aM3oZ3;+Zk*4sNE37v@#iE!g}g`W^qUp>id`~G*f z%6jkHu}XJcUoAk%B0s+p2CwF=tA9Y^alxZ6S&$KL8EAk4d_LqS0}skt!H`?RN)}|@ z3bwesHHwbbPR)e9Y62jno=KP#azze+8Dc2g4mjkzUVIG??U;pQf5#E=)>LLLKZA;E}A{V2aG`EbQ-^e<6E zi>0~Ov2EvH?#G0&72{y}eI;2%W2`cqERd`a0?|kx%`^V-J=?UtcK+=l&s;5@@v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-NE~)(Co9BKPP;)ZHehQC7sCHOTdCQ+uTF(~A z99+7f%;OxM(1^p{Ga8Df9W1H1#cxqG%<;9nlYV~^Qsx6Kqy;}^|9W=GwAeefAF}M1$}4(Y+Rbf?_*F zM`zAMN5}Ge3mqNU@t>EKtEH#2wTp*{gS)HCe}6URO6|M68taKOhF zw$|>Vsxq>wsxsGApc2>AB%qSlB-EhSFJHe56;qMEA|b6ND=8~}jpo5KI)-klvD4Az z$J71S!S&_${d4duS7a}%Ub`j+Rl9yg6)LGJE(^UTD(^b literal 0 HcmV?d00001 diff --git a/Documentation/Images/Associations2/BelongsToSchema.svg b/Documentation/Images/Associations2/BelongsToSchema.svg new file mode 100644 index 000000000..720e2bd11 --- /dev/null +++ b/Documentation/Images/Associations2/BelongsToSchema.svg @@ -0,0 +1,133 @@ + + + + BelongsToSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + author + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasManySchema.svg b/Documentation/Images/Associations2/HasManySchema.svg new file mode 100644 index 000000000..189ed0188 --- /dev/null +++ b/Documentation/Images/Associations2/HasManySchema.svg @@ -0,0 +1,135 @@ + + + + HasManySchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + authorId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + author + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasManyThroughSchema.svg b/Documentation/Images/Associations2/HasManyThroughSchema.svg new file mode 100644 index 000000000..a3219c05f --- /dev/null +++ b/Documentation/Images/Associations2/HasManyThroughSchema.svg @@ -0,0 +1,185 @@ + + + + HasManyThroughSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + countryCode + + + text + + + + + + + + citizenId + + + integer + + + + + + + + issueDate + + + date + + + + + + passport + + + + + + + + + + + + + + + + code + + + text + + + + + + + + name + + + text + + + + + + country + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + citizen + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasOneSchema.svg b/Documentation/Images/Associations2/HasOneSchema.svg new file mode 100644 index 000000000..b774fc54f --- /dev/null +++ b/Documentation/Images/Associations2/HasOneSchema.svg @@ -0,0 +1,153 @@ + + + + HasOneSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + countryCode + + + text + + + + + + + + population + + + integer + + + + + + + + density + + + double + + + + + + demographics + + + + + + + + + + + + + + + + code + + + text + + + + + + + + name + + + text + + + + + + + + + + + + + + + + + + + + country + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/HasOneThroughSchema.svg b/Documentation/Images/Associations2/HasOneThroughSchema.svg new file mode 100644 index 000000000..cca317fce --- /dev/null +++ b/Documentation/Images/Associations2/HasOneThroughSchema.svg @@ -0,0 +1,198 @@ + + + + HasOneThroughSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + name + + + text + + + + + + library + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + libraryId + + + integer + + + + + + + + title + + + text + + + + + + book + + + + + + + + + + + + + + + + libraryId + + + integer + + + + + + + + street + + + text + + + + + + + + city + + + text + + + + + + address + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/Makefile b/Documentation/Images/Associations2/Makefile new file mode 100644 index 000000000..7c42c98f5 --- /dev/null +++ b/Documentation/Images/Associations2/Makefile @@ -0,0 +1,3 @@ +fixfonts: + sed -i '' -- 's/SFUIText-Regular, SF UI Text/-apple-system,sans-serif/g' *.svg + sed -i '' -- 's/SFUIText-Semibold, SF UI Text/-apple-system,sans-serif/g' *.svg diff --git a/Documentation/Images/Associations2/RecursiveSchema.svg b/Documentation/Images/Associations2/RecursiveSchema.svg new file mode 100644 index 000000000..9970827e3 --- /dev/null +++ b/Documentation/Images/Associations2/RecursiveSchema.svg @@ -0,0 +1,91 @@ + + + + RecursiveSchema + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id + + + integer + + + + + + + + managerId + + + integer + + + + + + + + name + + + text + + + + + + + + + + + + + employee + + + + + + + + + + + + + + + + diff --git a/Documentation/Images/Associations2/TreeOfAssociationKeys.svg b/Documentation/Images/Associations2/TreeOfAssociationKeys.svg new file mode 100644 index 000000000..d3d3032f7 --- /dev/null +++ b/Documentation/Images/Associations2/TreeOfAssociationKeys.svg @@ -0,0 +1,110 @@ + + + + TreeOfAssociationKeys + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + root + + + + + + + + + + + + + + "author" + + + + + + + + + + + + + + "coverImage" + + + + + + + + + + + + + + "country" + + + + + diff --git a/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg b/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg new file mode 100644 index 000000000..4a1d65d5b --- /dev/null +++ b/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg @@ -0,0 +1,130 @@ + + + + TreeOfAssociationKeysMapping + Created with Sketch. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + root + + + + + + + + + + + + + + "author" + + + + + + + + + + + + + + "coverImage" + + + + + + + + + + + + + + "country" + + + + + SELECT + book.* + , + author.* + , + country.* + , + coverImage.* + + FROM … + + + + + + From 4586eb9a82cfa1de62c0f8b6d9341b75b220509e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 18:27:59 +0200 Subject: [PATCH 192/348] Associations Documentation --- .../QueryInterface/Association/BelongsToAssociation.swift | 8 ++++---- GRDB/QueryInterface/Association/HasManyAssociation.swift | 8 ++++---- GRDB/QueryInterface/Association/HasOneAssociation.swift | 8 ++++---- GRDB/QueryInterface/QueryInterfaceRequest.swift | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index fbcc82e8d..4cc4de2ad 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -7,10 +7,10 @@ public struct BelongsToAssociation : Association, TableRequest wher public var key: String - // :nodoc: + /// :nodoc: public var databaseTableName: String { return RightAssociated.databaseTableName } - // :nodoc: + /// :nodoc: public let request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest @@ -22,14 +22,14 @@ public struct BelongsToAssociation : Association, TableRequest wher foreignKeyRequest: foreignKeyRequest) } - // :nodoc: + /// :nodoc: public func associationMapping(_ db: Database) throws -> AssociationMapping { return try AssociationMappingRequest .foreignKey(request: foreignKeyRequest, originIsLeft: true) .fetch(db) } - // :nodoc: + /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { return BelongsToAssociation( key: key, diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 8653413c2..acc642c00 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -7,10 +7,10 @@ public struct HasManyAssociation : Association, TableRequest where public var key: String - // :nodoc: + /// :nodoc: public var databaseTableName: String { return RightAssociated.databaseTableName } - // :nodoc: + /// :nodoc: public let request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest @@ -22,14 +22,14 @@ public struct HasManyAssociation : Association, TableRequest where foreignKeyRequest: foreignKeyRequest) } - // :nodoc: + /// :nodoc: public func associationMapping(_ db: Database) throws -> AssociationMapping { return try AssociationMappingRequest .foreignKey(request: foreignKeyRequest, originIsLeft: false) .fetch(db) } - // :nodoc: + /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { return HasManyAssociation( key: key, diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 0a7f4b85f..b18dacb9f 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -7,10 +7,10 @@ public struct HasOneAssociation : Association, TableRequest where public var key: String - // :nodoc: + /// :nodoc: public var databaseTableName: String { return RightAssociated.databaseTableName } - // :nodoc: + /// :nodoc: public let request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest @@ -22,14 +22,14 @@ public struct HasOneAssociation : Association, TableRequest where foreignKeyRequest: foreignKeyRequest) } - // :nodoc: + /// :nodoc: public func associationMapping(_ db: Database) throws -> AssociationMapping { return try AssociationMappingRequest .foreignKey(request: foreignKeyRequest, originIsLeft: false) .fetch(db) } - // :nodoc: + /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { return HasOneAssociation( key: key, diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 7c3ee6d17..07ed1eaf4 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -167,7 +167,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating } extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { - // :nodoc: + /// :nodoc: public var databaseTableName: String { return T.databaseTableName } From d6f088609e0157c25ae9483088be8fe531894cee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 18:34:49 +0200 Subject: [PATCH 193/348] Prevent chaining required association behind an optional one --- GRDB/QueryInterface/QueryInterfaceQuery.swift | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 8999861c2..902db778f 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -63,7 +63,7 @@ struct QueryInterfaceQuery { sql += try " FROM " + source.sourceSQL(db, &arguments) for join in joins { - sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier!) + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier!, isRequiredAllowed: true) } if let filter = try filterPromise.resolve(db) { @@ -425,11 +425,19 @@ struct AssociationJoin { var key: String var associationMapping: (Database) throws -> AssociationMapping - func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier) throws -> String { + func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier, isRequiredAllowed: Bool) throws -> String { + var isRequiredAllowed = isRequiredAllowed var sql = "" switch op { - case .optional: sql += "LEFT JOIN" - case .required: sql += "JOIN" + case .optional: + isRequiredAllowed = false + sql += "LEFT JOIN" + case .required: + guard isRequiredAllowed else { + // TODO: chainOptionalRequired + fatalError("Not implemented: chaining a required association behind an optional association") + } + sql += "JOIN" } let rightQualifier = rightQuery.qualifier! @@ -445,7 +453,7 @@ struct AssociationJoin { } for join in rightQuery.joins { - sql += try " " + join.joinSQL(db, &arguments, leftQualifier: rightQualifier) + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: rightQualifier, isRequiredAllowed: isRequiredAllowed) } return sql From 39c5313738911f7c1e0e056bef9ca410cfd0c75f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 18:45:51 +0200 Subject: [PATCH 194/348] Associations Documentation --- Documentation/AssociationsBasics.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index d85dbc48c..ba314792a 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1244,7 +1244,7 @@ You can also perform custom navigation in the tree by using *row scopes*. See [R ## Known Issues -**You can't chain a required association on an optional association.** +**You can't chain a required association on an optional association:** ```swift // NOT IMPLEMENTED @@ -1255,18 +1255,16 @@ let request = Book This code compiles, but you'll get a runtime fatal error "Not implemented: chaining a required association behind an optional association". Future versions of GRDB may allow such requests. -**Joining two associations with the same association key at the same level is undefined behavior.** - -Since [association keys](#the-structure-of-a-joined-request) are the names of the joined tables unless specified otherwise, this exceptional condition is unfortunately easy to trigger: +**You can't join two associations with the same [association key](#the-structure-of-a-joined-request) at the same level:** ```swift -// UNDEFINED BEHAVIOR +// NOT IMPLEMENTED let request = Book .including(Book.author) // key "author" .including(Book.author) // key "author" ``` -This code currently compiles, and generates valid SQL. But GRDB may change the generated SQL in the future. +This code compiles, but you'll get a runtime fatal error "The association key `author` is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.". Future versions of GRDB may allow such requests. To join the same table twice, and make sure GRDB does not modify the fetched results in some future release, make sure no two associations have the same name on a given level: From 83104769ef9d7e35db14d415dfb5b90a6617cf06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 29 Apr 2018 19:21:10 +0200 Subject: [PATCH 195/348] Conditional Conformance requires Swift 4.1 and Xcode 9.3+ --- .travis.yml | 150 ++++++++++++++++------------------------------------ Makefile | 18 +------ README.md | 7 +-- 3 files changed, 52 insertions(+), 123 deletions(-) diff --git a/.travis.yml b/.travis.yml index 416b9532c..164f49bb5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,198 +15,140 @@ jobs: ########################################### ## Test GRDB - # Test GRDBOSX (Xcode 9.2) + # Test GRDBOSX (Xcode 9.3) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBOSX (Xcode 9.2, macOS) + - TID=GRDBOSX (Xcode 9.3, macOS) script: make test_framework_GRDBOSX - # Test GRDBWatchOS (Xcode 9.2) + # Test GRDBWatchOS (Xcode 9.3) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBWatchOS (Xcode 9.2, watchOS) + - TID=GRDBWatchOS (Xcode 9.3, watchOS) script: make test_framework_GRDBWatchOS - # Test GRDBiOS (Xcode 9.2, iOS ) + # Test GRDBiOS (Xcode 9.3, iOS ) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBiOS (Xcode 9.2, iOS ) + - TID=GRDBiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBiOS_maxTarget - # Test GRDBiOS (Xcode 9.2, iOS )) + # Test GRDBiOS (Xcode 9.3, iOS )) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBiOS (Xcode 9.2, iOS ) + - TID=GRDBiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBiOS_minTarget - # Test GRDB [SPM] (Xcode 9.2, macOS) + # Test GRDB [SPM] (Xcode 9.3, macOS) - stage: Test GRDB gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDB [SPM] (Xcode 9.2, macOS) + - TID=GRDB [SPM] (Xcode 9.3, macOS) script: make test_SPM - # Test GRDBOSX (Xcode 9.0) - - stage: Test GRDB - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBOSX - - # Test GRDBiOS (Xcode 9.0, iOS ) - - stage: Test GRDB - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBiOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBiOS_maxTarget - ########################################### ## Test GRDB (Custom SQLite) - # Test GRDBCustomSQLiteOSX (Xcode 9.2) + # Test GRDBCustomSQLiteOSX (Xcode 9.3) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteOSX (Xcode 9.2, macOS) + - TID=GRDBCustomSQLiteOSX (Xcode 9.3, macOS) script: make test_framework_GRDBCustomSQLiteOSX - # Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + # Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + - TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_maxTarget - # Test GRDBCustomSQLiteiOS (Xcode 9.2, iOS )) + # Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS )) - stage: Test GRDB + Custom SQLite gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.2, iOS ) + - TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCustomSQLiteiOS_minTarget - # Test GRDBCustomSQLiteOSX (Xcode 9.0) - - stage: Test GRDB + Custom SQLite - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCustomSQLiteOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBCustomSQLiteOSX - - # Test GRDBCustomSQLiteiOS (Xcode 9.0, iOS ) - - stage: Test GRDB + Custom SQLite - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCustomSQLiteiOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBCustomSQLiteiOS_maxTarget - ########################################### ## Test GRDB (SQLCipher) - # Test GRDBCipherOSX (Xcode 9.2) + # Test GRDBCipherOSX (Xcode 9.3) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipherOSX (Xcode 9.2, macOS) + - TID=GRDBCipherOSX (Xcode 9.3, macOS) script: make test_framework_GRDBCipherOSX - # Test GRDBCipheriOS (Xcode 9.2, iOS ) + # Test GRDBCipheriOS (Xcode 9.3, iOS ) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipheriOS (Xcode 9.2, iOS ) + - TID=GRDBCipheriOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCipheriOS_maxTarget - # Test GRDBCipheriOS (Xcode 9.2, iOS )) + # Test GRDBCipheriOS (Xcode 9.3, iOS )) - stage: Test GRDB + SQLCipher gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=GRDBCipheriOS (Xcode 9.2, iOS ) + - TID=GRDBCipheriOS (Xcode 9.3, iOS ) script: make test_framework_GRDBCipheriOS_minTarget - # Test GRDBCipherOSX (Xcode 9.0) - - stage: Test GRDB + SQLCipher - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCipherOSX (Xcode 9.0, macOS) - script: make test_framework_GRDBCipherOSX - - # Test GRDBCipheriOS (Xcode 9.0, iOS ) - - stage: Test GRDB + SQLCipher - gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9 - env: - - TID=GRDBCipheriOS (Xcode 9.0, iOS ) - script: make test_framework_GRDBCipheriOS_maxTarget - - ########################################### ## Test Installation Methods - # Manual Install (Xcode 9.2) + # Manual Install (Xcode 9.3) - stage: Test Installation gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=Manual Install (Xcode 9.2) + - TID=Manual Install (Xcode 9.3) script: make test_install_manual - # Manual Install (GRDBCipher, Xcode 9.2) + # Manual Install (GRDBCipher, Xcode 9.3) - stage: Test Installation gemfile: .ci/gemfiles/Gemfile.travis - osx_image: xcode9.2 + osx_image: xcode9.3 env: - - TID=Manual Install (GRDBCipher, Xcode 9.2) + - TID=Manual Install (GRDBCipher, Xcode 9.3) script: make test_install_GRDBCipher - # Cocoapods Lint (Xcode 9.2) + # Cocoapods Lint (Xcode 9.3) - stage: Test Installation - osx_image: xcode9.2 + osx_image: xcode9.3 install: - gem install cocoapods # Since Travis is not always on latest version env: - - TID=Cocoapods (Xcode 9.2) + - TID=Cocoapods (Xcode 9.3) script: make test_CocoaPodsLint - # Cocoapods Lint (Xcode 9.0) + # SPM Install (Xcode 9.3) - stage: Test Installation - osx_image: xcode9 - install: - - gem install cocoapods # Since Travis is not always on latest version + osx_image: xcode9.3 env: - - TID=Cocoapods (Xcode 9.0) - script: make test_CocoaPodsLint - - # SPM Install (Xcode 9.2) - - stage: Test Installation - osx_image: xcode9.2 - env: - - TID=SPM (Xcode 9.2) + - TID=SPM (Xcode 9.3) script: make test_install_SPM ## Carthage Build ## Commented out until `make test_CarthageBuild` performs *reliably*. ## See https://github.com/groue/GRDB.swift/pull/262 # - stage: Test Installation - # osx_image: xcode9.2 + # osx_image: xcode9.3 # before_install: # - brew update # - brew outdated carthage || brew upgrade carthage diff --git a/Makefile b/Makefile index 847fc35ac..a223d02e6 100644 --- a/Makefile +++ b/Makefile @@ -44,26 +44,12 @@ XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) # xcodebuild actions to run test targets TEST_ACTIONS = clean build build-for-testing test-without-building -# xcodebuild destination to run tests on iOS 8.1 (requires a pre-installed simulator) -MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=8.1" - # When adding support for an Xcode version, look for available devices with `instruments -s devices` ifeq ($(XCODEVERSION),9.3) MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.3" -else ifeq ($(XCODEVERSION),9.2) - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.2" -else ifeq ($(XCODEVERSION),9.1) - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.1" -else ifeq ($(XCODEVERSION),9.0) - ifeq ($(XCODEVERSION_PATCH),1) - # Xcode 9.0.1: @groue's personal computer - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0.1" - else - # Xcode 9.0: Travis https://docs.travis-ci.com/user/reference/osx/#Xcode-9.0 - MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.0" - endif + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" else - # Xcode < 9.0 is not supported + # Swift 4.1 required: Xcode < 9.3 is not supported endif # If xcpretty is available, use it for xcodebuild output diff --git a/README.md b/README.md index 1e0990dbb..ce8b511d6 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,16 @@ -GRDB 2 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) +GRDB 3 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) ========== ### A toolkit for SQLite databases, with a focus on application development **Latest release**: March 30, 2018 • version 2.10.0 • [CHANGELOG](CHANGELOG.md) -**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9+ +**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4+** | **v2.10.0** | +| **Swift 4.1** | **v3.0.0** | +| Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3 | [v1.0](https://github.com/groue/GRDB.swift/tree/v1.0) | From e05a64f1cb14b51fe298583f186ce1750bc06fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 08:11:16 +0200 Subject: [PATCH 196/348] Cleanup --- .../Association/Association.swift | 12 ++---- .../Association/AssociationQuery.swift | 15 +++---- .../Association/AssociationRequest.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 42 +++++++++---------- .../QueryInterfaceRequest+Association.swift | 10 ++--- 5 files changed, 39 insertions(+), 42 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index d0028c0ab..29f5fb6d8 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -201,32 +201,28 @@ extension Association { /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated - { + public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated { return mapRequest { $0.chain(.optional, association) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated - { + public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated { return mapRequest { $0.chain(.required, association) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated - { + public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated { return mapRequest { $0.chain(.optional, association.select([])) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated - { + public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated { return mapRequest { $0.chain(.required, association.select([])) } } } diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index c89a1b25b..bcbfd1cf1 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -14,11 +14,12 @@ struct AssociationQuery { if let qualifier = qualifier { qualifiers.append(qualifier) } - qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) - return qualifiers + return joins.reduce(into: qualifiers) { + $0.append(contentsOf: $1.query.allQualifiers) + } } - var preparedQuery: AssociationQuery { + var qualifiedQuery: AssociationQuery { var qualifier = SQLTableQualifier(tableName: source.tableName!) var query = self @@ -28,7 +29,7 @@ struct AssociationQuery { query.ordering = ordering.qualified(with: qualifier) query.joins = joins.map { var join = $0 - join.rightQuery = join.rightQuery.preparedQuery + join.query = join.query.qualifiedQuery return join } return query @@ -36,13 +37,13 @@ struct AssociationQuery { var completeSelection: [SQLSelectable] { return joins.reduce(into: selection) { - $0.append(contentsOf: $1.rightQuery.completeSelection) + $0.append(contentsOf: $1.query.completeSelection) } } var completeOrdering: QueryOrdering { return joins.reduce(ordering) { - $0.appending($1.rightQuery.completeOrdering) + $0.appending($1.query.completeOrdering) } } @@ -54,7 +55,7 @@ struct AssociationQuery { var endIndex = startIndex + selectionWidth var scopes: [String: RowAdapter] = [:] for join in joins { - if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + if let (joinAdapter, joinEndIndex) = try join.query.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") scopes[join.key] = joinAdapter endIndex = joinEndIndex diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 0c8d54351..90bd1f37a 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -48,7 +48,7 @@ extension AssociationRequest { { let join = AssociationJoin( op: chainOp, - rightQuery: association.request.query, + query: association.request.query, key: association.key, associationMapping: association.associationMapping) return AssociationRequest(query: query.joining(join)) diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 902db778f..6c47f4f63 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -149,13 +149,13 @@ struct QueryInterfaceQuery { var completeSelection: [SQLSelectable] { return joins.reduce(into: selection) { - $0.append(contentsOf: $1.rightQuery.completeSelection) + $0.append(contentsOf: $1.query.completeSelection) } } var completeOrdering: QueryOrdering { return joins.reduce(ordering) { - $0.appending($1.rightQuery.completeOrdering) + $0.appending($1.query.completeOrdering) } } @@ -165,16 +165,17 @@ struct QueryInterfaceQuery { var allQualifiers: [SQLTableQualifier] { var qualifiers: [SQLTableQualifier] = [] - if let qualifier = source.qualifier { + if let qualifier = qualifier { qualifiers.append(qualifier) } - qualifiers.append(contentsOf: joins.flatMap { $0.rightQuery.allQualifiers }) - return qualifiers + return joins.reduce(into: qualifiers) { + $0.append(contentsOf: $1.query.allQualifiers) + } } } extension QueryInterfaceQuery { - private var preparedQuery: QueryInterfaceQuery { + private var qualifiedQuery: QueryInterfaceQuery { var query = self if !joins.isEmpty { @@ -192,7 +193,7 @@ extension QueryInterfaceQuery { query.joins = query.joins.map { var join = $0 - join.rightQuery = join.rightQuery.preparedQuery + join.query = join.query.qualifiedQuery return join } @@ -200,16 +201,16 @@ extension QueryInterfaceQuery { return query } - /// precondition: self is the result of preparedQuery + /// precondition: self is the result of qualifiedQuery private func makeSelectStatement(_ db: Database) throws -> SelectStatement { var arguments: StatementArguments? = StatementArguments() - let sql = try preparedQuery.sql(db, &arguments) + let sql = try self.sql(db, &arguments) let statement = try db.makeSelectStatement(sql) try statement.setArgumentsWithValidation(arguments!) return statement } - /// precondition: self is the result of preparedQuery + /// precondition: self is the result of qualifiedQuery private func rowAdapter(_ db: Database) throws -> RowAdapter? { if joins.isEmpty { return nil @@ -222,7 +223,7 @@ extension QueryInterfaceQuery { var endIndex = selectionWidth var scopes: [String: RowAdapter] = [:] for join in joins { - if let (joinAdapter, joinEndIndex) = try join.rightQuery.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + if let (joinAdapter, joinEndIndex) = try join.query.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") scopes[join.key] = joinAdapter endIndex = joinEndIndex @@ -238,7 +239,7 @@ extension QueryInterfaceQuery { } func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let query = preparedQuery + let query = qualifiedQuery return try (query.makeSelectStatement(db), query.rowAdapter(db)) } @@ -249,7 +250,7 @@ extension QueryInterfaceQuery { /// The database region that the request looks into. func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try preparedQuery.makeSelectStatement(db) + let statement = try qualifiedQuery.makeSelectStatement(db) let region = statement.fetchedRegion // Can we intersect the region with rowIds? @@ -421,7 +422,7 @@ extension QueryInterfaceQuery { struct AssociationJoin { var op: AssociationChainOperator - var rightQuery: AssociationQuery + var query: AssociationQuery var key: String var associationMapping: (Database) throws -> AssociationMapping @@ -440,20 +441,19 @@ struct AssociationJoin { sql += "JOIN" } - let rightQualifier = rightQuery.qualifier! - - sql += try " " + rightQuery.source.sourceSQL(db, &arguments) + sql += try " " + query.source.sourceSQL(db, &arguments) + let qualifier = query.qualifier! let filters = try [ - associationMapping(db)(leftQualifier, rightQualifier), - rightQuery.filterPromise.resolve(db) + associationMapping(db)(leftQualifier, qualifier), + query.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { sql += " ON " + filters.joined(operator: .and).expressionSQL(&arguments) } - for join in rightQuery.joins { - sql += try " " + join.joinSQL(db, &arguments, leftQualifier: rightQualifier, isRequiredAllowed: isRequiredAllowed) + for join in query.joins { + sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier, isRequiredAllowed: isRequiredAllowed) } return sql diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 296d0bb19..309da524b 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -5,7 +5,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { { let join = AssociationJoin( op: chainOp, - rightQuery: association.request.query, + query: association.request.query, key: association.key, associationMapping: association.associationMapping) return QueryInterfaceRequest(query: query.joining(join)) @@ -56,16 +56,16 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { extension Association where LeftAssociated: MutablePersistableRecord { func request(from record: LeftAssociated) -> QueryInterfaceRequest { - var query = request.query.preparedQuery // make sure query has a qualifier - let qualifier = query.source.qualifier! + var query = request.query.qualifiedQuery // make sure query has a qualifier + let qualifier = query.qualifier! let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) - + query = query.filter { db in let associationMapping = try self.associationMapping(db) guard let filter = associationMapping(recordQualifier, qualifier) else { fatalError("Can't request from record without association mapping") } - let container = PersistenceContainer(record) + let container = PersistenceContainer(record) // support for record classes: late construction of container return filter.resolvedExpression(inContext: [recordQualifier: container]) } From 5747d1cff0f8d2fdeeb7c9b68e9b424a0c212f01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 08:26:23 +0200 Subject: [PATCH 197/348] No more #if swift(>=4.1) --- GRDB.xcodeproj/project.pbxproj | 8 ------- GRDB/Core/Cursor.swift | 8 ------- GRDB/Core/Database.swift | 16 ------------- GRDB/Core/DatabaseError.swift | 10 -------- GRDB/Core/DatabaseFunction.swift | 10 -------- GRDB/Core/DatabaseRegion.swift | 8 ------- GRDB/Core/Statement.swift | 12 ---------- GRDB/Legacy/Swift4.1.swift | 24 ------------------- .../SQLExpression+QueryInterface.swift | 18 +------------- GRDB/Record/PersistableRecord.swift | 21 ++-------------- GRDBCipher.xcodeproj/project.pbxproj | 6 ----- GRDBCustom.xcodeproj/project.pbxproj | 6 ----- Tests/GRDBTests/CursorTests.swift | 9 ------- Tests/GRDBTests/DatabaseAggregateTests.swift | 4 ---- Tests/GRDBTests/DatabaseFunctionTests.swift | 4 ---- .../QueryInterfaceExpressionsTests.swift | 4 ---- 16 files changed, 3 insertions(+), 165 deletions(-) delete mode 100644 GRDB/Legacy/Swift4.1.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 229b2acee..5a20e3e81 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -481,9 +481,6 @@ 56B021CD1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */; }; 56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */; }; 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; }; - 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; - 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; - 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */; }; 56B6EF56208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B6EF57208CB4E3002F0ACB /* ColumnExpressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */; }; 56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; }; @@ -1030,7 +1027,6 @@ 56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordPersistenceConflictPolicyTests.swift; sourceTree = ""; }; 56B14E7E1D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromDictionaryLiteralTests.swift; sourceTree = ""; }; 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = ""; }; - 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColumnExpressionTests.swift; sourceTree = ""; }; 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = ""; }; 56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = ""; }; @@ -1748,7 +1744,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98EC2039B6F3008D7DBF /* Fixits-3.0.swift */, - 56B1C3CC201C8D0E001938DA /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -2399,7 +2394,6 @@ 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */, 565490B81D5AE236005622CB /* DatabaseError.swift in Sources */, 56BF6D3C1DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, - 56B1C3CF201C8D0E001938DA /* Swift4.1.swift in Sources */, 56DAA2E11DE9C827006E10C8 /* Cursor.swift in Sources */, 5653EB0520944C7C00F46237 /* BelongsToAssociation.swift in Sources */, 565490BC1D5AE236005622CB /* DatabaseSchemaCache.swift in Sources */, @@ -2487,7 +2481,6 @@ 5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, 56A2388C1B9C75030082EB20 /* Statement.swift in Sources */, 5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */, - 56B1C3CE201C8D0E001938DA /* Swift4.1.swift in Sources */, 5605F1941C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */, 5690C3431D23E82A00E59934 /* Data.swift in Sources */, @@ -2928,7 +2921,6 @@ 5605F1931C6B1A8700235C62 /* QueryInterfaceQuery.swift in Sources */, 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */, - 56B1C3CD201C8D0E001938DA /* Swift4.1.swift in Sources */, 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 56FC98781D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 8de34aebe..0062157d4 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -132,7 +132,6 @@ extension Cursor { return nil } - #if swift(>=4.1) /// Returns a cursor over the concatenated non-nil results of mapping /// transform over this cursor. public func compactMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { @@ -143,13 +142,6 @@ extension Cursor { public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { return compactMap(transform) } - #else - /// Returns a cursor over the concatenated non-nil results of mapping - /// transform over this cursor. - public func flatMap(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor>, ElementOfResult> { - return map(transform).filter { $0 != nil }.map { $0! } - } - #endif /// Returns a cursor that skips any initial elements that satisfy /// `predicate`. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 9d38e5cd9..c93f4841b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -867,14 +867,6 @@ extension Database { self.rawValue = rawValue } - #if !swift(>=4.1) - /// The hash value - /// :nodoc: - public var hashValue: Int { - return rawValue.hashValue - } - #endif - /// The `BINARY` built-in SQL collation public static let binary = CollationName("BINARY") @@ -906,14 +898,6 @@ extension Database { self.rawValue = rawValue } - #if !swift(>=4.1) - /// The hash value - /// :nodoc: - public var hashValue: Int { - return rawValue.hashValue - } - #endif - /// The `TEXT` SQL column type public static let text = ColumnType("TEXT") diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index afa6cb5d9..778e3e8ef 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -139,16 +139,6 @@ public struct ResultCode : RawRepresentable, Equatable, CustomStringConvertible public static let SQLITE_OK_LOAD_PERMANENTLY = ResultCode(rawValue: (SQLITE_OK.rawValue | (1<<8))) } -#if !swift(>=4.1) -// Equatable -extension ResultCode { - /// :nodoc: - public static func == (_ lhs: ResultCode, _ rhs: ResultCode) -> Bool { - return lhs.rawValue == rhs.rawValue - } -} -#endif - // CustomStringConvertible extension ResultCode { /// :nodoc: diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 257740ff1..5e64eb366 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -10,16 +10,6 @@ public final class DatabaseFunction: Hashable { private struct Identity: Hashable { let name: String let nArg: Int32 // -1 for variadic functions - - #if !swift(>=4.1) - var hashValue: Int { - return name.hashValue ^ nArg.hashValue - } - - static func == (lhs: Identity, rhs: Identity) -> Bool { - return lhs.name == rhs.name && lhs.nArg == rhs.nArg - } - #endif } public var name: String { return identity.name } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 678144fbf..99a2d092a 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -255,14 +255,6 @@ private struct TableRegion: Equatable { return false } - #if !swift(>=4.1) - static func == (lhs: TableRegion, rhs: TableRegion) -> Bool { - if lhs.columns != rhs.columns { return false } - if lhs.rowIds != rhs.rowIds { return false } - return true - } - #endif - func intersection(_ other: TableRegion) -> TableRegion { let columnsIntersection: Set? switch (self.columns, other.columns) { diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 482def1cd..0bc43bc6c 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -905,18 +905,6 @@ extension StatementArguments { } } -#if !swift(>=4.1) -// Equatable -extension StatementArguments { - /// :nodoc: - public static func == (lhs: StatementArguments, rhs: StatementArguments) -> Bool { - if lhs.values != rhs.values { return false } - if lhs.namedValues != rhs.namedValues { return false } - return true - } -} -#endif - /// A thread-unsafe statement cache struct StatementCache { unowned let db: Database diff --git a/GRDB/Legacy/Swift4.1.swift b/GRDB/Legacy/Swift4.1.swift deleted file mode 100644 index c1adaac2f..000000000 --- a/GRDB/Legacy/Swift4.1.swift +++ /dev/null @@ -1,24 +0,0 @@ -// Compatibility layer for Swift < 4.1 - -#if !swift(>=4.1) -extension Sequence { - // From future import SE-0187 - func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] { - return try flatMap(transform) - } -} - -extension UnsafeMutablePointer { - // From future import SE-0184 - func deallocate() { - deallocate(capacity: 0) - } -} - -extension UnsafeMutableRawBufferPointer { - // From future import SE-0184 - func copyMemory(from source: C) where C : Collection, C.Element == UInt8 { - copyBytes(from: source) - } -} -#endif diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 3248c9963..734e88d87 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -556,7 +556,7 @@ public struct SQLFunctionName : Hashable { /// The SQL function name /// /// :nodoc: - public let sql: String + public var sql: String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -568,22 +568,6 @@ public struct SQLFunctionName : Hashable { public init(_ sql: String) { self.sql = sql } - - #if !swift(>=4.1) - /// The hash value - /// - /// :nodoc: - public var hashValue: Int { - return sql.hashValue - } - - /// Equality operator - /// - /// :nodoc: - public static func == (lhs: SQLFunctionName, rhs: SQLFunctionName) -> Bool { - return lhs.sql == rhs.sql - } - #endif } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index 96a3f82b1..e5d9cfd5b 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -991,16 +991,8 @@ private struct InsertQuery: Hashable { let tableName: String let insertedColumns: [String] - // Not generated by Swift 4.1 + // TODO: remove when Swift can generate it var hashValue: Int { return tableName.hashValue } - - #if !swift(>=4.1) - static func == (lhs: InsertQuery, rhs: InsertQuery) -> Bool { - if lhs.tableName != rhs.tableName { return false } - if lhs.onConflict != rhs.onConflict { return false } - return lhs.insertedColumns == rhs.insertedColumns - } - #endif } extension InsertQuery { @@ -1032,17 +1024,8 @@ private struct UpdateQuery: Hashable { let updatedColumns: [String] let conditionColumns: [String] - // Not generated by Swift 4.1 + // TODO: remove when Swift can generate it var hashValue: Int { return tableName.hashValue } - - #if !swift(>=4.1) - static func == (lhs: UpdateQuery, rhs: UpdateQuery) -> Bool { - if lhs.tableName != rhs.tableName { return false } - if lhs.onConflict != rhs.onConflict { return false } - if lhs.updatedColumns != rhs.updatedColumns { return false } - return lhs.conditionColumns == rhs.conditionColumns - } - #endif } extension UpdateQuery { diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 8b911d1ec..09684ca77 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -554,8 +554,6 @@ 5698AD391DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 569A98FC2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; 569A98FD2039B72D008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */; }; - 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; - 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA6201C904C0069DE70 /* Swift4.1.swift */; }; 569C1EB31CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB41CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; 569C1EB61CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */; }; @@ -1076,7 +1074,6 @@ 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E8200D387000A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1753,7 +1750,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98FA2039B72C008D7DBF /* Fixits-3.0.swift */, - 569B7FA6201C904C0069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -2164,7 +2160,6 @@ 564F9C2F1F07611400877A00 /* DatabaseFunction.swift in Sources */, 5659F4991EA8D989004A4992 /* Pool.swift in Sources */, 5653EB8F20961FC000F46237 /* BelongsToAssociation.swift in Sources */, - 569B7FA8201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6FA1F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54D1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759B1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, @@ -2597,7 +2592,6 @@ 564F9C321F07611700877A00 /* DatabaseFunction.swift in Sources */, 5659F49C1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB9020961FC000F46237 /* BelongsToAssociation.swift in Sources */, - 569B7FA9201C904C0069DE70 /* Swift4.1.swift in Sources */, 5674A6F71F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5501EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5664759E1D97D8A000FF74B8 /* SQLCollection.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 9f2aa8291..210584469 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -237,8 +237,6 @@ 5698AD3A1DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */; }; 569A98F82039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; 569A98F92039B716008D7DBF /* Fixits-3.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569A98F62039B716008D7DBF /* Fixits-3.0.swift */; }; - 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; - 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569B7FA2201C90430069DE70 /* Swift4.1.swift */; }; 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 569EF0E7200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; 56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; @@ -743,7 +741,6 @@ 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; 569A98F62039B716008D7DBF /* Fixits-3.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-3.0.swift"; sourceTree = ""; }; - 569B7FA2201C90430069DE70 /* Swift4.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Swift4.1.swift; sourceTree = ""; }; 569C1EB11CF07DDD0042627B /* SchedulingWatchdogTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdogTests.swift; sourceTree = ""; }; 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegion.swift; sourceTree = ""; }; 56A238131B9C74A90082EB20 /* DatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTests.swift; sourceTree = ""; }; @@ -1399,7 +1396,6 @@ 56D121591ED34978001347D2 /* Fixits-0.109.0.swift */, 56873BEB1F2CB400004D24B4 /* Fixits-1.2.swift */, 569A98F62039B716008D7DBF /* Fixits-3.0.swift */, - 569B7FA2201C90430069DE70 /* Swift4.1.swift */, ); path = Legacy; sourceTree = ""; @@ -1839,7 +1835,6 @@ 564F9C331F07611800877A00 /* DatabaseFunction.swift in Sources */, 5659F49D1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB4220961F6100F46237 /* BelongsToAssociation.swift in Sources */, - 569B7FA5201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F61F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB5511EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC3C1D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, @@ -2111,7 +2106,6 @@ 564F9C301F07611500877A00 /* DatabaseFunction.swift in Sources */, 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */, 5653EB4120961F6100F46237 /* BelongsToAssociation.swift in Sources */, - 569B7FA4201C90430069DE70 /* Swift4.1.swift in Sources */, 5674A6F51F307F600095F066 /* PersistableRecord+Encodable.swift in Sources */, 56CEB54E1EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 5698AC391D9E5A590056AF8C /* FTS3Pattern.swift in Sources */, diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index f73f99419..c69411c3b 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -78,21 +78,12 @@ class CursorTests: GRDBTestCase { } } - #if swift(>=4.1) func testCompactMap() { let cursor = AnyCursor(["1", "foo", "2"]).compactMap { Int($0) } XCTAssertEqual(try cursor.next()!, 1) XCTAssertEqual(try cursor.next()!, 2) XCTAssertTrue(try cursor.next() == nil) // end } - #else - func testFlatMapOfOptional() { - let cursor = AnyCursor(["1", "foo", "2"]).flatMap { Int($0) } - XCTAssertEqual(try cursor.next()!, 1) - XCTAssertEqual(try cursor.next()!, 2) - XCTAssertTrue(try cursor.next() == nil) // end - } - #endif func testForEach() throws { let cursor = AnyCursor([1, 2]) diff --git a/Tests/GRDBTests/DatabaseAggregateTests.swift b/Tests/GRDBTests/DatabaseAggregateTests.swift index faf882210..bf466b528 100644 --- a/Tests/GRDBTests/DatabaseAggregateTests.swift +++ b/Tests/GRDBTests/DatabaseAggregateTests.swift @@ -295,11 +295,7 @@ class DatabaseAggregateTests: GRDBTestCase { struct Aggregate : DatabaseAggregate { var result: DatabaseValueConvertible? mutating func step(_ dbValues: [DatabaseValue]) { - #if swift(>=4.1) let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } - #else - let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } - #endif result = ints.reduce(0, +) } func finalize() -> DatabaseValueConvertible? { diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 4fd02a4b7..60ae195bb 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -250,11 +250,7 @@ class DatabaseFunctionTests: GRDBTestCase { func testFunctionOfTwoArguments() throws { let dbQueue = try makeDatabaseQueue() let fn = DatabaseFunction("f", argumentCount: 2) { dbValues in - #if swift(>=4.1) let ints = dbValues.compactMap { Int.fromDatabaseValue($0) } - #else - let ints = dbValues.flatMap { Int.fromDatabaseValue($0) } - #endif return ints.reduce(0, +) } dbQueue.add(function: fn) diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index b06954417..f2c8e18e0 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -31,11 +31,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { dbWriter.add(collation: collation) customFunction = DatabaseFunction("avgOf", pure: true) { dbValues in - #if swift(>=4.1) let sum = dbValues.compactMap { Int.fromDatabaseValue($0) }.reduce(0, +) - #else - let sum = dbValues.flatMap { Int.fromDatabaseValue($0) }.reduce(0, +) - #endif return Double(sum) / Double(dbValues.count) } dbWriter.add(function: self.customFunction) From 5e7235307ad436c6e77c09ef3755d7fbd7100cf2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 08:36:29 +0200 Subject: [PATCH 198/348] Cleanup --- .../Association/Association.swift | 4 ---- .../Association/BelongsToAssociation.swift | 18 ++++++++---------- .../Association/HasManyAssociation.swift | 18 ++++++++---------- .../Association/HasOneAssociation.swift | 18 ++++++++---------- 4 files changed, 24 insertions(+), 34 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 29f5fb6d8..e831f1ce0 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -56,10 +56,6 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self } -func defaultAssociationKey(for type: T.Type) -> String { - return T.databaseTableName -} - extension Association { /// Creates an association with a new net of selected columns. /// diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 4cc4de2ad..4b66eba1d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -11,15 +11,14 @@ public struct BelongsToAssociation : Association, TableRequest wher public var databaseTableName: String { return RightAssociated.databaseTableName } /// :nodoc: - public let request: AssociationRequest + public var request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest public func forKey(_ key: String) -> BelongsToAssociation { - return BelongsToAssociation( - key: key, - request: request, - foreignKeyRequest: foreignKeyRequest) + var association = self + association.key = key + return association } /// :nodoc: @@ -31,10 +30,9 @@ public struct BelongsToAssociation : Association, TableRequest wher /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { - return BelongsToAssociation( - key: key, - request: transform(request), - foreignKeyRequest: foreignKeyRequest) + var association = self + association.request = transform(request) + return association } } @@ -53,7 +51,7 @@ extension TableRecord { foreignKey: foreignKey) return BelongsToAssociation( - key: key ?? defaultAssociationKey(for: Right.self), + key: key ?? Right.databaseTableName, request: AssociationRequest(rightRequest), foreignKeyRequest: foreignKeyRequest) } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index acc642c00..a61dca186 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -11,15 +11,14 @@ public struct HasManyAssociation : Association, TableRequest where public var databaseTableName: String { return RightAssociated.databaseTableName } /// :nodoc: - public let request: AssociationRequest + public var request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest public func forKey(_ key: String) -> HasManyAssociation { - return HasManyAssociation( - key: key, - request: request, - foreignKeyRequest: foreignKeyRequest) + var association = self + association.key = key + return association } /// :nodoc: @@ -31,10 +30,9 @@ public struct HasManyAssociation : Association, TableRequest where /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { - return HasManyAssociation( - key: key, - request: transform(request), - foreignKeyRequest: foreignKeyRequest) + var association = self + association.request = transform(request) + return association } } @@ -53,7 +51,7 @@ extension TableRecord { foreignKey: foreignKey) return HasManyAssociation( - key: key ?? defaultAssociationKey(for: Right.self), + key: key ?? Right.databaseTableName, request: AssociationRequest(rightRequest), foreignKeyRequest: foreignKeyRequest) } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b18dacb9f..22c8dbb6f 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -11,15 +11,14 @@ public struct HasOneAssociation : Association, TableRequest where public var databaseTableName: String { return RightAssociated.databaseTableName } /// :nodoc: - public let request: AssociationRequest + public var request: AssociationRequest let foreignKeyRequest: ForeignKeyRequest public func forKey(_ key: String) -> HasOneAssociation { - return HasOneAssociation( - key: key, - request: request, - foreignKeyRequest: foreignKeyRequest) + var association = self + association.key = key + return association } /// :nodoc: @@ -31,10 +30,9 @@ public struct HasOneAssociation : Association, TableRequest where /// :nodoc: public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { - return HasOneAssociation( - key: key, - request: transform(request), - foreignKeyRequest: foreignKeyRequest) + var association = self + association.request = transform(request) + return association } } @@ -53,7 +51,7 @@ extension TableRecord { foreignKey: foreignKey) return HasOneAssociation( - key: key ?? defaultAssociationKey(for: Right.self), + key: key ?? Right.databaseTableName, request: AssociationRequest(rightRequest), foreignKeyRequest: foreignKeyRequest) } From ccc259c25c525380d1fb8331303c3c9da22415bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 08:55:16 +0200 Subject: [PATCH 199/348] Documentation --- GRDB/QueryInterface/QueryInterfaceRequest.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 07ed1eaf4..555f516a4 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -166,10 +166,16 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating } } +/// Conditional conformance to TableRequest when RowDecoder conforms +/// to TableRecord: +/// +/// let request = Player.all() +/// request.filter(key: ...) +/// request.filter(keys: ...) extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { /// :nodoc: public var databaseTableName: String { - return T.databaseTableName + return RowDecoder.databaseTableName } } From ae162a88c65054edb724960d07a9b348d75024b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 08:57:10 +0200 Subject: [PATCH 200/348] Upgrade .swift-version and Swift badge to 4.1 --- .swift-version | 2 +- README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.swift-version b/.swift-version index 389f7740e..7d5c902e7 100644 --- a/.swift-version +++ b/.swift-version @@ -1 +1 @@ -4.0 \ No newline at end of file +4.1 diff --git a/README.md b/README.md index ce8b511d6..7012dd79e 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -GRDB 3 [![Swift](https://img.shields.io/badge/swift-4-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) +GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)](https://developer.apple.com/swift/) [![Platforms](https://img.shields.io/cocoapods/p/GRDB.swift.svg)](https://developer.apple.com/swift/) [![License](https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000)](/LICENSE) [![Build Status](https://travis-ci.org/groue/GRDB.swift.svg?branch=master)](https://travis-ci.org/groue/GRDB.swift) ========== ### A toolkit for SQLite databases, with a focus on application development From dddeff458a01a8e5fcbbbc64c6009d2928c478e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 09:02:05 +0200 Subject: [PATCH 201/348] none() is no longer a requirement of FilteredRequest --- .../QueryInterface/Association/Association.swift | 5 ----- .../Association/AssociationQuery.swift | 6 ------ .../Association/AssociationRequest.swift | 4 ---- GRDB/QueryInterface/QueryInterfaceQuery.swift | 6 ------ GRDB/QueryInterface/QueryInterfaceRequest.swift | 9 --------- GRDB/QueryInterface/RequestProtocols.swift | 16 +++++++++------- 6 files changed, 9 insertions(+), 37 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index e831f1ce0..83904de72 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -70,11 +70,6 @@ extension Association { return mapRequest { $0.filter(predicate) } } - /// Creates an association that matches nothing. - public func none() -> Self { - return mapRequest { $0.none() } - } - /// Creates an association with the provided *orderings*. /// /// Any previous ordering is replaced. diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index bcbfd1cf1..1f580a82e 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -105,12 +105,6 @@ extension AssociationQuery { } return query } - - func none() -> AssociationQuery { - var query = self - query.filterPromise = DatabasePromise(value: false.sqlExpression) - return query - } func order(_ orderings: [SQLOrderingTerm]) -> AssociationQuery { return order(QueryOrdering(orderings: orderings)) diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 90bd1f37a..af8046401 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -21,10 +21,6 @@ extension AssociationRequest { return AssociationRequest(query: query.filter(predicate)) } - func none() -> AssociationRequest { - return AssociationRequest(query: query.none()) - } - func order(_ orderings: [SQLOrderingTerm]) -> AssociationRequest { return AssociationRequest(query: query.order(orderings)) } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 6c47f4f63..f0fc04037 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -352,12 +352,6 @@ extension QueryInterfaceQuery { return query } - func none() -> QueryInterfaceQuery { - var query = self - query.filterPromise = DatabasePromise(value: false.sqlExpression) - return query - } - func group(_ expressions: [SQLExpressible]) -> QueryInterfaceQuery { var query = self query.groupByExpressions = expressions.map { $0.sqlExpression } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 555f516a4..0204305d1 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -82,15 +82,6 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating return QueryInterfaceRequest(query: query.filter(predicate)) } - /// Creates a request that matches nothing. - /// - /// // SELECT * FROM players WHERE 0 - /// var request = Player.all() - /// request = request.none() - public func none() -> QueryInterfaceRequest { - return QueryInterfaceRequest(query: query.none()) - } - /// Creates a request grouped according to *expressions*. public func group(_ expressions: [SQLExpressible]) -> QueryInterfaceRequest { return QueryInterfaceRequest(query: query.group(expressions)) diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 84d1ede7c..bf2987935 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -62,13 +62,6 @@ public protocol FilteredRequest { /// var request = Player.all() /// request = request.filter { db in true } func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self - - /// Creates a request that matches nothing. - /// - /// // SELECT * FROM players WHERE 0 - /// var request = Player.all() - /// request = request.none() - func none() -> Self } extension FilteredRequest { @@ -91,6 +84,15 @@ extension FilteredRequest { public func filter(sql: String, arguments: StatementArguments? = nil) -> Self { return filter(SQLExpressionLiteral(sql, arguments: arguments)) } + + /// Creates a request that matches nothing. + /// + /// // SELECT * FROM players WHERE 0 + /// var request = Player.all() + /// request = request.none() + public func none() -> Self { + return filter(false) + } } // MARK: - TableRequest { From 50dd846a36590924c16d0f6c2484c6885eaa8383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 12:25:07 +0200 Subject: [PATCH 202/348] Remove useless constraint on Association.LeftAssociated and Association.RightAssociated --- GRDB/QueryInterface/Association/Association.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 83904de72..12f190748 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -1,8 +1,8 @@ /// The base protocol for all associations that define a connection between two /// Record types. public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { - associatedtype LeftAssociated: TableRecord - associatedtype RightAssociated: TableRecord + associatedtype LeftAssociated + associatedtype RightAssociated /// The association key defines how rows fetched from this association /// should be consumed. From a45d0194720d7eaa3f111f9931af7d33e123fea1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 12:50:38 +0200 Subject: [PATCH 203/348] Simplification Rename AssociationMapping to JoinCondition Replace AssociationMappingRequest enum with ForeignKeyJoinConditionRequest struct Rename AssociationChainOperator to AssociationJoinOperator, and "chain" to "join" --- GRDB.xcodeproj/project.pbxproj | 8 -- .../Association/Association.swift | 94 +++++++++---------- .../Association/AssociationMapping.swift | 23 ----- .../Association/AssociationRequest.swift | 6 +- .../Association/BelongsToAssociation.swift | 6 +- .../Association/HasManyAssociation.swift | 6 +- .../Association/HasOneAssociation.swift | 6 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 55 ++++++++++- .../QueryInterfaceRequest+Association.swift | 78 ++++----------- GRDBCipher.xcodeproj/project.pbxproj | 16 +--- GRDBCustom.xcodeproj/project.pbxproj | 16 +--- 11 files changed, 130 insertions(+), 184 deletions(-) delete mode 100644 GRDB/QueryInterface/Association/AssociationMapping.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 5a20e3e81..09785bcf6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -191,9 +191,6 @@ 5653EB0F20944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; 5653EB1020944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; 5653EB1120944C7C00F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */; }; - 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; - 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; - 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */; }; 5653EB1520944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; 5653EB1720944C7C00F46237 /* AssociationQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */; }; @@ -883,7 +880,6 @@ 5653EAFA20944C7B00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasManyAssociation.swift; sourceTree = ""; }; 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; - 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationQuery.swift; sourceTree = ""; }; 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; @@ -1425,7 +1421,6 @@ isa = PBXGroup; children = ( 5653EAFA20944C7B00F46237 /* Association.swift */, - 5653EAFD20944C7B00F46237 /* AssociationMapping.swift */, 5653EAFE20944C7C00F46237 /* AssociationQuery.swift */, 5653EAFC20944C7B00F46237 /* AssociationRequest.swift */, 5653EAF820944C7B00F46237 /* BelongsToAssociation.swift */, @@ -2365,7 +2360,6 @@ 565490CC1D5AE252005622CB /* (null) in Sources */, 56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, - 5653EB1420944C7C00F46237 /* AssociationMapping.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, @@ -2491,7 +2485,6 @@ 56A238881B9C75030082EB20 /* Row.swift in Sources */, 56CEB4F41EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 569531201C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */, - 5653EB1320944C7C00F46237 /* AssociationMapping.swift in Sources */, 5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */, 56BF6D391DEF47DA006039A3 /* Fixits-0-90-1.swift in Sources */, 563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */, @@ -2945,7 +2938,6 @@ 56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */, 569A98ED2039B6F3008D7DBF /* Fixits-3.0.swift in Sources */, 5605F1671C672E4000235C62 /* NSNumber.swift in Sources */, - 5653EB1220944C7C00F46237 /* AssociationMapping.swift in Sources */, C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */, 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 12f190748..c0c1d1883 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -50,7 +50,7 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { var request: AssociationRequest { get } /// :nodoc: - func associationMapping(_ db: Database) throws -> AssociationMapping + func joinCondition(_ db: Database) throws -> JoinCondition /// :nodoc: func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self @@ -141,51 +141,26 @@ extension Association { } } -/// Not to be mismatched with SQL join operators (inner join, left join). -/// -/// AssociationChainOperator is designed to be hierarchically nested, unlike -/// SQL join operators. -/// -/// Consider the following request for (A, B, C) tuples: -/// -/// let r = A.including(optional: A.b.including(required: B.c)) -/// -/// It chains three associations, the first optional, the second required. -/// -/// It looks like it means: "Give me all As, along with their Bs, granted those -/// Bs have their Cs. For As whose B has no C, give me a nil B". -/// -/// It can not be expressed as one left join, and a regular join, as below, -/// Because this would not honor the first optional: -/// -/// -- dubious -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// JOIN c ON ... -/// -/// Instead, it should: -/// - allow (A + missing (B + C)) -/// - prevent (A + (B + missing C)). -/// -/// This can be expressed in SQL with two left joins, and an extra condition: -/// -/// -- likely correct -/// SELECT a.*, b.*, c.* -/// FROM a -/// LEFT JOIN b ON ... -/// LEFT JOIN c ON ... -/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C -/// -/// This is currently not implemented, and requires a little more thought. -/// I don't even know if inventing a whole new way to perform joins should even -/// be on the table. But we have a hierarchical way to express joined queries, -/// and they have a meaning: -/// -/// // what is my meaning? -/// A.including(optional: A.b.including(required: B.c)) -enum AssociationChainOperator { - case required, optional +public typealias JoinCondition = (_ leftQualifier: SQLTableQualifier, _ rightQualifier: SQLTableQualifier) -> SQLExpression? + +struct ForeignKeyJoinConditionRequest { + var foreignKeyRequest: ForeignKeyRequest + var originIsLeft: Bool + + func fetch(_ db: Database) throws -> JoinCondition { + let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping + let columnMapping: [(left: Column, right: Column)] + if originIsLeft { + columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } + } else { + columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } + } + return { (leftQualifier, rightQualifier) in + return columnMapping + .map { $0.right.qualifiedExpression(with: rightQualifier) == $0.left.qualifiedExpression(with: leftQualifier) } + .joined(operator: .and) + } + } } extension Association { @@ -193,27 +168,46 @@ extension Association { /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated { - return mapRequest { $0.chain(.optional, association) } + return mapRequest { $0.joining(.optional, association) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated { - return mapRequest { $0.chain(.required, association) } + return mapRequest { $0.joining(.required, association) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated { - return mapRequest { $0.chain(.optional, association.select([])) } + return mapRequest { $0.joining(.optional, association.select([])) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated { - return mapRequest { $0.chain(.required, association.select([])) } + return mapRequest { $0.joining(.required, association.select([])) } + } +} + +extension Association where LeftAssociated: MutablePersistableRecord { + func request(from record: LeftAssociated) -> QueryInterfaceRequest { + let query = request.query.qualifiedQuery // make sure query has a qualifier + let associationQualifier = query.qualifier! + let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) + + // Turn `right.id = left.id` into `right.id = 1` + let resolvedQuery = query.filter { db in + guard let joinCondition = try self.joinCondition(db)(recordQualifier, associationQualifier) else { + fatalError("Can't request from record without association mapping") + } + let container = PersistenceContainer(record) // support for record classes: late construction of container + return joinCondition.resolvedExpression(inContext: [recordQualifier: container]) + } + + return QueryInterfaceRequest(query: QueryInterfaceQuery(resolvedQuery)) } } diff --git a/GRDB/QueryInterface/Association/AssociationMapping.swift b/GRDB/QueryInterface/Association/AssociationMapping.swift deleted file mode 100644 index a75c01494..000000000 --- a/GRDB/QueryInterface/Association/AssociationMapping.swift +++ /dev/null @@ -1,23 +0,0 @@ -public typealias AssociationMapping = (SQLTableQualifier, SQLTableQualifier) -> SQLExpression? - -enum AssociationMappingRequest { - case foreignKey(request: ForeignKeyRequest, originIsLeft: Bool) - - func fetch(_ db: Database) throws -> AssociationMapping { - switch self { - case .foreignKey(request: let foreignKeyRequest, originIsLeft: let originIsLeft): - let foreignKeyMapping = try foreignKeyRequest.fetch(db).mapping - let columnMapping: [(left: Column, right: Column)] - if originIsLeft { - columnMapping = foreignKeyMapping.map { (left: Column($0.origin), right: Column($0.destination)) } - } else { - columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } - } - return { (leftQualifier, rightQualifier) in - return columnMapping - .map { $0.right.qualifiedExpression(with: rightQualifier) == $0.left.qualifiedExpression(with: leftQualifier) } - .joined(operator: .and) - } - } - } -} diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index af8046401..2b3b3a568 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -38,15 +38,15 @@ extension AssociationRequest { return AssociationRequest(query: query.qualified(with: &alias.qualifier)) } - func chain(_ chainOp: AssociationChainOperator, _ association: A) + func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> AssociationRequest where A.LeftAssociated == T { let join = AssociationJoin( - op: chainOp, + joinOperator: joinOperator, query: association.request.query, key: association.key, - associationMapping: association.associationMapping) + joinConditionPromise: association.joinCondition) return AssociationRequest(query: query.joining(join)) } } diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 4b66eba1d..7a6623eaa 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -22,10 +22,8 @@ public struct BelongsToAssociation : Association, TableRequest wher } /// :nodoc: - public func associationMapping(_ db: Database) throws -> AssociationMapping { - return try AssociationMappingRequest - .foreignKey(request: foreignKeyRequest, originIsLeft: true) - .fetch(db) + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: true).fetch(db) } /// :nodoc: diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index a61dca186..4c9d88edf 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -22,10 +22,8 @@ public struct HasManyAssociation : Association, TableRequest where } /// :nodoc: - public func associationMapping(_ db: Database) throws -> AssociationMapping { - return try AssociationMappingRequest - .foreignKey(request: foreignKeyRequest, originIsLeft: false) - .fetch(db) + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) } /// :nodoc: diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 22c8dbb6f..b3c70de9e 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -22,10 +22,8 @@ public struct HasOneAssociation : Association, TableRequest where } /// :nodoc: - public func associationMapping(_ db: Database) throws -> AssociationMapping { - return try AssociationMappingRequest - .foreignKey(request: foreignKeyRequest, originIsLeft: false) - .fetch(db) + public func joinCondition(_ db: Database) throws -> JoinCondition { + return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) } /// :nodoc: diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index f0fc04037..598c6e28f 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -414,16 +414,63 @@ extension QueryInterfaceQuery { // MARK: - AssociationJoin +/// Not to be mismatched with SQL join operators (inner join, left join). +/// +/// AssociationJoinOperator is designed to be hierarchically nested, unlike +/// SQL join operators. +/// +/// Consider the following request for (A, B, C) tuples: +/// +/// let r = A.including(optional: A.b.including(required: B.c)) +/// +/// It chains three associations, the first optional, the second required. +/// +/// It looks like it means: "Give me all As, along with their Bs, granted those +/// Bs have their Cs. For As whose B has no C, give me a nil B". +/// +/// It can not be expressed as one left join, and a regular join, as below, +/// Because this would not honor the first optional: +/// +/// -- dubious +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// JOIN c ON ... +/// +/// Instead, it should: +/// - allow (A + missing (B + C)) +/// - prevent (A + (B + missing C)). +/// +/// This can be expressed in SQL with two left joins, and an extra condition: +/// +/// -- likely correct +/// SELECT a.*, b.*, c.* +/// FROM a +/// LEFT JOIN b ON ... +/// LEFT JOIN c ON ... +/// WHERE NOT((b.id IS NOT NULL) AND (c.id IS NULL)) -- no B without C +/// +/// This is currently not implemented, and requires a little more thought. +/// I don't even know if inventing a whole new way to perform joins should even +/// be on the table. But we have a hierarchical way to express joined queries, +/// and they have a meaning: +/// +/// // what is my meaning? +/// A.including(optional: A.b.including(required: B.c)) +enum AssociationJoinOperator { + case required, optional +} + struct AssociationJoin { - var op: AssociationChainOperator + var joinOperator: AssociationJoinOperator var query: AssociationQuery var key: String - var associationMapping: (Database) throws -> AssociationMapping + var joinConditionPromise: (Database) throws -> JoinCondition func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" - switch op { + switch joinOperator { case .optional: isRequiredAllowed = false sql += "LEFT JOIN" @@ -439,7 +486,7 @@ struct AssociationJoin { let qualifier = query.qualifier! let filters = try [ - associationMapping(db)(leftQualifier, qualifier), + joinConditionPromise(db)(leftQualifier, qualifier), query.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 309da524b..4ab22160c 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -1,13 +1,13 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { - func chain(_ chainOp: AssociationChainOperator, _ association: A) + func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { let join = AssociationJoin( - op: chainOp, + joinOperator: joinOperator, query: association.request.query, key: association.key, - associationMapping: association.associationMapping) + joinConditionPromise: association.joinCondition) return QueryInterfaceRequest(query: query.joining(join)) } @@ -16,60 +16,29 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder - { - return chain(.optional, association) + public func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.optional, association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder - { - return chain(.required, association) + public func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.required, association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder - { - return chain(.optional, association.select([])) + public func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.optional, association.select([])) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder - { - return chain(.required, association.select([])) - } -} - -extension Association where LeftAssociated: MutablePersistableRecord { - func request(from record: LeftAssociated) -> QueryInterfaceRequest { - var query = request.query.qualifiedQuery // make sure query has a qualifier - let qualifier = query.qualifier! - let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) - - query = query.filter { db in - let associationMapping = try self.associationMapping(db) - guard let filter = associationMapping(recordQualifier, qualifier) else { - fatalError("Can't request from record without association mapping") - } - let container = PersistenceContainer(record) // support for record classes: late construction of container - return filter.resolvedExpression(inContext: [recordQualifier: container]) - } - - return QueryInterfaceRequest(query: QueryInterfaceQuery(query)) + public func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + return joining(.required, association.select([])) } } @@ -85,10 +54,7 @@ extension MutablePersistableRecord { /// let player: Player = ... /// let request = player.request(for: Player.team) /// let team = try request.fetchOne(db) // Team? - public func request(for association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == Self - { + public func request(for association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return association.request(from: self) } } @@ -100,40 +66,28 @@ extension TableRecord { /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public static func including(optional association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == Self - { + public static func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return all().including(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public static func including(required association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == Self - { + public static func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return all().including(required: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public static func joining(optional association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == Self - { + public static func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return all().joining(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public static func joining(required association: A) - -> QueryInterfaceRequest - where A.LeftAssociated == Self - { + public static func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return all().joining(required: association) } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 09684ca77..9a083ad0f 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -211,8 +211,6 @@ 5653EB9C20961FC000F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */; }; 5653EB9D20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; 5653EB9E20961FC000F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8C20961FBF00F46237 /* Association.swift */; }; - 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; - 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */; }; 5653EBA220961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EBA320961FCA00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EBB820961FE800F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */; }; @@ -967,7 +965,6 @@ 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB8C20961FBF00F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; - 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EBA620961FE600F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; 5653EBA720961FE600F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; @@ -1471,15 +1468,14 @@ 5653EB8420961FBF00F46237 /* Association */ = { isa = PBXGroup; children = ( - 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, - 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, + 5653EB8C20961FBF00F46237 /* Association.swift */, 5653EB8720961FBF00F46237 /* AssociationQuery.swift */, - 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, + 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, + 5653EB8520961FBF00F46237 /* BelongsToAssociation.swift */, 5653EB8920961FBF00F46237 /* ForeignKey.swift */, 5653EB8A20961FBF00F46237 /* ForeignKeyRequest.swift */, - 5653EB8B20961FBF00F46237 /* AssociationRequest.swift */, - 5653EB8C20961FBF00F46237 /* Association.swift */, - 5653EB8D20961FBF00F46237 /* AssociationMapping.swift */, + 5653EB8820961FBF00F46237 /* HasManyAssociation.swift */, + 5653EB8620961FBF00F46237 /* HasOneAssociation.swift */, ); path = Association; sourceTree = ""; @@ -2193,7 +2189,6 @@ 560FC5341CB003810014AA8E /* QueryInterfaceQuery.swift in Sources */, 566B912C1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 560FC5351CB003810014AA8E /* Statement.swift in Sources */, - 5653EB9F20961FC000F46237 /* AssociationMapping.swift in Sources */, 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, @@ -2625,7 +2620,6 @@ 56AFCA091CB1A8BB00F48B96 /* QueryInterfaceQuery.swift in Sources */, 566B912F1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, 56AFCA0A1CB1A8BB00F48B96 /* Migration.swift in Sources */, - 5653EBA020961FC000F46237 /* AssociationMapping.swift in Sources */, 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 210584469..7f137ab7d 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -67,8 +67,6 @@ 5653EB4E20961F6100F46237 /* AssociationRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3D20961F6100F46237 /* AssociationRequest.swift */; }; 5653EB4F20961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; 5653EB5020961F6100F46237 /* Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3E20961F6100F46237 /* Association.swift */; }; - 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; - 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB3F20961F6100F46237 /* AssociationMapping.swift */; }; 5653EB5420961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EB5520961F7D00F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EB6820961FB200F46237 /* AssociationParallelSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */; }; @@ -640,7 +638,6 @@ 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyRequest.swift; sourceTree = ""; }; 5653EB3D20961F6100F46237 /* AssociationRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationRequest.swift; sourceTree = ""; }; 5653EB3E20961F6100F46237 /* Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Association.swift; sourceTree = ""; }; - 5653EB3F20961F6100F46237 /* AssociationMapping.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationMapping.swift; sourceTree = ""; }; 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; 5653EB5820961FB000F46237 /* AssociationParallelSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationParallelSQLTests.swift; sourceTree = ""; }; 5653EB5920961FB100F46237 /* AssociationBelongsToFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToFetchableRecordTests.swift; sourceTree = ""; }; @@ -1117,15 +1114,14 @@ 5653EB3620961F6000F46237 /* Association */ = { isa = PBXGroup; children = ( - 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, - 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, + 5653EB3E20961F6100F46237 /* Association.swift */, 5653EB3920961F6000F46237 /* AssociationQuery.swift */, - 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, + 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, + 5653EB3720961F6000F46237 /* BelongsToAssociation.swift */, 5653EB3B20961F6000F46237 /* ForeignKey.swift */, 5653EB3C20961F6000F46237 /* ForeignKeyRequest.swift */, - 5653EB3D20961F6100F46237 /* AssociationRequest.swift */, - 5653EB3E20961F6100F46237 /* Association.swift */, - 5653EB3F20961F6100F46237 /* AssociationMapping.swift */, + 5653EB3A20961F6000F46237 /* HasManyAssociation.swift */, + 5653EB3820961F6000F46237 /* HasOneAssociation.swift */, ); path = Association; sourceTree = ""; @@ -1868,7 +1864,6 @@ F3BA800C1CFB286F003DC1BA /* DatabaseError.swift in Sources */, 566B91301FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA80221CFB288C003DC1BA /* NSNumber.swift in Sources */, - 5653EB5220961F6100F46237 /* AssociationMapping.swift in Sources */, 5653EB4620961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA80321CFB28A4003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48D1EA8D94E004A4992 /* Utils.swift in Sources */, @@ -2139,7 +2134,6 @@ F3BA80681CFB2E55003DC1BA /* DatabaseError.swift in Sources */, 566B912D1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */, F3BA807E1CFB2E61003DC1BA /* NSNumber.swift in Sources */, - 5653EB5120961F6100F46237 /* AssociationMapping.swift in Sources */, 5653EB4520961F6100F46237 /* AssociationQuery.swift in Sources */, F3BA808E1CFB2E7A003DC1BA /* FetchedRecordsController.swift in Sources */, 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */, From 9a379fc1bcf88d5ac3255a302688501f58f6661f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 12:57:12 +0200 Subject: [PATCH 204/348] Use DatabasePromise where relevant --- GRDB/QueryInterface/Association/AssociationRequest.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 4 ++-- GRDB/QueryInterface/QueryInterfaceRequest+Association.swift | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 2b3b3a568..4f5b252eb 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -46,7 +46,7 @@ extension AssociationRequest { joinOperator: joinOperator, query: association.request.query, key: association.key, - joinConditionPromise: association.joinCondition) + joinConditionPromise: DatabasePromise(association.joinCondition)) return AssociationRequest(query: query.joining(join)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 598c6e28f..a839f04e4 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -465,7 +465,7 @@ struct AssociationJoin { var joinOperator: AssociationJoinOperator var query: AssociationQuery var key: String - var joinConditionPromise: (Database) throws -> JoinCondition + var joinConditionPromise: DatabasePromise func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed @@ -486,7 +486,7 @@ struct AssociationJoin { let qualifier = query.qualifier! let filters = try [ - joinConditionPromise(db)(leftQualifier, qualifier), + joinConditionPromise.resolve(db)(leftQualifier, qualifier), query.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 4ab22160c..4e7025c57 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -7,7 +7,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { joinOperator: joinOperator, query: association.request.query, key: association.key, - joinConditionPromise: association.joinCondition) + joinConditionPromise: DatabasePromise(association.joinCondition)) return QueryInterfaceRequest(query: query.joining(join)) } From 09458c1d37d7f6d4a93ce4377e7c13475cb57b5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 13:41:20 +0200 Subject: [PATCH 205/348] Documentation, move asRequest(of:) to QueryInterfaceRequest in order to avoid AnyFetchRequest contamination --- GRDB/Core/FetchRequest.swift | 17 ---- GRDB/Legacy/Fixits-0.109.0.swift | 2 +- .../Association/Association.swift | 90 +++++++++++++++++-- .../Association/AssociationRequest.swift | 2 + .../QueryInterfaceRequest.swift | 25 +++++- GRDB/QueryInterface/RequestProtocols.swift | 5 +- 6 files changed, 112 insertions(+), 29 deletions(-) diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index d17185743..bcea72d7e 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -73,23 +73,6 @@ public protocol FetchRequest: SelectStatementRequest { } extension FetchRequest { - /// Returns a request bound to type T. - /// - /// The returned request can fetch if the type T is fetchable (Row, - /// value, record). - /// - /// // Int? - /// let maxScore = Player - /// .select(max(scoreColumn)) - /// .asRequest(of: Int.self) // <-- - /// .fetchOne(db) - /// - /// - parameter type: The fetched type T - /// - returns: A typed request bound to type T. - public func asRequest(of type: T.Type) -> AnyFetchRequest { - return AnyFetchRequest(self) - } - /// Returns an adapted request. public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { return AdaptedFetchRequest(self, adapter) diff --git a/GRDB/Legacy/Fixits-0.109.0.swift b/GRDB/Legacy/Fixits-0.109.0.swift index 6c2034ea6..1b9dcc727 100644 --- a/GRDB/Legacy/Fixits-0.109.0.swift +++ b/GRDB/Legacy/Fixits-0.109.0.swift @@ -1,4 +1,4 @@ extension FetchRequest { - @available(*, unavailable, renamed:"asRequest(of:)") + @available(*, unavailable, message:"Use QueryInterfaceRequest.asRequest(of:), or AnyFetchRequest") public func bound(to type: T.Type) -> AnyFetchRequest { preconditionFailure() } } diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index c0c1d1883..841739b8c 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -1,5 +1,7 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// /// The base protocol for all associations that define a connection between two -/// Record types. +/// record types. public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { associatedtype LeftAssociated associatedtype RightAssociated @@ -49,6 +51,7 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { /// :nodoc: var request: AssociationRequest { get } + // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: func joinCondition(_ db: Database) throws -> JoinCondition @@ -59,26 +62,97 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { extension Association { /// Creates an association with a new net of selected columns. /// - /// Any previous selection is replaced. + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.color + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team.select([Column("color")]) + /// var request = Player.including(required: association) + /// + /// Any previous selection is replaced: + /// + /// // SELECT player.*, team.color + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team + /// .select([Column("id")]) + /// .select([Column("color")]) + /// var request = Player.including(required: association) public func select(_ selection: [SQLSelectable]) -> Self { return mapRequest { $0.select(selection) } } /// Creates an association with the provided *predicate promise* added to /// the eventual set of already applied predicates. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId AND 1 + /// let association = Player.team.filter { db in true } + /// var request = Player.including(required: association) public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self { return mapRequest { $0.filter(predicate) } } /// Creates an association with the provided *orderings*. /// - /// Any previous ordering is replaced. + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name + /// let association = Player.team.order(Column("name")) + /// var request = Player.including(required: association) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name + /// let association = Player.team.order(Column("name")) + /// var request = Player.including(required: association) + /// + /// // SELECT * FROM player ORDER BY name + /// let association = Player.team + /// .order(Column("color")) + /// .reversed() + /// .order(Column("name")) + /// var request = Player.including(required: association) public func order(_ orderings: [SQLOrderingTerm]) -> Self { return mapRequest { $0.order(orderings) } } - /// Creates an association that reverses applied orderings. If no ordering - /// was applied, the returned request is identical. + /// Creates an association that reverses applied orderings. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// // ORDER BY team.name DESC + /// let association = Player.team.order(Column("name")).reversed() + /// var request = Player.including(required: association) + /// + /// If no ordering was applied, the returned association is identical. + /// + /// // SELECT player.*, team.* + /// // FROM player + /// // JOIN team ON team.id = player.teamId + /// let association = Player.team.reversed() + /// var request = Player.including(required: association) public func reversed() -> Self { return mapRequest { $0.reversed() } } @@ -95,7 +169,7 @@ extension Association { /// let player: Player /// let team: Team /// - /// static func all() -> AnyFetchRequest { + /// static func all() -> QueryInterfaceRequest { /// return Player /// .including(required: Player.team.forKey(CodingKeys.team)) /// .asRequest(of: PlayerInfo.self) @@ -107,7 +181,7 @@ extension Association { public func forKey(_ codingKey: CodingKey) -> Self { return forKey(codingKey.stringValue) } - + /// Creates an association that allows you to define unambiguous expressions /// based on the associated record. /// @@ -124,7 +198,7 @@ extension Association { /// let teamAlias = TableAlias() /// let request = Player /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(teamAlias[Column("color"] == "red") + /// .filter(teamAlias[Column("color")] == "red") /// /// When you give a name to a table alias, you can reliably inject sql /// snippets in your requests: diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 4f5b252eb..b584d20f6 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -1,3 +1,5 @@ +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// /// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, /// the AssociationRequest is (`b.*` + `b.name = 'foo'`). public struct AssociationRequest { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 0204305d1..aa782b4b8 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -110,11 +110,17 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating return QueryInterfaceRequest(query: query.order(orderings)) } - /// Creates a request sorted in reversed order. + /// Creates a request that reverses applied orderings. /// /// // SELECT * FROM players ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() + /// + /// If no ordering was applied, the returned request is identical. + /// + /// // SELECT * FROM players + /// var request = Player.all() + /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { return QueryInterfaceRequest(query: query.reversed()) } @@ -155,6 +161,23 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating } return QueryInterfaceRequest(query: query.qualified(with: &alias.qualifier)) } + + /// Creates a request bound to type Target. + /// + /// The returned request can fetch if the type Target is fetchable (Row, + /// value, record). + /// + /// // Int? + /// let maxScore = try Player + /// .select(max(scoreColumn)) + /// .asRequest(of: Int.self) // <-- + /// .fetchOne(db) + /// + /// - parameter type: The fetched type Target + /// - returns: A typed request bound to type Target. + public func asRequest(of type: Target.Type) -> QueryInterfaceRequest { + return QueryInterfaceRequest(query: query) + } } /// Conditional conformance to TableRequest when RowDecoder conforms diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index bf2987935..b1df8148f 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -241,13 +241,14 @@ public protocol OrderedRequest { /// .order([Column("name")]) func order(_ orderings: [SQLOrderingTerm]) -> Self - /// Creates a request that reverses applied orderings. If no ordering - /// was applied, the returned request is identical. + /// Creates a request that reverses applied orderings. /// /// // SELECT * FROM players ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() /// + /// If no ordering was applied, the returned request is identical. + /// /// // SELECT * FROM players /// var request = Player.all() /// request = request.reversed() From e6f084d39756beabf5bb42522134acfe3a402103 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 13:59:20 +0200 Subject: [PATCH 206/348] Law of Demeter --- .../Association/AssociationQuery.swift | 36 ++++++------ GRDB/QueryInterface/QueryInterfaceQuery.swift | 57 ++++++++++++------- 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index 1f580a82e..715787775 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -5,6 +5,18 @@ struct AssociationQuery { var ordering: QueryOrdering var joins: [AssociationJoin] + var qualifiedQuery: AssociationQuery { + var qualifier = SQLTableQualifier(tableName: source.tableName!) + + var query = self + query.source = source.qualified(with: &qualifier) + query.selection = selection.map { $0.qualifiedSelectable(with: qualifier) } + query.filterPromise = filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } + query.ordering = ordering.qualified(with: qualifier) + query.joins = joins.map { $0.qualifiedJoin } + return query + } + var qualifier: SQLTableQualifier? { return source.qualifier } @@ -15,35 +27,19 @@ struct AssociationQuery { qualifiers.append(qualifier) } return joins.reduce(into: qualifiers) { - $0.append(contentsOf: $1.query.allQualifiers) + $0.append(contentsOf: $1.allQualifiers) } } - var qualifiedQuery: AssociationQuery { - var qualifier = SQLTableQualifier(tableName: source.tableName!) - - var query = self - query.source = query.source.qualified(with: &qualifier) - query.selection = selection.map { $0.qualifiedSelectable(with: qualifier) } - query.filterPromise = filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } - query.ordering = ordering.qualified(with: qualifier) - query.joins = joins.map { - var join = $0 - join.query = join.query.qualifiedQuery - return join - } - return query - } - var completeSelection: [SQLSelectable] { return joins.reduce(into: selection) { - $0.append(contentsOf: $1.query.completeSelection) + $0.append(contentsOf: $1.completeSelection) } } var completeOrdering: QueryOrdering { return joins.reduce(ordering) { - $0.appending($1.query.completeOrdering) + $0.appending($1.completeOrdering) } } @@ -55,7 +51,7 @@ struct AssociationQuery { var endIndex = startIndex + selectionWidth var scopes: [String: RowAdapter] = [:] for join in joins { - if let (joinAdapter, joinEndIndex) = try join.query.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + if let (joinAdapter, joinEndIndex) = try join.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") scopes[join.key] = joinAdapter endIndex = joinEndIndex diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index a839f04e4..f19e43a23 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -147,18 +147,6 @@ struct QueryInterfaceQuery { // MARK: Join Support - var completeSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.query.completeSelection) - } - } - - var completeOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.query.completeOrdering) - } - } - var qualifier: SQLTableQualifier? { return source.qualifier } @@ -169,7 +157,19 @@ struct QueryInterfaceQuery { qualifiers.append(qualifier) } return joins.reduce(into: qualifiers) { - $0.append(contentsOf: $1.query.allQualifiers) + $0.append(contentsOf: $1.allQualifiers) + } + } + + var completeSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.completeSelection) + } + } + + var completeOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.completeOrdering) } } } @@ -178,6 +178,7 @@ extension QueryInterfaceQuery { private var qualifiedQuery: QueryInterfaceQuery { var query = self + // Don't qualify unless there are joins if !joins.isEmpty { var qualifier = SQLTableQualifier(tableName: query.source.tableName!) query.source = source.qualified(with: &qualifier) @@ -191,11 +192,7 @@ extension QueryInterfaceQuery { query.havingExpression = query.havingExpression?.qualifiedExpression(with: qualifier) } - query.joins = query.joins.map { - var join = $0 - join.query = join.query.qualifiedQuery - return join - } + query.joins = query.joins.map { $0.qualifiedJoin } query.allQualifiers.resolveAmbiguities() return query @@ -223,7 +220,7 @@ extension QueryInterfaceQuery { var endIndex = selectionWidth var scopes: [String: RowAdapter] = [:] for join in joins { - if let (joinAdapter, joinEndIndex) = try join.query.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + if let (joinAdapter, joinEndIndex) = try join.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") scopes[join.key] = joinAdapter endIndex = joinEndIndex @@ -467,6 +464,28 @@ struct AssociationJoin { var key: String var joinConditionPromise: DatabasePromise + var qualifiedJoin: AssociationJoin { + var join = self + join.query = query.qualifiedQuery + return join + } + + var allQualifiers: [SQLTableQualifier] { + return query.allQualifiers + } + + var completeSelection: [SQLSelectable] { + return query.completeSelection + } + + var completeOrdering: QueryOrdering { + return query.completeOrdering + } + + func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + return try query.rowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) + } + func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" From 9f78a758bd370e9be5cec2c6e205af673e0182e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 14:04:07 +0200 Subject: [PATCH 207/348] RowAdapter.addingScopes returns self if the scopes dictionary is empty --- GRDB/Core/RowAdapter.swift | 6 +++++- TODO.md | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index 3434651ac..f322bf4d2 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -237,7 +237,11 @@ extension RowAdapter { /// - parameter scopes: A dictionary that maps scope names to /// row adapters. public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter { - return ScopeAdapter(base: self, scopes: scopes) + if scopes.isEmpty { + return self + } else { + return ScopeAdapter(base: self, scopes: scopes) + } } } diff --git a/TODO.md b/TODO.md index 6200b7834..f5c6fbcd4 100644 --- a/TODO.md +++ b/TODO.md @@ -27,7 +27,7 @@ GRDB 3.0 - sync - ? - [ ] filter(rowid:), filter(rowids:) -- [ ] If required by associations, make reversed() make nothing when there is no alraedy applied ordering +- [ ] hide ScopeAdapter(base, scopes), because base.addingScopes has a better implementation Not sure From 8d5e57873e6103c0f93aa5ce679fca5b73465f73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 15:33:16 +0200 Subject: [PATCH 208/348] Documentation --- .../Association/Association.swift | 25 +++++++++++++------ .../QueryInterfaceRequest+Association.swift | 12 +++++---- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 841739b8c..3ec70811e 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -34,7 +34,7 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { /// Creates an association with the given key. /// - /// This new key impacts how rows fetched from this association + /// This new key impacts how rows fetched from the resulting association /// should be consumed: /// /// struct Player: TableRecord { @@ -120,10 +120,6 @@ extension Association { /// // FROM player /// // JOIN team ON team.id = player.teamId /// // ORDER BY team.name - /// let association = Player.team.order(Column("name")) - /// var request = Player.including(required: association) - /// - /// // SELECT * FROM player ORDER BY name /// let association = Player.team /// .order(Column("color")) /// .reversed() @@ -159,7 +155,8 @@ extension Association { /// Creates an association with the given key. /// - /// This new key helps Decodable records decode fetched rows: + /// This new key helps Decodable records decode rows fetched from the + /// resulting association: /// /// struct Player: TableRecord { /// static let team = belongsTo(Team.self) @@ -209,7 +206,7 @@ extension Association { /// let teamAlias = TableAlias(name: "custom") /// let request = Player /// .including(required: Player.team.aliased(teamAlias)) - /// .filter(sql: "custom.color = ?", arguments: ["red") + /// .filter(sql: "custom.color = ?", arguments: ["red"]) public func aliased(_ alias: TableAlias) -> Self { return mapRequest { $0.aliased(alias) } } @@ -217,6 +214,7 @@ extension Association { public typealias JoinCondition = (_ leftQualifier: SQLTableQualifier, _ rightQualifier: SQLTableQualifier) -> SQLExpression? +/// Turns a ForeignKeyRequest into a JoinCondition struct ForeignKeyJoinConditionRequest { var foreignKeyRequest: ForeignKeyRequest var originIsLeft: Bool @@ -268,6 +266,19 @@ extension Association { } extension Association where LeftAssociated: MutablePersistableRecord { + /// Support for MutablePersistableRecord.request(for:). + /// + /// For example: + /// + /// struct Team: { + /// static let players = hasMany(Book.self) + /// var players: QueryInterfaceRequest { + /// return request(for: Team.players) + /// } + /// } + /// + /// let team: Team = ... + /// let players = try team.players.fetchAll(db) // [Player] func request(from record: LeftAssociated) -> QueryInterfaceRequest { let query = request.query.qualifiedQuery // make sure query has a qualifier let associationQualifier = query.qualifier! diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 4e7025c57..7b4fc8073 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -47,13 +47,15 @@ extension MutablePersistableRecord { /// /// For example: /// - /// struct Player: TableRecord { - /// static let team = belongsTo(Team.self) + /// struct Team: { + /// static let players = hasMany(Book.self) + /// var players: QueryInterfaceRequest { + /// return request(for: Team.players) + /// } /// } /// - /// let player: Player = ... - /// let request = player.request(for: Player.team) - /// let team = try request.fetchOne(db) // Team? + /// let team: Team = ... + /// let players = try team.players.fetchAll(db) // [Player] public func request(for association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { return association.request(from: self) } From 344eba821f3179f39728514d087a83a1f34c5331 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 30 Apr 2018 19:31:56 +0200 Subject: [PATCH 209/348] Spot more qualifier/alias problems --- GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift | 1 + GRDB/QueryInterface/FTS5+QueryInterface.swift | 1 + GRDB/QueryInterface/QueryInterfaceQuery.swift | 1 + 3 files changed, 3 insertions(+) diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 6e2d37356..f3efa1d00 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -12,6 +12,7 @@ extension QueryInterfaceRequest { /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { + // TODO: should use proper qualified name return filter(Column(query.source.qualifiedName).match(pattern)) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index fcc29e883..c864efc6b 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -20,6 +20,7 @@ guard let pattern = pattern else { return none() } + // TODO: should use proper qualified name return filter(SQLExpressionBinary(.match, Column(query.source.qualifiedName), pattern)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index f19e43a23..3eae89876 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -617,6 +617,7 @@ enum SQLSource { } } + // TODO: remove /// An alias or an actual table name var qualifiedName: String { switch self { From 66a425f71812f145498438c0c79c6474e7bb651a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 14:44:51 +0200 Subject: [PATCH 210/348] Thread-safe table name disambiguation, via SQLGenerationContext. Merge SQLTableQualifier into TableAlias. --- GRDB.xcodeproj/project.pbxproj | 8 + GRDB/Core/DatabaseValue.swift | 9 +- GRDB/Legacy/Fixits-3.0.swift | 4 + .../Association/Association.swift | 24 +- .../Association/AssociationQuery.swift | 33 +-- .../Association/AssociationRequest.swift | 7 +- GRDB/QueryInterface/Column.swift | 26 +- .../FTS3+QueryInterfaceRequest.swift | 9 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 6 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 171 +++++------ .../QueryInterfaceRequest.swift | 17 +- GRDB/QueryInterface/RequestProtocols.swift | 20 ++ .../SQLCollatedExpression.swift | 8 +- GRDB/QueryInterface/SQLCollection.swift | 21 +- GRDB/QueryInterface/SQLExpressible.swift | 12 +- .../SQLExpression+QueryInterface.swift | 170 ++++++----- GRDB/QueryInterface/SQLExpression.swift | 41 +-- .../QueryInterface/SQLGenerationContext.swift | 265 ++++++++++++++++++ GRDB/QueryInterface/SQLOrdering.swift | 31 +- .../SQLSelectable+QueryInterface.swift | 54 ++-- GRDB/QueryInterface/SQLSelectable.swift | 161 +---------- ...QLSpecificExpressible+QueryInterface.swift | 4 +- GRDB/Record/TableRecord.swift | 12 +- GRDBCipher.xcodeproj/project.pbxproj | 18 +- GRDBCustom.xcodeproj/project.pbxproj | 6 + TODO.md | 2 + Tests/GRDBTests/ColumnExpressionTests.swift | 10 +- .../GRDBTests/SQLExpressionLiteralTests.swift | 11 +- 28 files changed, 634 insertions(+), 526 deletions(-) create mode 100644 GRDB/QueryInterface/SQLGenerationContext.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 09785bcf6..4a264ad8d 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -203,6 +203,9 @@ 5653EB252094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EB262094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; 5653EB272094A14400F46237 /* QueryInterfaceRequest+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */; }; + 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; + 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; + 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; }; 565490B41D5A4820005622CB /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B51D5A4827005622CB /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 565490B61D5AE236005622CB /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; }; @@ -884,6 +887,7 @@ 5653EAFF20944C7C00F46237 /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = ""; }; 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HasOneAssociation.swift; sourceTree = ""; }; 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "QueryInterfaceRequest+Association.swift"; sourceTree = ""; }; + 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; @@ -1372,6 +1376,7 @@ 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -2361,6 +2366,7 @@ 56BF6D351DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 566B91291FA4CF810012D5B0 /* Database+Schema.swift in Sources */, 5671FC261DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, + 5653EC142098738B00F46237 /* SQLGenerationContext.swift in Sources */, 56CEB5521EAA359A00BFAF62 /* SQLExpressible.swift in Sources */, 565490DB1D5AE252005622CB /* SQLCollatedExpression.swift in Sources */, 5674A7071F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, @@ -2466,6 +2472,7 @@ 56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 5653EB1620944C7C00F46237 /* AssociationQuery.swift in Sources */, 560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */, + 5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */, 5657AB121D10899D006283EF /* URL.swift in Sources */, 5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */, 5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */, @@ -2942,6 +2949,7 @@ 56A238871B9C75030082EB20 /* Row.swift in Sources */, 5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */, 5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */, + 5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */, 560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 566475A21D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 258bdefe2..3b804a745 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -308,14 +308,13 @@ extension DatabaseValue { extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { // fast path for NULL if isNull { return "NULL" } - if arguments != nil { - arguments!.values.append(self) + if context.appendArguments([self]) { return "?" } else { // Correctness above all: use SQLite to quote the value. @@ -352,13 +351,13 @@ extension DatabaseValue { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return self } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index b1730ba26..78f41549f 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -18,6 +18,10 @@ public typealias MutablePersistable = MutablePersistableRecord @available(*, unavailable, renamed:"PersistableRecord") public typealias Persistable = PersistableRecord +/// :nodoc: +@available(*, unavailable, renamed:"TableAlias") +public typealias SQLTableQualifier = TableAlias + extension Database { /// :nodoc: @available(*, unavailable, message: "Use db.columns(in: tableName).count instead") diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 3ec70811e..6edc0fd32 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -179,8 +179,8 @@ extension Association { return forKey(codingKey.stringValue) } - /// Creates an association that allows you to define unambiguous expressions - /// based on the associated record. + /// Creates an association that allows you to define expressions that target + /// a specific database table. /// /// In the example below, the "team.color = 'red'" condition in the where /// clause could be not achieved without table aliases. @@ -212,7 +212,7 @@ extension Association { } } -public typealias JoinCondition = (_ leftQualifier: SQLTableQualifier, _ rightQualifier: SQLTableQualifier) -> SQLExpression? +public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression? /// Turns a ForeignKeyRequest into a JoinCondition struct ForeignKeyJoinConditionRequest { @@ -227,9 +227,9 @@ struct ForeignKeyJoinConditionRequest { } else { columnMapping = foreignKeyMapping.map { (left: Column($0.destination), right: Column($0.origin)) } } - return { (leftQualifier, rightQualifier) in + return { (leftAlias, rightAlias) in return columnMapping - .map { $0.right.qualifiedExpression(with: rightQualifier) == $0.left.qualifiedExpression(with: leftQualifier) } + .map { $0.right.qualifiedExpression(with: rightAlias) == $0.left.qualifiedExpression(with: leftAlias) } .joined(operator: .and) } } @@ -280,17 +280,17 @@ extension Association where LeftAssociated: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: LeftAssociated) -> QueryInterfaceRequest { - let query = request.query.qualifiedQuery // make sure query has a qualifier - let associationQualifier = query.qualifier! - let recordQualifier = SQLTableQualifier.init(tableName: LeftAssociated.databaseTableName) + let associationAlias = TableAlias() + let query = request.query.qualified(with: associationAlias) + let recordAlias = TableAlias(tableName: LeftAssociated.databaseTableName) - // Turn `right.id = left.id` into `right.id = 1` + // Turn `associated.recordId = record.id` into `associated.recordId = 1` let resolvedQuery = query.filter { db in - guard let joinCondition = try self.joinCondition(db)(recordQualifier, associationQualifier) else { - fatalError("Can't request from record without association mapping") + guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { + fatalError("Can't request from record without join condition") } let container = PersistenceContainer(record) // support for record classes: late construction of container - return joinCondition.resolvedExpression(inContext: [recordQualifier: container]) + return joinCondition.resolvedExpression(inContext: [recordAlias: container]) } return QueryInterfaceRequest(query: QueryInterfaceQuery(resolvedQuery)) diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index 715787775..2f09fdb3c 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -6,28 +6,29 @@ struct AssociationQuery { var joins: [AssociationJoin] var qualifiedQuery: AssociationQuery { - var qualifier = SQLTableQualifier(tableName: source.tableName!) - var query = self - query.source = source.qualified(with: &qualifier) - query.selection = selection.map { $0.qualifiedSelectable(with: qualifier) } - query.filterPromise = filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } - query.ordering = ordering.qualified(with: qualifier) + + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.ordering = ordering.qualified(with: alias) query.joins = joins.map { $0.qualifiedJoin } + return query } - var qualifier: SQLTableQualifier? { - return source.qualifier + var alias: TableAlias? { + return source.alias } - var allQualifiers: [SQLTableQualifier] { - var qualifiers: [SQLTableQualifier] = [] - if let qualifier = qualifier { - qualifiers.append(qualifier) + var allAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) } - return joins.reduce(into: qualifiers) { - $0.append(contentsOf: $1.allQualifiers) + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.allAliases) } } @@ -122,9 +123,9 @@ extension AssociationQuery { return query } - func qualified(with qualifier: inout SQLTableQualifier) -> AssociationQuery { + func qualified(with alias: TableAlias) -> AssociationQuery { var query = self - query.source = source.qualified(with: &qualifier) + query.source = source.qualified(with: alias) return query } } diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index b584d20f6..ba9f08ade 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -32,12 +32,7 @@ extension AssociationRequest { } func aliased(_ alias: TableAlias) -> AssociationRequest { - let userProvidedAlias = alias.userProvidedAlias - defer { - // Allow user to explicitely rename (TODO: test) - alias.userProvidedAlias = userProvidedAlias - } - return AssociationRequest(query: query.qualified(with: &alias.qualifier)) + return AssociationRequest(query: query.qualified(with: alias)) } func joining(_ joinOperator: AssociationJoinOperator, _ association: A) diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 26010d442..5cfb79769 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -28,19 +28,19 @@ public protocol ColumnExpression: SQLExpression { extension ColumnExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { return name.quotedDatabaseIdentifier } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return QualifiedColumn(name, qualifier: qualifier) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return QualifiedColumn(name, alias: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } @@ -67,29 +67,29 @@ public struct Column: ColumnExpression { /// A qualified column in the database, as in `SELECT t.a FROM t` struct QualifiedColumn: ColumnExpression { var name: String - private let qualifier: SQLTableQualifier + private let alias: TableAlias /// Creates a column given its name. - init(_ name: String, qualifier: SQLTableQualifier) { + init(_ name: String, alias: TableAlias) { self.name = name - self.qualifier = qualifier + self.alias = alias } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.qualifiedName { - return qualifierName.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier } return name.quotedDatabaseIdentifier } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { // Never requalify return self } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { guard - let container = context[qualifier], + let container = context[alias.root], let value = container.value(forCaseInsensitiveColumn: name) else { return self diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index f3efa1d00..8370c844f 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -12,8 +12,13 @@ extension QueryInterfaceRequest { /// If the search pattern is nil, the request does not match any /// database row. public func matching(_ pattern: FTS3Pattern?) -> QueryInterfaceRequest { - // TODO: should use proper qualified name - return filter(Column(query.source.qualifiedName).match(pattern)) + guard let pattern = pattern else { + return none() + } + let alias = TableAlias() + let qualifiedQuery = query.qualified(with: alias) + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index c864efc6b..3fb0005b3 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -20,8 +20,10 @@ guard let pattern = pattern else { return none() } - // TODO: should use proper qualified name - return filter(SQLExpressionBinary(.match, Column(query.source.qualifiedName), pattern)) + let alias = TableAlias() + let qualifiedQuery = query.qualified(with: alias) + let matchExpression = TableMatchExpression(alias: alias, pattern: pattern.databaseValue) + return QueryInterfaceRequest(query: qualifiedQuery).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 3eae89876..4396a12b4 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -49,7 +49,7 @@ struct QueryInterfaceQuery { self.joins = joins } - func sql(_ db: Database, _ arguments: inout StatementArguments?) throws -> String { + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" if isDistinct { @@ -58,29 +58,31 @@ struct QueryInterfaceQuery { let selection = completeSelection GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - sql += " " + selection.map { $0.resultColumnSQL(&arguments) }.joined(separator: ", ") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - sql += try " FROM " + source.sourceSQL(db, &arguments) + sql += try " FROM " + source.sourceSQL(db, &context) for join in joins { - sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier!, isRequiredAllowed: true) + sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) } if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&arguments) + sql += " WHERE " + filter.expressionSQL(&context) } if !groupByExpressions.isEmpty { - sql += " GROUP BY " + groupByExpressions.map { $0.expressionSQL(&arguments) }.joined(separator: ", ") + sql += " GROUP BY " + sql += groupByExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") } if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&arguments) + sql += " HAVING " + havingExpression.expressionSQL(&context) } let orderings = completeOrdering.resolve() if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } if let limit = limit { @@ -90,6 +92,7 @@ struct QueryInterfaceQuery { return sql } + /// precondition: self is the result of qualifiedQuery func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { guard groupByExpressions.isEmpty else { // Programmer error @@ -111,19 +114,18 @@ struct QueryInterfaceQuery { fatalError("Can't delete without any database table") } - var sql = "DELETE" - var arguments: StatementArguments? = StatementArguments() + var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases) - sql += try " FROM " + source.sourceSQL(db, &arguments) + var sql = try "DELETE FROM " + source.sourceSQL(db, &context) if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&arguments) + sql += " WHERE " + filter.expressionSQL(&context) } if let limit = limit { let orderings = self.completeOrdering.resolve() if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&arguments) }.joined(separator: ", ") + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { @@ -134,7 +136,7 @@ struct QueryInterfaceQuery { } let statement = try db.makeUpdateStatement(sql) - statement.arguments = arguments! + statement.arguments = context.arguments! return statement } @@ -147,17 +149,17 @@ struct QueryInterfaceQuery { // MARK: Join Support - var qualifier: SQLTableQualifier? { - return source.qualifier + var alias: TableAlias? { + return source.alias } - var allQualifiers: [SQLTableQualifier] { - var qualifiers: [SQLTableQualifier] = [] - if let qualifier = qualifier { - qualifiers.append(qualifier) + var allAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) } - return joins.reduce(into: qualifiers) { - $0.append(contentsOf: $1.allQualifiers) + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.allAliases) } } @@ -178,32 +180,25 @@ extension QueryInterfaceQuery { private var qualifiedQuery: QueryInterfaceQuery { var query = self - // Don't qualify unless there are joins - if !joins.isEmpty { - var qualifier = SQLTableQualifier(tableName: query.source.tableName!) - query.source = source.qualified(with: &qualifier) - } - - if let qualifier = query.qualifier { - query.selection = query.selection.map { $0.qualifiedSelectable(with: qualifier) } - query.filterPromise = query.filterPromise.map { [qualifier] (_, expr) in expr?.qualifiedExpression(with: qualifier) } - query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: qualifier) } - query.ordering = query.ordering.qualified(with: qualifier) - query.havingExpression = query.havingExpression?.qualifiedExpression(with: qualifier) - } + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) } + query.ordering = query.ordering.qualified(with: alias) + query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) query.joins = query.joins.map { $0.qualifiedJoin } - query.allQualifiers.resolveAmbiguities() return query } /// precondition: self is the result of qualifiedQuery private func makeSelectStatement(_ db: Database) throws -> SelectStatement { - var arguments: StatementArguments? = StatementArguments() - let sql = try self.sql(db, &arguments) + var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases) + let sql = try self.sql(db, &context) let statement = try db.makeSelectStatement(sql) - try statement.setArgumentsWithValidation(arguments!) + statement.arguments = context.arguments! return statement } @@ -253,7 +248,7 @@ extension QueryInterfaceQuery { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard joins.isEmpty, case .table(tableName: let tableName, qualifier: _) = source else { + guard joins.isEmpty, case .table(tableName: let tableName, alias: _) = source else { // TODO: try harder return region } @@ -391,9 +386,9 @@ extension QueryInterfaceQuery { return query } - func qualified(with qualifier: inout SQLTableQualifier) -> QueryInterfaceQuery { + func qualified(with alias: TableAlias) -> QueryInterfaceQuery { var query = self - query.source = source.qualified(with: &qualifier) + query.source = source.qualified(with: alias) return query } } @@ -470,8 +465,8 @@ struct AssociationJoin { return join } - var allQualifiers: [SQLTableQualifier] { - return query.allQualifiers + var allAliases: [TableAlias] { + return query.allAliases } var completeSelection: [SQLSelectable] { @@ -486,7 +481,7 @@ struct AssociationJoin { return try query.rowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) } - func joinSQL(_ db: Database,_ arguments: inout StatementArguments?, leftQualifier: SQLTableQualifier, isRequiredAllowed: Bool) throws -> String { + func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" switch joinOperator { @@ -501,19 +496,19 @@ struct AssociationJoin { sql += "JOIN" } - sql += try " " + query.source.sourceSQL(db, &arguments) + sql += try " " + query.source.sourceSQL(db, &context) - let qualifier = query.qualifier! + let rightAlias = query.alias! let filters = try [ - joinConditionPromise.resolve(db)(leftQualifier, qualifier), + joinConditionPromise.resolve(db)(leftAlias, rightAlias), query.filterPromise.resolve(db) ].compactMap { $0 } if !filters.isEmpty { - sql += " ON " + filters.joined(operator: .and).expressionSQL(&arguments) + sql += " ON " + filters.joined(operator: .and).expressionSQL(&context) } for join in query.joins { - sql += try " " + join.joinSQL(db, &arguments, leftQualifier: qualifier, isRequiredAllowed: isRequiredAllowed) + sql += try " " + join.joinSQL(db, &context, leftAlias: rightAlias, isRequiredAllowed: isRequiredAllowed) } return sql @@ -539,12 +534,12 @@ struct QueryOrdering { } } - func qualified(with qualifier: SQLTableQualifier) -> Element { + func qualified(with alias: TableAlias) -> Element { switch self { case .orderingTerm(let orderingTerm): - return .orderingTerm(orderingTerm.qualifiedOrdering(with: qualifier)) + return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.qualified(with: qualifier)) + return .queryOrdering(queryOrdering.qualified(with: alias)) } } @@ -581,9 +576,9 @@ struct QueryOrdering { isReversed: !isReversed) } - func qualified(with qualifier: SQLTableQualifier) -> QueryOrdering { + func qualified(with alias: TableAlias) -> QueryOrdering { return QueryOrdering( - elements: elements.map { $0.qualified(with: qualifier) }, + elements: elements.map { $0.qualified(with: alias) }, isReversed: isReversed) } @@ -605,75 +600,43 @@ struct QueryOrdering { // MARK: - SQLSource enum SQLSource { - case table(tableName: String, qualifier: SQLTableQualifier?) + case table(tableName: String, alias: TableAlias?) indirect case query(QueryInterfaceQuery) - var qualifier: SQLTableQualifier? { + var alias: TableAlias? { switch self { - case .table(_, let qualifier): - return qualifier + case .table(_, let alias): + return alias case .query(let query): - return query.qualifier + return query.alias } } - // TODO: remove - /// An alias or an actual table name - var qualifiedName: String { + func sourceSQL(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { switch self { - case .table(let tableName, let qualifier): - return qualifier?.qualifiedName ?? tableName - case .query(let query): - return query.source.qualifiedName - } - } - - /// An actual table name, not an alias - var tableName: String? { - switch self { - case .table(let tableName, _): - return tableName - case .query(let query): - return query.source.tableName - } - } - - func sourceSQL(_ db: Database,_ arguments: inout StatementArguments?) throws -> String { - switch self { - case .table(let tableName, let qualifier): - if let alias = qualifier?.alias, alias != tableName { - return "\(tableName.quotedDatabaseIdentifier) \(alias.quotedDatabaseIdentifier)" + case .table(let tableName, let alias): + if let alias = alias, let aliasName = context.aliasName(for: alias) { + return "\(tableName.quotedDatabaseIdentifier) \(aliasName.quotedDatabaseIdentifier)" } else { return "\(tableName.quotedDatabaseIdentifier)" } case .query(let query): - return try "(\(query.sql(db, &arguments)))" + return try "(\(query.sql(db, &context)))" } } - func qualified(with qualifier: inout SQLTableQualifier) -> SQLSource { + func qualified(with alias: TableAlias) -> SQLSource { switch self { - case .table(let tableName, let oldQualifier): - if let oldQualifier = oldQualifier { - qualifier = oldQualifier + case .table(let tableName, let sourceAlias): + if let sourceAlias = sourceAlias { + alias.rebase(on: sourceAlias) return self - } else if let qualifierTableName = qualifier.tableName { - if qualifierTableName == tableName { // TODO: should this test be case-insensitive? - return .table( - tableName: tableName, - qualifier: qualifier) - } else { - // TODO: how to enter this branch? Is it useful? - return self - } } else { - qualifier.tableName = tableName - return .table( - tableName: tableName, - qualifier: qualifier) + alias.setTableName(tableName) + return .table(tableName: tableName, alias: alias) } case .query(let query): - return .query(query.qualified(with: &qualifier)) + return .query(query.qualified(with: alias)) } } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index aa782b4b8..f1edafcab 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -136,8 +136,8 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating return QueryInterfaceRequest(query: query.limit(limit, offset: offset)) } - /// Creates a request that allows you to define unambiguous expressions - /// based on the fetched record. + /// Creates a request that allows you to define expressions that target + /// a specific database table. /// /// In the example below, the "team.avgScore < player.score" condition in /// the ON clause could be not achieved without table aliases. @@ -154,12 +154,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// .aliased(playerAlias) /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { - let userProvidedAlias = alias.userProvidedAlias - defer { - // Allow user to explicitely rename (TODO: test) - alias.userProvidedAlias = userProvidedAlias - } - return QueryInterfaceRequest(query: query.qualified(with: &alias.qualifier)) + return QueryInterfaceRequest(query: query.qualified(with: alias)) } /// Creates a request bound to type Target. @@ -223,7 +218,7 @@ extension TableRecord { /// for individual requests with the `TableRecord.select` method. public static func all() -> QueryInterfaceRequest { let query = QueryInterfaceQuery( - source: .table(tableName: databaseTableName, qualifier: nil), + source: .table(tableName: databaseTableName, alias: nil), selection: databaseSelection) return QueryInterfaceRequest(query: query) } @@ -386,8 +381,8 @@ extension TableRecord { return all().limit(limit, offset: offset) } - /// Creates a request that allows you to define unambiguous expressions - /// based on the fetched record. + /// Creates a request that allows you to define expressions that target + /// a specific database table. /// /// In the example below, the "team.avgScore < player.score" condition in /// the ON clause could be not achieved without table aliases. diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index b1df8148f..cb05debc5 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -99,7 +99,27 @@ extension FilteredRequest { /// The protocol for all requests that feed from a database table public protocol TableRequest { + /// The name of the database table var databaseTableName: String { get } + + /// Creates a request that allows you to define expressions that target + /// a specific database table. + /// + /// In the example below, the "team.avgScore < player.score" condition in + /// the ON clause could be not achieved without table aliases. + /// + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// + /// // SELECT player.*, team.* + /// // JOIN team ON ... AND team.avgScore < player.score + /// let playerAlias = TableAlias() + /// let request = Player + /// .all() + /// .aliased(playerAlias) + /// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")]) + func aliased(_ alias: TableAlias) -> Self } extension TableRequest where Self: FilteredRequest { diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index b976014b6..9bd319b8c 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -58,13 +58,13 @@ extension SQLCollatedExpression : SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.orderingTermSQL(&arguments) + public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.orderingTermSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { - return SQLCollatedExpression(expression.qualifiedExpression(with: qualifier), collationName: collationName) + public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + return SQLCollatedExpression(expression.qualifiedExpression(with: alias), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQLCollection.swift b/GRDB/QueryInterface/SQLCollection.swift index 22923ae0e..3242b5ea7 100644 --- a/GRDB/QueryInterface/SQLCollection.swift +++ b/GRDB/QueryInterface/SQLCollection.swift @@ -9,22 +9,7 @@ public protocol SQLCollection { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the collection. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let collection = SQLExpressionsArray([1,2,3]) - /// collection.collectionSQL(&arguments) // "1,2,3" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let collection = SQLExpressionsArray([1,2,3]) - /// collection.collectionSQL(&arguments) // "?,?,?" - /// arguments // [1,2,3] - func collectionSQL(_ arguments: inout StatementArguments?) -> String + func collectionSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -58,8 +43,8 @@ struct SQLExpressionsArray : SQLCollection { self.expressions = expressions.map { $0.sqlExpression } } - func collectionSQL(_ arguments: inout StatementArguments?) -> String { - return (expressions.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + func collectionSQL(_ context: inout SQLGenerationContext) -> String { + return (expressions.map { $0.expressionSQL(&context) } as [String]).joined(separator: ", ") } func contains(_ value: SQLExpressible) -> SQLExpression { diff --git a/GRDB/QueryInterface/SQLExpressible.swift b/GRDB/QueryInterface/SQLExpressible.swift index 9d7aa31db..f90778684 100644 --- a/GRDB/QueryInterface/SQLExpressible.swift +++ b/GRDB/QueryInterface/SQLExpressible.swift @@ -64,8 +64,8 @@ extension SQLExpressible where Self: SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } } @@ -75,14 +75,14 @@ extension SQLExpressible where Self: SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func countedSQL(_ arguments: inout StatementArguments?) -> String { - return sqlExpression.expressionSQL(&arguments) + public func countedSQL(_ context: inout SQLGenerationContext) -> String { + return sqlExpression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 734e88d87..f17d8f6ae 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -8,17 +8,17 @@ extension SQLExpression { /// /// :nodoc: public var literal: SQLExpressionLiteral { - var arguments: StatementArguments? = [] - let sql = expressionSQL(&arguments) - return SQLExpressionLiteral(sql, arguments: arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = expressionSQL(&context) + return SQLExpressionLiteral(sql, arguments: context.arguments) } /// The expression as a quoted SQL literal (not public in order to avoid abuses) /// /// "foo'bar".databaseValue.sql // "'foo''bar'"" var sql: String { - var arguments: StatementArguments? = nil - return expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + return expressionSQL(&context) } } @@ -66,14 +66,13 @@ public struct SQLExpressionLiteral : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - if let literalArguments = self.arguments { - guard arguments != nil else { + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + if let arguments = arguments { + if context.appendArguments(arguments) == false { // GRDB limitation: we don't know how to look for `?` in sql and // replace them with with literals. fatalError("Not implemented") } - arguments! += literalArguments } if unsafeRaw { return sql @@ -84,13 +83,13 @@ public struct SQLExpressionLiteral : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return self } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } @@ -171,19 +170,19 @@ public struct SQLExpressionUnary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&arguments) + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&context) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionUnary(op, expression.qualifiedExpression(with: qualifier)) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionUnary(op, expression.qualifiedExpression(with: alias)) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionUnary(op, expression.resolvedExpression(inContext: context)) } } @@ -280,8 +279,8 @@ public struct SQLExpressionBinary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "(" + lhs.expressionSQL(&arguments) + " " + op.sql + " " + rhs.expressionSQL(&arguments) + ")" + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + lhs.expressionSQL(&context) + " " + op.sql + " " + rhs.expressionSQL(&context) + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -297,7 +296,7 @@ public struct SQLExpressionBinary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column qualifiers + // FIXME: this implementation ignores column aliases switch op { case .equal, .is: // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` @@ -331,13 +330,13 @@ public struct SQLExpressionBinary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionBinary(op, lhs.qualifiedExpression(with: qualifier), rhs.qualifiedExpression(with: qualifier)) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionBinary(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionBinary(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) } } @@ -351,23 +350,23 @@ struct SQLExpressionAnd : SQLExpression { self.expressions = expressions } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - guard let expression = expressions.first else { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + guard let first = expressions.first else { // Ruby [].all? # => true - return true.sqlExpression.expressionSQL(&arguments) + return true.sqlExpression.expressionSQL(&context) } if expressions.count == 1 { - return expression.expressionSQL(&arguments) + return first.expressionSQL(&context) } - let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } + let expressionSQLs = expressions.map { $0.expressionSQL(&context) } return "(" + expressionSQLs.joined(separator: " AND ") + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: qualifier) }) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionAnd(expressions.map { $0.qualifiedExpression(with: alias) }) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionAnd(expressions.map { $0.resolvedExpression(inContext: context) }) } @@ -391,23 +390,23 @@ struct SQLExpressionOr : SQLExpression { self.expressions = expressions } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - guard let expression = expressions.first else { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + guard let first = expressions.first else { // Ruby [].any? # => false - return false.sqlExpression.expressionSQL(&arguments) + return false.sqlExpression.expressionSQL(&context) } if expressions.count == 1 { - return expression.expressionSQL(&arguments) + return first.expressionSQL(&context) } - let expressionSQLs = expressions.map { $0.expressionSQL(&arguments) } + let expressionSQLs = expressions.map { $0.expressionSQL(&context) } return "(" + expressionSQLs.joined(separator: " OR ") + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: qualifier) }) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionOr(expressions.map { $0.qualifiedExpression(with: alias) }) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionOr(expressions.map { $0.resolvedExpression(inContext: context) }) } @@ -444,11 +443,11 @@ struct SQLExpressionContains : SQLExpression { self.isNegated = negated } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { return "(" + - expression.expressionSQL(&arguments) + + expression.expressionSQL(&context) + (isNegated ? " NOT IN (" : " IN (") + - collection.collectionSQL(&arguments) + + collection.collectionSQL(&context) + "))" } @@ -458,7 +457,7 @@ struct SQLExpressionContains : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column qualifiers + // FIXME: this implementation ignores column aliases // Look for `id IN (1, 2, 3)` guard let column = expression as? ColumnExpression, let array = collection as? SQLExpressionsArray else @@ -485,11 +484,11 @@ struct SQLExpressionContains : SQLExpression { return rowIDs } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionContains(expression.qualifiedExpression(with: qualifier), collection, negated: isNegated) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) } } @@ -514,13 +513,13 @@ struct SQLExpressionBetween : SQLExpression { self.isNegated = negated } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { + func expressionSQL(_ context: inout SQLGenerationContext) -> String { return "(" + - expression.expressionSQL(&arguments) + + expression.expressionSQL(&context) + (isNegated ? " NOT BETWEEN " : " BETWEEN ") + - lowerBound.expressionSQL(&arguments) + + lowerBound.expressionSQL(&context) + " AND " + - upperBound.expressionSQL(&arguments) + + upperBound.expressionSQL(&context) + ")" } @@ -528,15 +527,15 @@ struct SQLExpressionBetween : SQLExpression { return SQLExpressionBetween(expression, lowerBound, upperBound, negated: !isNegated) } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { return SQLExpressionBetween( - expression.qualifiedExpression(with: qualifier), - lowerBound.qualifiedExpression(with: qualifier), - upperBound.qualifiedExpression(with: qualifier), + expression.qualifiedExpression(with: alias), + lowerBound.qualifiedExpression(with: alias), + upperBound.qualifiedExpression(with: alias), negated: isNegated) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionBetween( expression.resolvedExpression(inContext: context), lowerBound.resolvedExpression(inContext: context), @@ -612,19 +611,19 @@ public struct SQLExpressionFunction : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&arguments) } as [String]).joined(separator: ", ") + ")" + public func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return functionName.sql + "(" + (self.arguments.map { $0.expressionSQL(&context) } as [String]).joined(separator: ", ") + ")" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: qualifier) }) + public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionFunction(functionName, arguments: arguments.map { $0.qualifiedExpression(with: alias) }) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionFunction(functionName, arguments: arguments.map { $0.resolvedExpression(inContext: context) }) } } @@ -643,15 +642,15 @@ struct SQLExpressionCount : SQLExpression { self.counted = counted } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "COUNT(" + counted.countedSQL(&arguments) + ")" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "COUNT(" + counted.countedSQL(&context) + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCount(counted.qualifiedSelectable(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCount(counted.qualifiedSelectable(with: alias)) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } @@ -669,19 +668,42 @@ struct SQLExpressionCountDistinct : SQLExpression { self.counted = counted } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "COUNT(DISTINCT " + counted.expressionSQL(&arguments) + ")" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "COUNT(DISTINCT " + counted.expressionSQL(&context) + ")" } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCountDistinct(counted.qualifiedExpression(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCountDistinct(counted.qualifiedExpression(with: alias)) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return self } } +// MARK: - TableMatchExpression + +struct TableMatchExpression: SQLExpression { + var alias: TableAlias + var pattern: SQLExpression + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + context.resolvedName(for: alias).quotedDatabaseIdentifier + " MATCH " + pattern.expressionSQL(&context) + ")" + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return TableMatchExpression( + alias: self.alias, + pattern: pattern.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return TableMatchExpression( + alias: alias, + pattern: pattern.resolvedExpression(inContext: context)) + } +} + // MARK: - SQLExpressionCollate /// SQLExpressionCollate is an expression tainted by an SQLite collation. @@ -697,8 +719,8 @@ struct SQLExpressionCollate : SQLExpression { self.collationName = collationName } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - let sql = expression.expressionSQL(&arguments) + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + let sql = expression.expressionSQL(&context) if sql.last! == ")" { return String(sql.prefix(upTo: sql.index(sql.endIndex, offsetBy: -1))) + " COLLATE " + collationName.rawValue + ")" } else { @@ -706,11 +728,11 @@ struct SQLExpressionCollate : SQLExpression { } } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionCollate(expression.qualifiedExpression(with: qualifier), collationName: collationName) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionCollate(expression.resolvedExpression(inContext: context), collationName: collationName) } } diff --git a/GRDB/QueryInterface/SQLExpression.swift b/GRDB/QueryInterface/SQLExpression.swift index 8f8ddecd1..4d491ebca 100644 --- a/GRDB/QueryInterface/SQLExpression.swift +++ b/GRDB/QueryInterface/SQLExpression.swift @@ -23,22 +23,7 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the expression. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let expression = "foo'bar".databaseValue - /// expression.expressionSQL(&arguments) // "'foo''bar'" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let expression = "foo'bar".databaseValue - /// expression.expressionSQL(&arguments) // "?" - /// arguments // ["foo'bar"] - func expressionSQL(_ arguments: inout StatementArguments?) -> String + func expressionSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// @@ -59,13 +44,13 @@ public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderi /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns the rowIds matched by the expression. - func matchedRowIds(rowIdName: String?) -> Set? // TODO: this method should take SQLTableQualifier in account + func matchedRowIds(rowIdName: String?) -> Set? // FIXME: this method should take TableAlias in account /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression + func qualifiedExpression(with alias: TableAlias) -> SQLExpression /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression } extension SQLExpression { @@ -96,8 +81,8 @@ extension SQLExpression { /// The default implementation returns qualifiedExpression(with:) /// /// :nodoc: - public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return qualifiedExpression(with: qualifier) + public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return qualifiedExpression(with: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) @@ -105,8 +90,8 @@ extension SQLExpression { /// The default implementation returns qualifiedExpression(with:) /// /// :nodoc: - public func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { - return qualifiedExpression(with: qualifier) + public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { + return qualifiedExpression(with: alias) } } @@ -151,19 +136,19 @@ struct SQLExpressionNot : SQLExpression { self.expression = expression } - func expressionSQL(_ arguments: inout StatementArguments?) -> String { - return "NOT \(expression.expressionSQL(&arguments))" + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "NOT \(expression.expressionSQL(&context))" } var negated: SQLExpression { return expression } - func qualifiedExpression(with qualifier: SQLTableQualifier) -> SQLExpression { - return SQLExpressionNot(expression.qualifiedExpression(with: qualifier)) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionNot(expression.qualifiedExpression(with: alias)) } - func resolvedExpression(inContext context: [SQLTableQualifier: PersistenceContainer]) -> SQLExpression { + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { return SQLExpressionNot(expression.resolvedExpression(inContext: context)) } } diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift new file mode 100644 index 000000000..9e8590fa9 --- /dev/null +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -0,0 +1,265 @@ +/// SQLGenerationContext is responsible for preventing SQL injection and +/// disambiguating table names when GRDB generates SQL queries. +public struct SQLGenerationContext { + private(set) var arguments: StatementArguments? + private var resolvedNames: [TableAlias: String] + private var qualifierNeeded: Bool + + /// Used for SQLExpression -> SQLExpressionLiteral conversion + static func literalGenerationContext(withArguments: Bool) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: withArguments ? [] : nil, + resolvedNames: [:], + qualifierNeeded: false) + } + + /// Used for QueryInterfaceQuery.makeSelectStatement() and QueryInterfaceQuery.makeDeleteStatement() + static func queryGenerationContext(aliases: [TableAlias]) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: [], + resolvedNames: aliases.resolvedNames, + qualifierNeeded: aliases.count > 1) + } + + /// Used for TableRecord.selectionSQL + static func recordSelectionGenerationContext(alias: TableAlias) -> SQLGenerationContext { + return SQLGenerationContext( + arguments: nil, + resolvedNames: [:], + qualifierNeeded: true) + } + + /// Returns whether arguments could be appended + mutating func appendArguments(_ newArguments: StatementArguments) -> Bool { + guard let arguments = arguments else { + return false + } + self.arguments = arguments + newArguments + return true + } + + /// May be nil, when a qualifier is not needed: + /// + /// WHERE .column == 1 + /// SELECT .* + /// + /// WHERE column == 1 + /// SELECT * + func qualifier(for alias: TableAlias) -> String? { + if alias.hasUserName { + return alias.identityName + } + if qualifierNeeded == false { + return nil + } + return resolvedName(for: alias) + } + + /// WHERE MATCH pattern + func resolvedName(for alias: TableAlias) -> String { + return resolvedNames[alias.root] ?? alias.identityName + } + + /// FROM tableName + func aliasName(for alias: TableAlias) -> String? { + let resolvedName = self.resolvedName(for: alias) + if resolvedName != alias.tableName { + return resolvedName + } + return nil + } +} + +// MARK: - TableAlias + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +public class TableAlias: Hashable { + private enum Impl { + /// A TableAlias is undefined when it is created by the GRDB user: + /// + /// let alias = TableAlias() + /// let alias = TableAlias(name: "player") + case undefined(userName: String?) + + /// A TableAlias is a table when explicitly specified: + /// + /// let alias = TableAlias(tableName: "player") + /// + /// Or when it has been qualified by a request: + /// + /// let alias = TableAlias() + /// let request = Player.all().aliased(alias) + case table(tableName: String, userName: String?) + case derived(TableAlias) + } + private var impl: Impl + + // exposed for SQLGenerationContext and expression.resolvedExpression + var root: TableAlias { + if case .derived(let base) = impl { + return base.root + } else { + return self + } + } + + // exposed to SQLGenerationContext + fileprivate var identityName: String { + return userName ?? tableName + } + + // exposed to SQLGenerationContext + fileprivate var hasUserName: Bool { + return userName != nil + } + + var tableName: String { + switch impl { + case .undefined: + fatalError("Undefined alias has no table name") + case .table(tableName: let tableName, userName: _): + return tableName + case .derived(let base): + return base.tableName + } + } + + private var userName: String? { + switch impl { + case .undefined(let userName): + return userName + case .table(tableName: _, userName: let userName): + return userName + case .derived(let base): + return base.userName + } + } + + public init(name: String? = nil) { + self.impl = .undefined(userName: name) + } + + init(tableName: String, userName: String? = nil) { + self.impl = .table(tableName: tableName, userName: userName) + } + + func rebase(on base: TableAlias) { + switch impl { + case .undefined(let userName): + if let userName = userName { + // rename + base.setUserName(userName) + } + self.impl = .derived(base) + default: + fatalError("Not implemented") + } + } + + func setUserName(_ userName: String) { + switch impl { + case .undefined: + self.impl = .undefined(userName: userName) + case .table(tableName: let tableName, userName: _): + self.impl = .table(tableName: tableName, userName: userName) + case .derived(let base): + base.setUserName(userName) + } + } + + func setTableName(_ tableName: String) { + switch impl { + case .undefined(let userName): + self.impl = .table(tableName: tableName, userName: userName) + case .table(tableName: let initialTableName, userName: _): + GRDBPrecondition(tableName.lowercased() == initialTableName.lowercased(), "Can't change table name of a table alias") + case .derived(let base): + base.setTableName(tableName) + } + } + + /// Returns a qualified value that is able to resolve ambiguities in + /// joined queries. + public subscript(_ selectable: SQLSelectable) -> SQLSelectable { + return selectable.qualifiedSelectable(with: self) + } + + /// Returns a qualified expression that is able to resolve ambiguities in + /// joined queries. + public subscript(_ expression: SQLExpression) -> SQLExpression { + return expression.qualifiedExpression(with: self) + } + + /// :nodoc: + public var hashValue: Int { + if case .derived(let base) = impl { + return base.hashValue + } else { + return ObjectIdentifier(self).hashValue + } + } + + /// :nodoc: + public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { + return ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) + } +} + +extension Array where Element == TableAlias { + /// Resolve ambiguities in aliases' names. + fileprivate var resolvedNames: [TableAlias: String] { + let aliases = map { $0.root } + + // It is a programmer error to reuse the same (===) TableAlias for + // multiple tables. + GRDBPrecondition(aliases.count == Set(aliases).count, "A TableAlias most not be used to refer to multiple tables") + + let groups = Dictionary.init(grouping: aliases) { + $0.identityName.lowercased() + } + + var uniqueLowercaseNames: Set = [] + var ambiguousGroups: [[TableAlias]] = [] + + for (lowercaseName, group) in groups { + if group.count > 1 { + // It is a programmer error to reuse the same alias for multiple tables + GRDBPrecondition(group.filter({ $0.hasUserName }).count < 2, "ambiguous alias: \(group[0].identityName)") + ambiguousGroups.append(group) + } else { + uniqueLowercaseNames.insert(lowercaseName) + } + } + + var resolvedNames: [TableAlias: String] = [:] + for group in ambiguousGroups { + var index = 1 + for alias in group { + if alias.hasUserName { continue } + let radical = alias.identityName.databaseQualifierRadical + var resolvedName: String + repeat { + resolvedName = "\(radical)\(index)" + index += 1 + } while uniqueLowercaseNames.contains(resolvedName.lowercased()) + uniqueLowercaseNames.insert(resolvedName.lowercased()) + resolvedNames[alias] = resolvedName + } + } + return resolvedNames + } +} + +extension String { + /// "bar" => "bar" + /// "foo12" => "foo" + var databaseQualifierRadical: String { + let digits: ClosedRange = "0"..."9" + let radicalEndIndex = self // "foo12" + .reversed() // "21oof" + .prefix(while: { digits.contains($0) }) // "21" + .endIndex // reversed(foo^12) + .base // foo^12 + return String(prefix(upTo: radicalEndIndex)) + } +} diff --git a/GRDB/QueryInterface/SQLOrdering.swift b/GRDB/QueryInterface/SQLOrdering.swift index fec103e3f..51e944bee 100644 --- a/GRDB/QueryInterface/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQLOrdering.swift @@ -15,25 +15,10 @@ public protocol SQLOrderingTerm { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// /// Returns an SQL string that represents the ordering term. - /// - /// When the arguments parameter is nil, any value must be written down as - /// a literal in the returned SQL: - /// - /// var arguments: StatementArguments? = nil - /// let orderingTerm = Column("name") ?? "Anonymous" - /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, 'Anonymous')" - /// - /// When the arguments parameter is not nil, then values may be replaced by - /// `?` or colon-prefixed tokens, and fed into arguments. - /// - /// var arguments = StatementArguments() - /// let orderingTerm = Column("name") ?? "Anonymous" - /// orderingTerm.orderingTermSQL(&arguments) // "IFNULL(name, ?)" - /// arguments // ["Anonymous"] - func orderingTermSQL(_ arguments: inout StatementArguments?) -> String + func orderingTermSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm + func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm } // MARK: - SQLOrdering @@ -51,21 +36,21 @@ enum SQLOrdering : SQLOrderingTerm { } } - func orderingTermSQL(_ arguments: inout StatementArguments?) -> String { + func orderingTermSQL(_ context: inout SQLGenerationContext) -> String { switch self { case .asc(let expression): - return expression.expressionSQL(&arguments) + " ASC" + return expression.expressionSQL(&context) + " ASC" case .desc(let expression): - return expression.expressionSQL(&arguments) + " DESC" + return expression.expressionSQL(&context) + " DESC" } } - func qualifiedOrdering(with qualifier: SQLTableQualifier) -> SQLOrderingTerm { + func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm { switch self { case .asc(let expression): - return SQLOrdering.asc(expression.qualifiedExpression(with: qualifier)) + return SQLOrdering.asc(expression.qualifiedExpression(with: alias)) case .desc(let expression): - return SQLOrdering.desc(expression.qualifiedExpression(with: qualifier)) + return SQLOrdering.desc(expression.qualifiedExpression(with: alias)) } } } diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 4e5b17664..9c9817244 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -21,13 +21,13 @@ public struct AllColumns { extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { + public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { return "*" } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func countedSQL(_ arguments: inout StatementArguments?) -> String { + public func countedSQL(_ context: inout SQLGenerationContext) -> String { return "*" } @@ -47,14 +47,14 @@ extension AllColumns : SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: - public func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return QualifiedAllColumns(qualifier: qualifier) + public func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return QualifiedAllColumns(alias: alias) } /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func columnCount(_ db: Database) throws -> Int { - fatalError("Can't compute number of columns without a qualifier") + fatalError("Can't compute number of columns without an alias") } } @@ -62,38 +62,40 @@ extension AllColumns : SQLSelectable { /// QualifiedAllColumns is the `t.*` in `SELECT t.*`. struct QualifiedAllColumns { - private let qualifier: SQLTableQualifier + private let alias: TableAlias - init(qualifier: SQLTableQualifier) { - self.qualifier = qualifier + init(alias: TableAlias) { + self.alias = alias } } extension QualifiedAllColumns : SQLSelectable { - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let qualifierName = qualifier.qualifiedName { - return qualifierName.quotedDatabaseIdentifier + ".*" + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + if let qualifier = context.qualifier(for: alias) { + return qualifier.quotedDatabaseIdentifier + ".*" } return "*" } - func countedSQL(_ arguments: inout StatementArguments?) -> String { - // SELECT COUNT(t.*) is invalid SQL - fatalError("Not implemented, or invalid query") + func countedSQL(_ context: inout SQLGenerationContext) -> String { + if context.qualifier(for: alias) != nil { + // SELECT COUNT(t.*) is invalid SQL + fatalError("Not implemented, or invalid query") + } + return "*" } func count(distinct: Bool) -> SQLCount? { return nil } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { // Never requalify return self } func columnCount(_ db: Database) throws -> Int { - assert(qualifier.tableName != nil, "Missing table name") - return try db.columns(in: qualifier.tableName!).count + return try db.columns(in: alias.tableName).count } } @@ -101,27 +103,27 @@ extension QualifiedAllColumns : SQLSelectable { struct SQLAliasedExpression : SQLSelectable { let expression: SQLExpression - let alias: String + let name: String - init(_ expression: SQLExpression, alias: String) { + init(_ expression: SQLExpression, name: String) { self.expression = expression - self.alias = alias + self.name = name } - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - return expression.resultColumnSQL(&arguments) + " AS " + alias.quotedDatabaseIdentifier + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + return expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier } - func countedSQL(_ arguments: inout StatementArguments?) -> String { - return expression.countedSQL(&arguments) + func countedSQL(_ context: inout SQLGenerationContext) -> String { + return expression.countedSQL(&context) } func count(distinct: Bool) -> SQLCount? { return expression.count(distinct: distinct) } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { - return SQLAliasedExpression(expression.qualifiedExpression(with: qualifier), alias: alias) + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { + return SQLAliasedExpression(expression.qualifiedExpression(with: alias), name: name) } func columnCount(_ db: Database) throws -> Int { diff --git a/GRDB/QueryInterface/SQLSelectable.swift b/GRDB/QueryInterface/SQLSelectable.swift index 0c0e48476..bbc0e43a9 100644 --- a/GRDB/QueryInterface/SQLSelectable.swift +++ b/GRDB/QueryInterface/SQLSelectable.swift @@ -8,10 +8,10 @@ /// :nodoc: public protocol SQLSelectable { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func countedSQL(_ arguments: inout StatementArguments?) -> String + func countedSQL(_ context: inout SQLGenerationContext) -> String /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) func count(distinct: Bool) -> SQLCount? @@ -20,7 +20,7 @@ public protocol SQLSelectable { func columnCount(_ db: Database) throws -> Int /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable } // MARK: - SQLSelectionLiteral @@ -34,19 +34,18 @@ struct SQLSelectionLiteral : SQLSelectable { self.arguments = arguments } - func resultColumnSQL(_ arguments: inout StatementArguments?) -> String { - if let literalArguments = self.arguments { - guard arguments != nil else { + func resultColumnSQL(_ context: inout SQLGenerationContext) -> String { + if let arguments = arguments { + if context.appendArguments(arguments) == false { // GRDB limitation: we don't know how to look for `?` in sql and // replace them with with literals. fatalError("Not implemented") } - arguments! += literalArguments } return sql } - func countedSQL(_ arguments: inout StatementArguments?) -> String { + func countedSQL(_ context: inout SQLGenerationContext) -> String { fatalError("Selection literals can't be counted. To resolve this error, select one or several SQLExpressionLiteral instead.") } @@ -58,155 +57,11 @@ struct SQLSelectionLiteral : SQLSelectable { fatalError("Selection literals don't known how many columns they contain. To resolve this error, select one or several SQLExpressionLiteral instead.") } - func qualifiedSelectable(with qualifier: SQLTableQualifier) -> SQLSelectable { + func qualifiedSelectable(with alias: TableAlias) -> SQLSelectable { return self } } -// MARK: - TableAlias - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -public final class TableAlias { - var qualifier: SQLTableQualifier - - public init(name: String? = nil) { - self.qualifier = SQLTableQualifier(tableName: nil, userProvidedAlias: name) - } - - var userProvidedAlias: String? { - get { return qualifier.userProvidedAlias } - set { - // TODO: test - if let value = newValue { - qualifier.alias = value - qualifier.isUserProvided = true - } else { - qualifier.isUserProvided = false - } - } - } - - /// Returns a qualified value that is able to resolve ambiguities in - /// joined queries. - public subscript(_ selectable: SQLSelectable) -> SQLSelectable { - return selectable.qualifiedSelectable(with: qualifier) - } - - /// Returns a qualified expression that is able to resolve ambiguities in - /// joined queries. - public subscript(_ expression: SQLExpression) -> SQLExpression { - return expression.qualifiedExpression(with: qualifier) - } -} - -// MARK: - SQLTableQualifier - -/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) -/// -/// :nodoc: -public class SQLTableQualifier: Hashable { - var tableName: String? - var alias: String? - var isUserProvided: Bool - - init(tableName: String? = nil, userProvidedAlias: String? = nil) { - self.tableName = tableName - self.alias = userProvidedAlias - self.isUserProvided = (userProvidedAlias != nil) - } - - var qualifiedName: String? { - return alias ?? tableName - } - - var userProvidedAlias: String? { - return isUserProvided ? alias : nil - } - - /// :nodoc: - public var hashValue: Int { - return ObjectIdentifier(self).hashValue - } - - /// :nodoc: - public static func == (lhs: SQLTableQualifier, rhs: SQLTableQualifier) -> Bool { - return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) - } -} - -extension Array where Element == SQLTableQualifier { - /// Resolve ambiguities in qualifiers' names. - /// - /// Precondition: all qualifiers have a non-nil qualifiedName: - /// - /// var qualifier = SQLTableQualifier() // nil qualifiedName - /// let query = query.qualified(by: &leftQualifier) - /// // Now qualifier is guaranteed to have a non-nil qualifiedName. - func resolveAmbiguities() { - // Special case - guard let first = first else { - return - } - - // Special case for single qualifier: don't output any column name - if count == 1 { - if !first.isUserProvided { - first.alias = nil - first.tableName = nil - } - return - } - - // It is a programmer error to reuse the same (===) TableAlias for - // multiple tables. - GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") - - // Group qualifiers by lowercase name - let groups = Dictionary.init(grouping: self) { $0.qualifiedName!.lowercased() } - - var uniqueLowercaseNames: Set = [] - var ambiguousGroups: [[SQLTableQualifier]] = [] - - for (lowercaseName, group) in groups { - if group.count > 1 { - // It is a programmer error to reuse the same alias for multiple tables - GRDBPrecondition(group.filter({ $0.isUserProvided }).count < 2, "ambiguous alias: \(group[0].qualifiedName!)") - ambiguousGroups.append(group) - } else { - uniqueLowercaseNames.insert(lowercaseName) - } - } - - for group in ambiguousGroups { - var index = 1 - for qualifier in group { - if qualifier.isUserProvided { continue } - let radical = qualifier.qualifiedName!.databaseQualifierRadical - var alias: String - repeat { - alias = "\(radical)\(index)" - index += 1 - } while uniqueLowercaseNames.contains(alias.lowercased()) - uniqueLowercaseNames.insert(alias.lowercased()) - qualifier.alias = alias - } - } - } -} - -extension String { - /// "foo12" => "foo" - var databaseQualifierRadical: String { - let digits: ClosedRange = "0"..."9" - let radicalEndIndex = self // "foo12" - .reversed() // "21oof" - .prefix(while: { digits.contains($0) }) // "21" - .endIndex // reversed(foo^12) - .base // foo^12 - return String(prefix(upTo: radicalEndIndex)) - } -} - // MARK: - Counting /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift b/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift index ffe8c1735..fd56ad41d 100644 --- a/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSpecificExpressible+QueryInterface.swift @@ -25,8 +25,8 @@ extension SQLSpecificExpressible { /// Returns a value that can be used as an argument to QueryInterfaceRequest.select() /// /// See https://github.com/groue/GRDB.swift/#the-query-interface - public func aliased(_ alias: String) -> SQLSelectable { - return SQLAliasedExpression(sqlExpression, alias: alias) + public func aliased(_ name: String) -> SQLSelectable { + return SQLAliasedExpression(sqlExpression, name: name) } } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index d1c4d424c..b3350f557 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -86,11 +86,11 @@ extension TableRecord { /// // SELECT "p".* FROM players AS p /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" public static func selectionSQL(alias: String? = nil) -> String { - let qualifier = SQLTableQualifier(tableName: databaseTableName, userProvidedAlias: alias) - let selection = databaseSelection.map { $0.qualifiedSelectable(with: qualifier) } - var arguments: StatementArguments? = nil + let alias = TableAlias(tableName: databaseTableName, userName: alias) + let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) } + var context = SQLGenerationContext.recordSelectionGenerationContext(alias: alias) return selection - .map { $0.resultColumnSQL(&arguments) } + .map { $0.resultColumnSQL(&context) } .joined(separator: ", ") } @@ -113,9 +113,9 @@ extension TableRecord { /// try Player.numberOfSelectedColumns(db) /// } public static func numberOfSelectedColumns(_ db: Database) throws -> Int { - let qualifier = SQLTableQualifier(tableName: databaseTableName) + let alias = TableAlias(tableName: databaseTableName) return try databaseSelection - .map { try $0.qualifiedSelectable(with: qualifier).columnCount(db) } + .map { try $0.qualifiedSelectable(with: alias).columnCount(db) } .reduce(0, +) } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 9a083ad0f..c498b799b 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -269,6 +269,10 @@ 5653EBED20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EBEE20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EBEF20961FE800F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; + 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; + 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; + 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -827,8 +831,6 @@ 56F3E74F1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E7641E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; 56F3E7671E67F8C100BF0F01 /* Fixits-0.101.1.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */; }; - 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; - 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; }; 56FEE7FC1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE7FD1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; 56FEE8001F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; }; @@ -980,6 +982,8 @@ 5653EBB120961FE800F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; 5653EBB220961FE800F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; + 5653EC19209873E600F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1168,7 +1172,6 @@ 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = ""; }; 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56F3E7621E67F8C100BF0F01 /* Fixits-0.101.1.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.101.1.swift"; sourceTree = ""; }; - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = ""; }; 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = ""; }; 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = ""; }; @@ -1440,7 +1443,8 @@ 566475991D97D8A000FF74B8 /* SQLCollection.swift */, 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, - 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */, + 5653EC19209873E600F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -2146,6 +2150,7 @@ 566B91141FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 560FC51F1CB003810014AA8E /* CGFloat.swift in Sources */, 5674A7091F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 5653EC17209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, 5659F4A11EA8D997004A4992 /* Result.swift in Sources */, 560FC5201CB003810014AA8E /* Date.swift in Sources */, 560FC5221CB003810014AA8E /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, @@ -2192,7 +2197,6 @@ 5653EB9320961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3411D23E82A00E59934 /* Data.swift in Sources */, 5659F4891EA8D94E004A4992 /* Utils.swift in Sources */, - 56FC98791D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 560FC5361CB003810014AA8E /* DatabaseMigrator.swift in Sources */, 560FC5371CB003810014AA8E /* DatabaseSchemaCache.swift in Sources */, 560FC5381CB003810014AA8E /* DatabaseDateComponents.swift in Sources */, @@ -2215,6 +2219,7 @@ 567071F8208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 560FC53F1CB003810014AA8E /* Row.swift in Sources */, 560FC5401CB003810014AA8E /* StandardLibrary.swift in Sources */, + 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */, 560FC5411CB003810014AA8E /* PersistableRecord.swift in Sources */, 566475A31D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5674A6EA1F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2577,6 +2582,7 @@ 566B91171FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */, 56AFC9F31CB1A8BB00F48B96 /* Database.swift in Sources */, 5674A7061F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */, + 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */, 5659F4A41EA8D997004A4992 /* Result.swift in Sources */, 56AFC9F41CB1A8BB00F48B96 /* CGFloat.swift in Sources */, 56AFC9F51CB1A8BB00F48B96 /* Date.swift in Sources */, @@ -2623,7 +2629,6 @@ 5653EB9420961FC000F46237 /* AssociationQuery.swift in Sources */, 5690C3441D23E82A00E59934 /* Data.swift in Sources */, 5659F48C1EA8D94E004A4992 /* Utils.swift in Sources */, - 56FC987C1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */, 56AFCA0B1CB1A8BB00F48B96 /* Row.swift in Sources */, 56AFCA0C1CB1A8BB00F48B96 /* DatabaseSchemaCache.swift in Sources */, 56AFCA0D1CB1A8BB00F48B96 /* DatabaseDateComponents.swift in Sources */, @@ -2646,6 +2651,7 @@ 56AFCA151CB1A8BB00F48B96 /* PersistableRecord.swift in Sources */, 567071F9208A00D4006AD95A /* SQLiteDateParser.swift in Sources */, 56AFCA161CB1A8BB00F48B96 /* StatementColumnConvertible.swift in Sources */, + 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */, 566475A61D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABD1D107001006283EF /* NSData.swift in Sources */, 5674A6E71F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7f137ab7d..90f2ee9c5 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -97,6 +97,8 @@ 5653EB8120961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */; }; 5653EB8220961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; + 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; + 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -653,6 +655,7 @@ 5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = ""; }; 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; + 5653EC072098737400F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1087,6 +1090,7 @@ 56CEB5411EAA359A00BFAF62 /* SQLExpressible.swift */, 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */, 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */, + 5653EC072098737400F46237 /* SQLGenerationContext.swift */, 56CEB5431EAA359A00BFAF62 /* SQLOrdering.swift */, 56CEB5441EAA359A00BFAF62 /* SQLSelectable.swift */, 566475A11D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift */, @@ -1890,6 +1894,7 @@ F3BA80361CFB28A4003DC1BA /* TableRecord.swift in Sources */, 567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80271CFB2891003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A71D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABE1D107001006283EF /* NSData.swift in Sources */, 5674A6E61F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, @@ -2160,6 +2165,7 @@ F3BA80921CFB2E7A003DC1BA /* TableRecord.swift in Sources */, 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */, F3BA80831CFB2E67003DC1BA /* DatabaseValueConvertible+RawRepresentable.swift in Sources */, + 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */, 566475A41D9810A400FF74B8 /* SQLSelectable+QueryInterface.swift in Sources */, 5657AABB1D107001006283EF /* NSData.swift in Sources */, 5674A6E51F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */, diff --git a/TODO.md b/TODO.md index 6200b7834..56270c5d9 100644 --- a/TODO.md +++ b/TODO.md @@ -28,6 +28,8 @@ GRDB 3.0 - ? - [ ] filter(rowid:), filter(rowids:) - [ ] If required by associations, make reversed() make nothing when there is no alraedy applied ordering +- [ ] Fix matchingRowIds +- [ ] Simplify Range extensions for Swift 4.1 Not sure diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index 5c6625171..dae9e253e 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -71,8 +71,9 @@ class ColumnExpressionTests: GRDBTestCase { // Test FTS3 match expression let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - var arguments: StatementArguments? = nil - XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) } } @@ -132,8 +133,9 @@ class ColumnExpressionTests: GRDBTestCase { // Test FTS3 match expression let expression = try Player.Columns.name.match(FTS3Pattern(rawPattern: "foo")) - var arguments: StatementArguments? = nil - XCTAssertEqual(expression.expressionSQL(&arguments), "(\"name\" MATCH 'foo')") + let literal = expression.literal + XCTAssertEqual(literal.sql, "(\"name\" MATCH ?)") + XCTAssertEqual(literal.arguments, ["foo"]) } } } diff --git a/Tests/GRDBTests/SQLExpressionLiteralTests.swift b/Tests/GRDBTests/SQLExpressionLiteralTests.swift index 2b00e44c6..fff8c41fa 100644 --- a/Tests/GRDBTests/SQLExpressionLiteralTests.swift +++ b/Tests/GRDBTests/SQLExpressionLiteralTests.swift @@ -12,10 +12,10 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var arguments: StatementArguments? = StatementArguments() - let sql = expression.expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: true) + let sql = expression.expressionSQL(&context) XCTAssertEqual(sql, "((\"foo\" = ? COLLATE NOCASE) AND (\"baz\" >= ?))") - let values = arguments!.values + let values = context.arguments!.values XCTAssertEqual(values.count, 2) XCTAssertEqual(values[0], "'fooéı👨👨🏿🇫🇷🇨🇮'".databaseValue) XCTAssertEqual(values[1], 1.databaseValue) @@ -23,8 +23,9 @@ class SQLExpressionLiteralTests: GRDBTestCase { func testWithoutArguments() { let expression = Column("foo").collating(.nocase) == "'fooéı👨👨🏿🇫🇷🇨🇮'" && Column("baz") >= 1 - var arguments: StatementArguments? = nil - let sql = expression.expressionSQL(&arguments) + var context = SQLGenerationContext.literalGenerationContext(withArguments: false) + let sql = expression.expressionSQL(&context) + XCTAssertNil(context.arguments) XCTAssertEqual(sql, "((\"foo\" = '''fooéı👨👨🏿🇫🇷🇨🇮''' COLLATE NOCASE) AND (\"baz\" >= 1))") } } From a3189f79b6e67d777b94baacac1f57409936b100 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 14:52:03 +0200 Subject: [PATCH 211/348] StatementArguments: no more need for internal setters --- GRDB/Core/Statement.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 0bc43bc6c..2c3a6d773 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -588,8 +588,8 @@ extension UpdateStatement: AuthorizedStatement { } /// print(row) /// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"] public struct StatementArguments: CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral { - var values: [DatabaseValue] = [] - var namedValues: [String: DatabaseValue] = [:] + private(set) var values: [DatabaseValue] = [] + private(set) var namedValues: [String: DatabaseValue] = [:] public var isEmpty: Bool { return values.isEmpty && namedValues.isEmpty From 8e2cdeebc3eadf6e6971c1ee992287b05b30a528 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 15:03:36 +0200 Subject: [PATCH 212/348] Cleanup --- .../Association/Association.swift | 21 +++++++++---------- GRDB/QueryInterface/QueryInterfaceQuery.swift | 20 ++++++++---------- .../QueryInterfaceRequest.swift | 4 ++++ 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 6edc0fd32..bd94d6551 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -280,19 +280,18 @@ extension Association where LeftAssociated: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: LeftAssociated) -> QueryInterfaceRequest { + // Turn `JOIN associated ON associated.recordId = record.id` + // into `FROM associated WHERE associated.recordId = 1` let associationAlias = TableAlias() - let query = request.query.qualified(with: associationAlias) let recordAlias = TableAlias(tableName: LeftAssociated.databaseTableName) - - // Turn `associated.recordId = record.id` into `associated.recordId = 1` - let resolvedQuery = query.filter { db in - guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { - fatalError("Can't request from record without join condition") - } - let container = PersistenceContainer(record) // support for record classes: late construction of container - return joinCondition.resolvedExpression(inContext: [recordAlias: container]) + return QueryInterfaceRequest(request) + .aliased(associationAlias) + .filter { db in + guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { + fatalError("Can't request from record without join condition") + } + let container = PersistenceContainer(record) // support for record classes: late construction of container + return joinCondition.resolvedExpression(inContext: [recordAlias: container]) } - - return QueryInterfaceRequest(query: QueryInterfaceQuery(resolvedQuery)) } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 4396a12b4..fb73ba727 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -49,6 +49,15 @@ struct QueryInterfaceQuery { self.joins = joins } + init(_ query: AssociationQuery) { + self.init( + source: query.source, + selection: query.selection, + filterPromise: query.filterPromise, + ordering: query.ordering, + joins: query.joins) + } + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" @@ -393,17 +402,6 @@ extension QueryInterfaceQuery { } } -extension QueryInterfaceQuery { - init(_ query: AssociationQuery) { - self.init( - source: query.source, - selection: query.selection, - filterPromise: query.filterPromise, - ordering: query.ordering, - joins: query.joins) - } -} - // MARK: - AssociationJoin /// Not to be mismatched with SQL join operators (inner join, left join). diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index f1edafcab..e7646ef13 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -7,6 +7,10 @@ public struct QueryInterfaceRequest { init(query: QueryInterfaceQuery) { self.query = query } + + init(_ request: AssociationRequest) { + self.query = QueryInterfaceQuery(request.query) + } } extension QueryInterfaceRequest : FetchRequest { From ffaabdfd627e2f3cc029c3eac8155fe893039b5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 17:20:37 +0200 Subject: [PATCH 213/348] Toward improved DatabaseRegion for joined requests --- GRDB/Core/Database+Schema.swift | 16 +- GRDB/Core/DatabaseSchemaCache.swift | 20 +-- GRDB/QueryInterface/QueryInterfaceQuery.swift | 11 +- .../QueryInterfaceRequest.swift | 4 +- .../SQLExpression+QueryInterface.swift | 141 ++++++++++++------ .../QueryInterface/Support/SQLOperators.swift | 40 ++--- Tests/GRDBTests/DatabaseRegionTests.swift | 35 +++++ 7 files changed, 169 insertions(+), 98 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 7ac80ece1..fe86b618e 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -232,24 +232,24 @@ extension Database { } /// Returns the actual name of the database table - func canonicalName(table: String) throws -> String { - if let canonicalName = schemaCache.canonicalName(table: table) { - return canonicalName + func canonicalTableName(_ tableName: String) throws -> String { + if let canonicalTableName = schemaCache.canonicalTableName(tableName) { + return canonicalTableName } - guard let canonicalName = try String.fetchOne(self, """ + guard let canonicalTableName = try String.fetchOne(self, """ SELECT name FROM ( SELECT name, type FROM sqlite_master UNION SELECT name, type FROM sqlite_temp_master) WHERE type = 'table' AND LOWER(name) = ? - """, arguments: [table.lowercased()]) + """, arguments: [tableName.lowercased()]) else { - throw DatabaseError(message: "no such table: \(table)") + throw DatabaseError(message: "no such table: \(tableName)") } - schemaCache.set(canonicalName: canonicalName, forTable: table) - return canonicalName + schemaCache.set(canonicalTableName: canonicalTableName, forTable: tableName) + return canonicalTableName } } diff --git a/GRDB/Core/DatabaseSchemaCache.swift b/GRDB/Core/DatabaseSchemaCache.swift index 46d57e51c..237db0b97 100644 --- a/GRDB/Core/DatabaseSchemaCache.swift +++ b/GRDB/Core/DatabaseSchemaCache.swift @@ -2,8 +2,8 @@ protocol DatabaseSchemaCache { mutating func clear() - func canonicalName(table: String) -> String? - mutating func set(canonicalName: String, forTable table: String) + func canonicalTableName(_ table: String) -> String? + mutating func set(canonicalTableName: String, forTable table: String) func primaryKey(_ table: String) -> PrimaryKeyInfo? mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) @@ -20,26 +20,26 @@ protocol DatabaseSchemaCache { /// A thread-unsafe database schema cache struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { - private var canonicalNames: [String: String] = [:] + private var canonicalTableNames: [String: String] = [:] private var primaryKeys: [String: PrimaryKeyInfo] = [:] private var columns: [String: [ColumnInfo]] = [:] private var indexes: [String: [IndexInfo]] = [:] private var foreignKeys: [String: [ForeignKeyInfo]] = [:] mutating func clear() { - canonicalNames = [:] + canonicalTableNames = [:] primaryKeys = [:] columns = [:] indexes = [:] foreignKeys = [:] } - func canonicalName(table: String) -> String? { - return canonicalNames[table] + func canonicalTableName(_ table: String) -> String? { + return canonicalTableNames[table] } - mutating func set(canonicalName: String, forTable table: String) { - canonicalNames[table] = table + mutating func set(canonicalTableName: String, forTable table: String) { + canonicalTableNames[table] = table } func primaryKey(_ table: String) -> PrimaryKeyInfo? { @@ -79,8 +79,8 @@ struct SimpleDatabaseSchemaCache: DatabaseSchemaCache { struct EmptyDatabaseSchemaCache: DatabaseSchemaCache { func clear() { } - func canonicalName(table: String) -> String? { return nil } - func set(canonicalName: String, forTable table: String) { } + func canonicalTableName(_ table: String) -> String? { return nil } + func set(canonicalTableName: String, forTable table: String) { } func primaryKey(_ table: String) -> PrimaryKeyInfo? { return nil } func set(primaryKey: PrimaryKeyInfo, forTable table: String) { } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index fb73ba727..2d200afb4 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -186,7 +186,7 @@ struct QueryInterfaceQuery { } extension QueryInterfaceQuery { - private var qualifiedQuery: QueryInterfaceQuery { + var qualifiedQuery: QueryInterfaceQuery { var query = self let alias = TableAlias() @@ -239,9 +239,9 @@ extension QueryInterfaceQuery { return adapter.addingScopes(scopes) } + /// precondition: self is the result of qualifiedQuery func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - let query = qualifiedQuery - return try (query.makeSelectStatement(db), query.rowAdapter(db)) + return try (makeSelectStatement(db), rowAdapter(db)) } func fetchCount(_ db: Database) throws -> Int { @@ -250,6 +250,7 @@ extension QueryInterfaceQuery { } /// The database region that the request looks into. + /// precondition: self is the result of qualifiedQuery func fetchedRegion(_ db: Database) throws -> DatabaseRegion { let statement = try qualifiedQuery.makeSelectStatement(db) let region = statement.fetchedRegion @@ -257,7 +258,7 @@ extension QueryInterfaceQuery { // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table - guard joins.isEmpty, case .table(tableName: let tableName, alias: _) = source else { + guard case .table(tableName: let tableName, alias: _) = source else { // TODO: try harder return region } @@ -279,7 +280,7 @@ extension QueryInterfaceQuery { } // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalName(table: tableName) + let canonicalTableName = try db.canonicalTableName(tableName) return region.tableIntersection(canonicalTableName, rowIds: rowIds) } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index e7646ef13..9ff8518fd 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -23,7 +23,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.prepare(db) + return try query.qualifiedQuery.prepare(db) } /// Returns the number of rows fetched by the request. @@ -39,7 +39,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try query.fetchedRegion(db) + return try query.qualifiedQuery.fetchedRegion(db) } } diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index f17d8f6ae..96b22ad5a 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -292,42 +292,7 @@ public struct SQLExpressionBinary : SQLExpression { return SQLExpressionNot(self) } } - - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) - /// :nodoc: - public func matchedRowIds(rowIdName: String?) -> Set? { - // FIXME: this implementation ignores column aliases - switch op { - case .equal, .is: - // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` - func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set? { - var rowIdNames = [Column.rowID.name.lowercased()] - if let rowIdName = rowIdName { - rowIdNames.append(rowIdName.lowercased()) - } - guard rowIdNames.contains(column.name.lowercased()) else { - return nil - } - if let rowId = Int64.fromDatabaseValue(dbValue) { - return [rowId] - } else { - return [] - } - } - switch (lhs, rhs) { - case (let column as ColumnExpression, let dbValue as DatabaseValue): - return matchedRowIds(column: column, dbValue: dbValue) - case (let dbValue as DatabaseValue, let column as ColumnExpression): - return matchedRowIds(column: column, dbValue: dbValue) - default: - return nil - } - - default: - return nil - } - } - + /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// :nodoc: public func qualifiedExpression(with alias: TableAlias) -> SQLExpression { @@ -425,6 +390,91 @@ struct SQLExpressionOr : SQLExpression { } } +// MARK: - SQLExpressionEqual + +struct SQLExpressionEqual: SQLExpression { + var lhs: SQLExpression + var rhs: SQLExpression + var op: Operator + + init(_ op: Operator, _ lhs: SQLExpression, _ rhs: SQLExpression) { + self.lhs = lhs + self.rhs = rhs + self.op = op + } + + enum Operator: String { + case equal = "=" + case notEqual = "<>" + case `is` = "IS" + case isNot = "IS NOT" + + var negated: Operator { + switch self { + case .equal: return .notEqual + case .notEqual: return .equal + case .is: return .isNot + case .isNot: return .is + } + } + } + + func expressionSQL(_ context: inout SQLGenerationContext) -> String { + return "(" + + lhs.expressionSQL(&context) + + " " + + op.rawValue + + " " + + rhs.expressionSQL(&context) + + ")" + } + + var negated: SQLExpression { + return SQLExpressionEqual(op.negated, lhs, rhs) + } + + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionEqual(op, lhs.qualifiedExpression(with: alias), rhs.qualifiedExpression(with: alias)) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionEqual(op, lhs.resolvedExpression(inContext: context), rhs.resolvedExpression(inContext: context)) + } + + func matchedRowIds(rowIdName: String?) -> Set? { + // FIXME: this implementation ignores column aliases + switch op { + case .equal, .is: + // Look for `id ==/IS 1`, `rowid ==/IS 1`, `1 ==/IS id`, `1 ==/IS rowid` + func matchedRowIds(column: ColumnExpression, dbValue: DatabaseValue) -> Set? { + var rowIdNames = [Column.rowID.name.lowercased()] + if let rowIdName = rowIdName { + rowIdNames.append(rowIdName.lowercased()) + } + guard rowIdNames.contains(column.name.lowercased()) else { + return nil + } + if let rowId = Int64.fromDatabaseValue(dbValue) { + return [rowId] + } else { + return [] + } + } + switch (lhs, rhs) { + case (let column as ColumnExpression, let dbValue as DatabaseValue): + return matchedRowIds(column: column, dbValue: dbValue) + case (let dbValue as DatabaseValue, let column as ColumnExpression): + return matchedRowIds(column: column, dbValue: dbValue) + default: + return nil + } + + case .notEqual, .isNot: + return nil + } + } +} + // MARK: - SQLExpressionContains /// SQLExpressionContains is an expression that checks the inclusion of a @@ -455,7 +505,14 @@ struct SQLExpressionContains : SQLExpression { return SQLExpressionContains(expression, collection, negated: !isNegated) } - /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) + func qualifiedExpression(with alias: TableAlias) -> SQLExpression { + return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) + } + + func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { + return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) + } + func matchedRowIds(rowIdName: String?) -> Set? { // FIXME: this implementation ignores column aliases // Look for `id IN (1, 2, 3)` @@ -469,7 +526,7 @@ struct SQLExpressionContains : SQLExpression { if let rowIdName = rowIdName { rowIdNames.append(rowIdName.lowercased()) } - + guard rowIdNames.contains(column.name.lowercased()) else { return nil } @@ -483,14 +540,6 @@ struct SQLExpressionContains : SQLExpression { } return rowIDs } - - func qualifiedExpression(with alias: TableAlias) -> SQLExpression { - return SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated) - } - - func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { - return SQLExpressionContains(expression.resolvedExpression(inContext: context), collection, negated: isNegated) - } } // MARK: - SQLExpressionBetween diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index f0e8a78db..a333f30b7 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -1,38 +1,24 @@ // MARK: - Egality and Identity Operators (=, <>, IS, IS NOT) -extension SQLBinaryOperator { - /// The `=` binary operator - static let equal = SQLBinaryOperator("=", negated: "<>") - - /// The `<>` binary operator - static let notEqual = SQLBinaryOperator("<>", negated: "=") - - /// The `IS` binary operator - static let `is` = SQLBinaryOperator("IS", negated: "IS NOT") - - /// The `IS NOT` binary operator - static let isNot = SQLBinaryOperator("IS NOT", negated: "IS") -} - // Outputs "x = y" or "x IS NULL" private func isEqual(_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression { switch (lhs, rhs) { case (let lhs, let rhs as DatabaseValue): switch rhs.storage { case .null: - return SQLExpressionBinary(.is, lhs, DatabaseValue.null) + return SQLExpressionEqual(.is, lhs, rhs) default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } case (let lhs as DatabaseValue, let rhs): switch lhs.storage { case .null: - return SQLExpressionBinary(.is, rhs, DatabaseValue.null) + return SQLExpressionEqual(.is, rhs, lhs) default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } default: - return SQLExpressionBinary(.equal, lhs, rhs) + return SQLExpressionEqual(.equal, lhs, rhs) } } @@ -229,7 +215,7 @@ public func != (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL /// // name IS 'Arthur' /// Column("name") === "Arthur" public func === (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS` SQL operator. @@ -246,9 +232,9 @@ public func === (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" === Column("name") public func === (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionBinary(.is, rhs.sqlExpression, DatabaseValue.null) + return SQLExpressionEqual(.is, rhs.sqlExpression, DatabaseValue.null) } } @@ -265,7 +251,7 @@ public func === (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS login /// Column("email") === Column("login") public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.is, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.is, lhs.sqlExpression, rhs.sqlExpression) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -273,7 +259,7 @@ public func === (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ /// // name IS NOT 'Arthur' /// Column("name") !== "Arthur" public func !== (lhs: SQLSpecificExpressible, rhs: SQLExpressible?) -> SQLExpression { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs?.sqlExpression ?? DatabaseValue.null) } /// An SQL expression that compares two expressions with the `IS NOT` SQL operator. @@ -290,9 +276,9 @@ public func !== (lhs: SQLCollatedExpression, rhs: SQLExpressible?) -> SQLExpress /// "Arthur" !== Column("name") public func !== (lhs: SQLExpressible?, rhs: SQLSpecificExpressible) -> SQLExpression { if let lhs = lhs { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } else { - return SQLExpressionBinary(.isNot, rhs.sqlExpression, DatabaseValue.null) + return SQLExpressionEqual(.isNot, rhs.sqlExpression, DatabaseValue.null) } } @@ -309,7 +295,7 @@ public func !== (lhs: SQLExpressible?, rhs: SQLCollatedExpression) -> SQLExpress /// // email IS NOT login /// Column("email") !== Column("login") public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQLExpression { - return SQLExpressionBinary(.isNot, lhs.sqlExpression, rhs.sqlExpression) + return SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression) } diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index bf56708d7..4edded5e1 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -410,6 +410,41 @@ class DatabaseRegionTests : GRDBTestCase { } } + func testDatabaseRegionOfJoinedRequests() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + try db.execute("CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT)") + try db.execute("CREATE TABLE b (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") + try db.execute("CREATE TABLE c (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") + struct A: TableRecord { + static let databaseTableName = "a" + static let b = hasOne(B.self) + static let c = hasMany(C.self) + } + struct B: TableRecord { + static let databaseTableName = "b" + static let a = belongsTo(A.self) + } + struct C: TableRecord { + static let databaseTableName = "c" + } + do { + let request = A.filter(key: 1) + .including(optional: A.b.filter(key: 2)) + .including(optional: A.c.filter(keys: [1, 2, 3])) + // This test will fail when we are able to improve regions of joined requestt + try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)") + } + do { + let request = B.filter(key: 1) + .including(optional: B.a.filter(key: 2) + .including(optional: A.c.filter(keys: [1, 2, 3]))) + // This test will fail when we are able to improve regions of joined requestt + try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") + } + } + } + func testDatabaseRegionOfDerivedRequests() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in From ab36df6e0f108edd1cb6c0a2b79a82de3eb1dfbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 17:42:39 +0200 Subject: [PATCH 214/348] Use "finalized" to describe queries that are ready for SQL generation --- .../Association/AssociationQuery.swift | 123 ++-- GRDB/QueryInterface/QueryInterfaceQuery.swift | 556 +++++++++--------- .../QueryInterfaceRequest.swift | 4 +- 3 files changed, 347 insertions(+), 336 deletions(-) diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index 2f09fdb3c..a89a25361 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -5,67 +5,9 @@ struct AssociationQuery { var ordering: QueryOrdering var joins: [AssociationJoin] - var qualifiedQuery: AssociationQuery { - var query = self - - let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - query.ordering = ordering.qualified(with: alias) - query.joins = joins.map { $0.qualifiedJoin } - - return query - } - var alias: TableAlias? { return source.alias } - - var allAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.allAliases) - } - } - - var completeSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.completeSelection) - } - } - - var completeOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.completeOrdering) - } - } - - func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = startIndex + selectionWidth - var scopes: [String: RowAdapter] = [:] - for join in joins { - if let (joinAdapter, joinEndIndex) = try join.rowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { - GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") - scopes[join.key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) - return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) - } } extension AssociationQuery { @@ -129,3 +71,68 @@ extension AssociationQuery { return query } } + +extension AssociationQuery { + /// A finalized query is ready for SQL generation + var finalizedQuery: AssociationQuery { + var query = self + + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.ordering = ordering.qualified(with: alias) + query.joins = joins.map { $0.finalizedJoin } + + return query + } + + /// precondition: self is the result of finalizedQuery + var finalizedAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) + } + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.finalizedAliases) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.finalizedSelection) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.finalizedOrdering) + } + } + + /// precondition: self is the result of finalizedQuery + func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = startIndex + selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: keyPath + [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\((keyPath + [join.key]).joined(separator: "."))\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(startIndex ..< (startIndex + selectionWidth)) + return (adapter: adapter.addingScopes(scopes), endIndex: endIndex) + } +} diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 2d200afb4..dcb675dec 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -58,275 +58,9 @@ struct QueryInterfaceQuery { joins: query.joins) } - func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { - var sql = "SELECT" - - if isDistinct { - sql += " DISTINCT" - } - - let selection = completeSelection - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") - - sql += try " FROM " + source.sourceSQL(db, &context) - - for join in joins { - sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) - } - - if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if !groupByExpressions.isEmpty { - sql += " GROUP BY " - sql += groupByExpressions.map { $0.expressionSQL(&context) } - .joined(separator: ", ") - } - - if let havingExpression = havingExpression { - sql += " HAVING " + havingExpression.expressionSQL(&context) - } - - let orderings = completeOrdering.resolve() - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if let limit = limit { - sql += " LIMIT " + limit.sql - } - - return sql - } - - /// precondition: self is the result of qualifiedQuery - func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { - guard groupByExpressions.isEmpty else { - // Programmer error - fatalError("Can't delete query with GROUP BY clause") - } - - guard havingExpression == nil else { - // Programmer error - fatalError("Can't delete query with HAVING clause") - } - - guard joins.isEmpty else { - // Programmer error - fatalError("Can't delete query with JOIN clause") - } - - guard case .table = source else { - // Programmer error - fatalError("Can't delete without any database table") - } - - var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases) - - var sql = try "DELETE FROM " + source.sourceSQL(db, &context) - - if let filter = try filterPromise.resolve(db) { - sql += " WHERE " + filter.expressionSQL(&context) - } - - if let limit = limit { - let orderings = self.completeOrdering.resolve() - if !orderings.isEmpty { - sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") - } - - if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { - sql += " LIMIT " + limit.sql - } else { - fatalError("Can't delete query with limit") - } - } - - let statement = try db.makeUpdateStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// Remove ordering - var unorderedQuery: QueryInterfaceQuery { - var query = self - query.ordering = QueryOrdering() - return query - } - - // MARK: Join Support - var alias: TableAlias? { return source.alias } - - var allAliases: [TableAlias] { - var aliases: [TableAlias] = [] - if let alias = alias { - aliases.append(alias) - } - return joins.reduce(into: aliases) { - $0.append(contentsOf: $1.allAliases) - } - } - - var completeSelection: [SQLSelectable] { - return joins.reduce(into: selection) { - $0.append(contentsOf: $1.completeSelection) - } - } - - var completeOrdering: QueryOrdering { - return joins.reduce(ordering) { - $0.appending($1.completeOrdering) - } - } -} - -extension QueryInterfaceQuery { - var qualifiedQuery: QueryInterfaceQuery { - var query = self - - let alias = TableAlias() - query.source = source.qualified(with: alias) - query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } - query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } - query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) } - query.ordering = query.ordering.qualified(with: alias) - query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) - - query.joins = query.joins.map { $0.qualifiedJoin } - - return query - } - - /// precondition: self is the result of qualifiedQuery - private func makeSelectStatement(_ db: Database) throws -> SelectStatement { - var context = SQLGenerationContext.queryGenerationContext(aliases: allAliases) - let sql = try self.sql(db, &context) - let statement = try db.makeSelectStatement(sql) - statement.arguments = context.arguments! - return statement - } - - /// precondition: self is the result of qualifiedQuery - private func rowAdapter(_ db: Database) throws -> RowAdapter? { - if joins.isEmpty { - return nil - } - - let selectionWidth = try selection - .map { try $0.columnCount(db) } - .reduce(0, +) - - var endIndex = selectionWidth - var scopes: [String: RowAdapter] = [:] - for join in joins { - if let (joinAdapter, joinEndIndex) = try join.rowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { - GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") - scopes[join.key] = joinAdapter - endIndex = joinEndIndex - } - } - - if selectionWidth == 0 && scopes.isEmpty { - return nil - } - - let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) - return adapter.addingScopes(scopes) - } - - /// precondition: self is the result of qualifiedQuery - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try (makeSelectStatement(db), rowAdapter(db)) - } - - func fetchCount(_ db: Database) throws -> Int { - let (statement, adapter) = try countQuery.prepare(db) - return try Int.fetchOne(statement, adapter: adapter)! - } - - /// The database region that the request looks into. - /// precondition: self is the result of qualifiedQuery - func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let statement = try qualifiedQuery.makeSelectStatement(db) - let region = statement.fetchedRegion - - // Can we intersect the region with rowIds? - // - // Give up unless request feeds from a single database table - guard case .table(tableName: let tableName, alias: _) = source else { - // TODO: try harder - return region - } - - // Give up unless primary key is rowId - let primaryKeyInfo = try db.primaryKey(tableName) - guard primaryKeyInfo.isRowID else { - return region - } - - // Give up unless there is a where clause - guard let filter = try filterPromise.resolve(db) else { - return region - } - - // The filter knows better - guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return region - } - - // Database regions are case-insensitive: use the canonical table name - let canonicalTableName = try db.canonicalTableName(tableName) - return region.tableIntersection(canonicalTableName, rowIds: rowIds) - } - - private var countQuery: QueryInterfaceQuery { - guard groupByExpressions.isEmpty && limit == nil else { - // SELECT ... GROUP BY ... - // SELECT ... LIMIT ... - return trivialCountQuery - } - - guard joins.isEmpty, case .table = source else { - // SELECT ... FROM (something which is not a plain table) - return trivialCountQuery - } - - GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") - if selection.count == 1 { - guard let count = self.selection[0].count(distinct: isDistinct) else { - return trivialCountQuery - } - var countQuery = unorderedQuery - countQuery.isDistinct = false - countQuery.selection = [count.sqlSelectable] - return countQuery - } else { - // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... - - guard !isDistinct else { - return trivialCountQuery - } - - // SELECT expr1, expr2, ... FROM tableName ... - // -> - // SELECT COUNT(*) FROM tableName ... - var countQuery = unorderedQuery - countQuery.selection = [SQLExpressionCount(AllColumns())] - return countQuery - } - } - - // SELECT COUNT(*) FROM (self) - private var trivialCountQuery: QueryInterfaceQuery { - return QueryInterfaceQuery( - source: .query(unorderedQuery), - selection: [SQLExpressionCount(AllColumns())]) - } } extension QueryInterfaceQuery { @@ -384,6 +118,12 @@ extension QueryInterfaceQuery { return query } + func unordered() -> QueryInterfaceQuery { + var query = self + query.ordering = QueryOrdering() + return query + } + func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceQuery { var query = self query.limit = SQLLimit(limit: limit, offset: offset) @@ -403,6 +143,269 @@ extension QueryInterfaceQuery { } } +extension QueryInterfaceQuery { + /// A finalized query is ready for SQL generation + var finalizedQuery: QueryInterfaceQuery { + var query = self + + let alias = TableAlias() + query.source = source.qualified(with: alias) + query.selection = query.selection.map { $0.qualifiedSelectable(with: alias) } + query.filterPromise = query.filterPromise.map { [alias] (_, expr) in expr?.qualifiedExpression(with: alias) } + query.groupByExpressions = query.groupByExpressions.map { $0.qualifiedExpression(with: alias) } + query.ordering = query.ordering.qualified(with: alias) + query.havingExpression = query.havingExpression?.qualifiedExpression(with: alias) + + query.joins = query.joins.map { $0.finalizedJoin } + + return query + } + + /// precondition: self is the result of finalizedQuery + var finalizedAliases: [TableAlias] { + var aliases: [TableAlias] = [] + if let alias = alias { + aliases.append(alias) + } + return joins.reduce(into: aliases) { + $0.append(contentsOf: $1.finalizedAliases) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedSelection: [SQLSelectable] { + return joins.reduce(into: selection) { + $0.append(contentsOf: $1.finalizedSelection) + } + } + + /// precondition: self is the result of finalizedQuery + var finalizedOrdering: QueryOrdering { + return joins.reduce(ordering) { + $0.appending($1.finalizedOrdering) + } + } + + /// precondition: self is the result of finalizedQuery + private func finalizedRowAdapter(_ db: Database) throws -> RowAdapter? { + if joins.isEmpty { + return nil + } + + let selectionWidth = try selection + .map { try $0.columnCount(db) } + .reduce(0, +) + + var endIndex = selectionWidth + var scopes: [String: RowAdapter] = [:] + for join in joins { + if let (joinAdapter, joinEndIndex) = try join.finalizedRowAdapter(db, fromIndex: endIndex, forKeyPath: [join.key]) { + GRDBPrecondition(scopes[join.key] == nil, "The association key \"\(join.key)\" is ambiguous. Use the Association.forKey(_:) method is order to disambiguate.") + scopes[join.key] = joinAdapter + endIndex = joinEndIndex + } + } + + if selectionWidth == 0 && scopes.isEmpty { + return nil + } + + let adapter = RangeRowAdapter(0 ..< (0 + selectionWidth)) + return adapter.addingScopes(scopes) + } +} + +extension QueryInterfaceQuery { + func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { + var sql = "SELECT" + + if isDistinct { + sql += " DISTINCT" + } + + let selection = finalizedSelection + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ") + + sql += try " FROM " + source.sourceSQL(db, &context) + + for join in joins { + sql += try " " + join.joinSQL(db, &context, leftAlias: alias!, isRequiredAllowed: true) + } + + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if !groupByExpressions.isEmpty { + sql += " GROUP BY " + sql += groupByExpressions.map { $0.expressionSQL(&context) } + .joined(separator: ", ") + } + + if let havingExpression = havingExpression { + sql += " HAVING " + havingExpression.expressionSQL(&context) + } + + let orderings = finalizedOrdering.resolve() + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if let limit = limit { + sql += " LIMIT " + limit.sql + } + + return sql + } + + /// precondition: self is the result of finalizedQuery + private func makeSelectStatement(_ db: Database) throws -> SelectStatement { + var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + let sql = try self.sql(db, &context) + let statement = try db.makeSelectStatement(sql) + statement.arguments = context.arguments! + return statement + } + + /// precondition: self is the result of finalizedQuery + func makeDeleteStatement(_ db: Database) throws -> UpdateStatement { + guard groupByExpressions.isEmpty else { + // Programmer error + fatalError("Can't delete query with GROUP BY clause") + } + + guard havingExpression == nil else { + // Programmer error + fatalError("Can't delete query with HAVING clause") + } + + guard joins.isEmpty else { + // Programmer error + fatalError("Can't delete query with JOIN clause") + } + + guard case .table = source else { + // Programmer error + fatalError("Can't delete without any database table") + } + + var context = SQLGenerationContext.queryGenerationContext(aliases: finalizedAliases) + + var sql = try "DELETE FROM " + source.sourceSQL(db, &context) + + if let filter = try filterPromise.resolve(db) { + sql += " WHERE " + filter.expressionSQL(&context) + } + + if let limit = limit { + let orderings = finalizedOrdering.resolve() + if !orderings.isEmpty { + sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") + } + + if Database.sqliteCompileOptions.contains("ENABLE_UPDATE_DELETE_LIMIT") { + sql += " LIMIT " + limit.sql + } else { + fatalError("Can't delete query with limit") + } + } + + let statement = try db.makeUpdateStatement(sql) + statement.arguments = context.arguments! + return statement + } + + /// precondition: self is the result of finalizedQuery + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { + return try (makeSelectStatement(db), finalizedRowAdapter(db)) + } + + func fetchCount(_ db: Database) throws -> Int { + let (statement, adapter) = try countQuery.prepare(db) + return try Int.fetchOne(statement, adapter: adapter)! + } + + /// The database region that the request looks into. + /// precondition: self is the result of finalizedQuery + func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + let statement = try makeSelectStatement(db) + let region = statement.fetchedRegion + + // Can we intersect the region with rowIds? + // + // Give up unless request feeds from a single database table + guard case .table(tableName: let tableName, alias: _) = source else { + // TODO: try harder + return region + } + + // Give up unless primary key is rowId + let primaryKeyInfo = try db.primaryKey(tableName) + guard primaryKeyInfo.isRowID else { + return region + } + + // Give up unless there is a where clause + guard let filter = try filterPromise.resolve(db) else { + return region + } + + // The filter knows better + guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { + return region + } + + // Database regions are case-insensitive: use the canonical table name + let canonicalTableName = try db.canonicalTableName(tableName) + return region.tableIntersection(canonicalTableName, rowIds: rowIds) + } + + private var countQuery: QueryInterfaceQuery { + guard groupByExpressions.isEmpty && limit == nil else { + // SELECT ... GROUP BY ... + // SELECT ... LIMIT ... + return trivialCountQuery + } + + guard joins.isEmpty, case .table = source else { + // SELECT ... FROM (something which is not a plain table) + return trivialCountQuery + } + + GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection") + if selection.count == 1 { + guard let count = self.selection[0].count(distinct: isDistinct) else { + return trivialCountQuery + } + var countQuery = self.unordered() + countQuery.isDistinct = false + countQuery.selection = [count.sqlSelectable] + return countQuery + } else { + // SELECT [DISTINCT] expr1, expr2, ... FROM tableName ... + + guard !isDistinct else { + return trivialCountQuery + } + + // SELECT expr1, expr2, ... FROM tableName ... + // -> + // SELECT COUNT(*) FROM tableName ... + var countQuery = self.unordered() + countQuery.selection = [SQLExpressionCount(AllColumns())] + return countQuery + } + } + + // SELECT COUNT(*) FROM (self) + private var trivialCountQuery: QueryInterfaceQuery { + return QueryInterfaceQuery( + source: .query(unordered()), + selection: [SQLExpressionCount(AllColumns())]) + } +} + // MARK: - AssociationJoin /// Not to be mismatched with SQL join operators (inner join, left join). @@ -458,28 +461,29 @@ struct AssociationJoin { var key: String var joinConditionPromise: DatabasePromise - var qualifiedJoin: AssociationJoin { + var finalizedJoin: AssociationJoin { var join = self - join.query = query.qualifiedQuery + join.query = query.finalizedQuery return join } - var allAliases: [TableAlias] { - return query.allAliases + var finalizedAliases: [TableAlias] { + return query.finalizedAliases } - var completeSelection: [SQLSelectable] { - return query.completeSelection + var finalizedSelection: [SQLSelectable] { + return query.finalizedSelection } - var completeOrdering: QueryOrdering { - return query.completeOrdering + var finalizedOrdering: QueryOrdering { + return query.finalizedOrdering } - func rowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { - return try query.rowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) + func finalizedRowAdapter(_ db: Database, fromIndex startIndex: Int, forKeyPath keyPath: [String]) throws -> (adapter: RowAdapter, endIndex: Int)? { + return try query.finalizedRowAdapter(db, fromIndex: startIndex, forKeyPath: keyPath) } + /// precondition: query is the result of finalizedQuery func joinSQL(_ db: Database,_ context: inout SQLGenerationContext, leftAlias: TableAlias, isRequiredAllowed: Bool) throws -> String { var isRequiredAllowed = isRequiredAllowed var sql = "" diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 9ff8518fd..9cfa76eb5 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -23,7 +23,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - returns: A prepared statement and an eventual row adapter. /// :nodoc: public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) { - return try query.qualifiedQuery.prepare(db) + return try query.finalizedQuery.prepare(db) } /// Returns the number of rows fetched by the request. @@ -39,7 +39,7 @@ extension QueryInterfaceRequest : FetchRequest { /// - parameter db: A database connection. /// :nodoc: public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try query.qualifiedQuery.fetchedRegion(db) + return try query.finalizedQuery.fetchedRegion(db) } } From 872d6d21accd10defcbacc2d3669d107aa321337 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 19:01:45 +0200 Subject: [PATCH 215/348] Update README.md with singular table names --- README.md | 698 +++++++++++++++++++++++++++--------------------------- 1 file changed, 347 insertions(+), 351 deletions(-) diff --git a/README.md b/README.md index 7012dd79e..de4dc8e02 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)]( | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4.1** | **v3.0.0** | +| **Swift 4.1** | **v3.0.0** | | Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | @@ -97,7 +97,7 @@ See [Database Connections](#database-connections) ```swift try dbQueue.write { db in try db.execute(""" - CREATE TABLE places ( + CREATE TABLE place ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, favorite BOOLEAN NOT NULL DEFAULT 0, @@ -106,7 +106,7 @@ try dbQueue.write { db in """) try db.execute(""" - INSERT INTO places (title, favorite, latitude, longitude) + INSERT INTO place (title, favorite, latitude, longitude) VALUES (?, ?, ?, ?) """, arguments: ["Paris", true, 48.85341, 2.3488]) @@ -124,7 +124,7 @@ See [Executing Updates](#executing-updates) ```swift try dbQueue.read { db in // Fetch database rows - let rows = try Row.fetchCursor(db, "SELECT * FROM places") + let rows = try Row.fetchCursor(db, "SELECT * FROM place") while let row = try rows.next() { let title: String = row["title"] let isFavorite: Bool = row["favorite"] @@ -134,12 +134,12 @@ try dbQueue.read { db in } // Fetch values - let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! // Int - let placeTitles = try String.fetchAll(db, "SELECT title FROM places") // [String] + let placeCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! // Int + let placeTitles = try String.fetchAll(db, "SELECT title FROM place") // [String] } let placeCount = try dbQueue.read { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM places")! + try Int.fetchOne(db, "SELECT COUNT(*) FROM place")! } ``` @@ -163,7 +163,7 @@ struct Place { try dbQueue.write { db in // Create database table - try db.create(table: "places") { t in + try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) @@ -210,7 +210,7 @@ try dbQueue.write { db in let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) // SQL is always welcome - let places = try Place.fetchAll(db, "SELECT * FROM places") + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` @@ -231,7 +231,7 @@ Place.filter(key: 1) }) // Track SQL requests -SQLRequest("SELECT * FROM places WHERE favorite ORDER BY title") +SQLRequest("SELECT * FROM place WHERE favorite ORDER BY title") .rx .fetchAll(in: dbQueue) .subscribe(onNext: { places: [Place] in @@ -390,7 +390,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Modify the database: try dbQueue.write { db in - try db.create(table: "places") { ... } + try db.create(table: "place") { ... } try Place(...).insert(db) } @@ -460,7 +460,7 @@ SQLite creates the database file if it does not already exist. The connection is ```swift // Modify the database: try dbPool.write { db in - try db.create(table: "places") { ... } + try db.create(table: "place") { ... } try Place(...).insert(db) } @@ -566,20 +566,20 @@ For example: ```swift try dbQueue.write { db in try db.execute(""" - CREATE TABLE players ( + CREATE TABLE player ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, score INT) """) try db.execute( - "INSERT INTO players (name, score) VALUES (:name, :score)", + "INSERT INTO player (name, score) VALUES (:name, :score)", arguments: ["name": "Barbara", "score": 1000]) // Join multiple statements with a semicolon: try db.execute(""" - INSERT INTO players (name, score) VALUES (?, ?); - INSERT INTO players (name, score) VALUES (?, ?) + INSERT INTO player (name, score) VALUES (?, ?); + INSERT INTO player (name, score) VALUES (?, ?) """, arguments: ["Arthur", 750, "Barbara", 1000]) } ``` @@ -592,7 +592,7 @@ Never ever embed values directly in your SQL strings, and always use arguments i ```swift try db.execute( - "INSERT INTO players (name, score) VALUES (?, ?)", + "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000]) let playerId = db.lastInsertedRowID ``` @@ -614,7 +614,7 @@ let playerId = player.id ```swift try dbQueue.read { db in - if let row = try Row.fetchOne(db, "SELECT * FROM wines WHERE id = ?", arguments: [1]) { + if let row = try Row.fetchOne(db, "SELECT * FROM wine WHERE id = ?", arguments: [1]) { let name: String = row["name"] let color: Color = row["color"] print(name, color) @@ -627,7 +627,7 @@ try dbQueue.read { db in ```swift try dbQueue.read { db in - let urls = try URL.fetchCursor(db, "SELECT url FROM wines") + let urls = try URL.fetchCursor(db, "SELECT url FROM wine") while let url = try urls.next() { print(url) } @@ -639,7 +639,7 @@ try dbQueue.read { db in ```swift let wines = try dbQueue.read { db in - try Wine.fetchAll(db, "SELECT * FROM wines") + try Wine.fetchAll(db, "SELECT * FROM wine") } ``` @@ -744,24 +744,24 @@ If you don't see, or don't care about the difference, use arrays. If you care ab ```swift // All URL hosts let hosts = try URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .map { url in url.host } // Prints all Github links try URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .filter { url in url.host == "github.com" } .forEach { url in print(url) } // Turn a cursor into an array: let cursor = URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .filter { url in url.host == "github.com" } let githubURLs = try Array(cursor) // [URL] // Turn a cursor into a set: let cursor = URL - .fetchCursor(db, "SELECT url FROM links") + .fetchCursor(db, "SELECT url FROM link") .flatMap { url in url.host } let hosts = try Set(cursor) // Set ``` @@ -787,7 +787,7 @@ try dbQueue.read { db in try Row.fetchAll(db, "SELECT ...", arguments: ...) // [Row] try Row.fetchOne(db, "SELECT ...", arguments: ...) // Row? - let rows = try Row.fetchCursor(db, "SELECT * FROM wines") + let rows = try Row.fetchCursor(db, "SELECT * FROM wine") while let row = try rows.next() { let name: String = row["name"] let color: Color = row["color"] @@ -796,7 +796,7 @@ try dbQueue.read { db in } let rows = try dbQueue.read { db in - try Row.fetchAll(db, "SELECT * FROM players") + try Row.fetchAll(db, "SELECT * FROM player") } ``` @@ -804,11 +804,11 @@ Arguments are optional arrays or dictionaries that fill the positional `?` and c ```swift let rows = try Row.fetchAll(db, - "SELECT * FROM players WHERE name = ?", + "SELECT * FROM player WHERE name = ?", arguments: ["Arthur"]) let rows = try Row.fetchAll(db, - "SELECT * FROM players WHERE name = :name", + "SELECT * FROM player WHERE name = :name", arguments: ["name": "Arthur"]) ``` @@ -1053,7 +1053,7 @@ try dbQueue.read { db in } let playerCount = try dbQueue.read { db in - try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! } ``` @@ -1062,8 +1062,8 @@ let playerCount = try dbQueue.read { db in There are many supported value types (Bool, Int, String, Date, Swift enums, etc.). See [Values](#values) for more information: ```swift -let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! // Int -let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL] +let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! // Int +let urls = try URL.fetchAll(db, "SELECT url FROM link") // [URL] ``` @@ -1089,14 +1089,14 @@ Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/do let url: URL = ... let verified: Bool = ... try db.execute( - "INSERT INTO links (url, verified) VALUES (?, ?)", + "INSERT INTO link (url, verified) VALUES (?, ?)", arguments: [url, verified]) ``` Values can be [extracted from rows](#column-values): ```swift -let rows = try Row.fetchCursor(db, "SELECT * FROM links") +let rows = try Row.fetchCursor(db, "SELECT * FROM link") while let row = try rows.next() { let url: URL = row["url"] let verified: Bool = row["verified"] @@ -1106,7 +1106,7 @@ while let row = try rows.next() { Values can be [directly fetched](#value-queries): ```swift -let urls = try URL.fetchAll(db, "SELECT url FROM links") // [URL] +let urls = try URL.fetchAll(db, "SELECT url FROM link") // [URL] ``` Use values in [Records](#records): @@ -1193,7 +1193,7 @@ Here is the support provided by GRDB for the various [date formats](https://www. ```swift try db.execute( - "INSERT INTO players (creationDate, ...) VALUES (?, ...)", + "INSERT INTO player (creationDate, ...) VALUES (?, ...)", arguments: [Date(), ...]) let creationDate: Date = row["creationDate"] @@ -1228,7 +1228,7 @@ components.day = 18 // Store "1973-09-18" let dbComponents = DatabaseDateComponents(components, format: .YMD) try db.execute( - "INSERT INTO players (birthDate, ...) VALUES (?, ...)", + "INSERT INTO player (birthDate, ...) VALUES (?, ...)", arguments: [dbComponents, ...]) // Read "1973-09-18" @@ -1248,7 +1248,7 @@ NSDecimalNumber deserves a longer discussion: **SQLite has no support for decimal numbers.** Given the table below, SQLite will actually store integers or doubles: ```sql -CREATE TABLE transfers ( +CREATE TABLE transfer ( amount DECIMAL(10,5) -- will store integer or double, actually ) ``` @@ -1256,9 +1256,9 @@ CREATE TABLE transfers ( This means that computations will not be exact: ```swift -try db.execute("INSERT INTO transfers (amount) VALUES (0.1)") -try db.execute("INSERT INTO transfers (amount) VALUES (0.2)") -let sum = try NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfers")! +try db.execute("INSERT INTO transfer (amount) VALUES (0.1)") +try db.execute("INSERT INTO transfer (amount) VALUES (0.2)") +let sum = try NSDecimalNumber.fetchOne(db, "SELECT SUM(amount) FROM transfer")! // Yikes! 0.3000000000000000512 print(sum) @@ -1269,14 +1269,14 @@ Don't blame SQLite or GRDB, and instead store your decimal numbers differently. A classic technique is to store *integers* instead, since SQLite performs exact computations of integers. For example, don't store Euros, but store cents instead: ```swift -// Store -let amount = NSDecimalNumber(string: "0.1") // 0.1 -let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value // 100 -try db.execute("INSERT INTO transfers (amount) VALUES (?)", arguments: [integerAmount]) +// Write +let amount = NSDecimalNumber(string: "0.10") +let integerAmount = amount.multiplying(byPowerOf10: 2).int64Value +try db.execute("INSERT INTO transfer (amount) VALUES (?)", arguments: [integerAmount]) // Read -let integerAmount = try Int64.fetchOne(db, "SELECT SUM(amount) FROM transfers")! // 100 -let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.1 +let integerAmount = try Int64.fetchOne(db, "SELECT SUM(amount) FROM transfer")! +let amount = NSDecimalNumber(value: integerAmount).multiplying(byPowerOf10: -2) // 0.10 ``` @@ -1304,11 +1304,11 @@ extension Grape : DatabaseValueConvertible { } // Store try db.execute( - "INSERT INTO wines (grape, color) VALUES (?, ?)", + "INSERT INTO wine (grape, color) VALUES (?, ?)", arguments: [Grape.merlot, Color.red]) // Read -let rows = try Row.fetchCursor(db, "SELECT * FROM wines") +let rows = try Row.fetchCursor(db, "SELECT * FROM wine") while let row = try rows.next() { let grape: Grape = row["grape"] let color: Color = row["color"] @@ -1343,8 +1343,8 @@ GRDB generally opens transactions for you, as a way to enforce its [concurrency ```swift // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.write { db in try Credit(destinationAccout, amount).insert(db) @@ -1352,8 +1352,8 @@ try dbQueue.write { db in } // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbPool.write { db in try Credit(destinationAccout, amount).insert(db) @@ -1369,15 +1369,15 @@ Yet you may need to exactly control when transactions take place: `DatabaseQueue.inDatabase()` and `DatabasePool.writeWithoutTransaction()` execute your database statements outside of any transaction: ```swift -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... try dbQueue.inDatabase { db in try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) } -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... try dbPool.writeWithoutTransaction { db in try Credit(destinationAccout, amount).insert(db) try Debit(sourceAccount, amount).insert(db) @@ -1401,8 +1401,8 @@ To open explicit transactions, use one of the `Database.inTransaction`, `Databas ```swift // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction try db.inTransaction { @@ -1413,8 +1413,8 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } // BEGIN TRANSACTION -// INSERT INTO credits ... -// INSERT INTO debits ... +// INSERT INTO credit ... +// INSERT INTO debit ... // COMMIT try dbQueue.inTransaction { db in // or dbPool.writeInTransaction try Credit(destinationAccout, amount).insert(db) @@ -1566,10 +1566,10 @@ There are two kinds of prepared statements: **select statements**, and **update ```swift try dbQueue.write { db in - let updateSQL = "INSERT INTO players (name, score) VALUES (:name, :score)" + let updateSQL = "INSERT INTO player (name, score) VALUES (:name, :score)" let updateStatement = try db.makeUpdateStatement(updateSQL) - let selectSQL = "SELECT * FROM players WHERE name = ?" + let selectSQL = "SELECT * FROM player WHERE name = ?" let selectStatement = try db.makeSelectStatement(selectSQL) } ``` @@ -1632,8 +1632,8 @@ Should a cached prepared statement throw an error, don't reuse it (it is a progr A custom SQL function or aggregate extends SQLite: ```sql -SELECT reverse(name) FROM players; -- custom function -SELECT maxLength(name) FROM players; -- custom aggregate +SELECT reverse(name) FROM player; -- custom function +SELECT maxLength(name) FROM player; -- custom aggregate ``` - [Custom SQL Functions](#custom-sql-functions) @@ -1706,7 +1706,7 @@ try dbQueue.read { db in **Use custom functions in the [query interface](#the-query-interface):** ```swift -// SELECT reverseString("name") FROM players +// SELECT reverseString("name") FROM player Player.select(reverseString.apply(nameColumn)) ``` @@ -1764,7 +1764,7 @@ dbQueue.add(function: maxLength) // Or dbPool.add(function: ...) try dbQueue.read { db in // Some Int - try Int.fetchOne(db, "SELECT maxLength(name) FROM players")! + try Int.fetchOne(db, "SELECT maxLength(name) FROM player")! } ``` @@ -1778,7 +1778,7 @@ SQLite has the opportunity to perform additional optimizations when aggregates a **Use custom aggregates in the [query interface](#the-query-interface):** ```swift -// SELECT maxLength("name") FROM players +// SELECT maxLength("name") FROM player Int.fetchOne(db, Player.select(maxLength.apply(nameColumn))) // Int? ``` @@ -1790,22 +1790,22 @@ GRDB comes with a set of schema introspection methods: ```swift try dbQueue.read { db in // Bool, true if the table exists - try db.tableExists("players") + try db.tableExists("player") // [ColumnInfo], the columns in the table - try db.columns(in: "players") + try db.columns(in: "player") // PrimaryKeyInfo - try db.primaryKey("players") + try db.primaryKey("player") // [ForeignKeyInfo], the foreign keys defined on the table - try db.foreignKeys(on: "players") + try db.foreignKeys(on: "player") // [IndexInfo], the indexes defined on the table - try db.indexes(on: "players") + try db.indexes(on: "player") // Bool, true if column(s) is a unique key - try db.table("players", hasUniqueKey: ["email"]) + try db.table("player", hasUniqueKey: ["email"]) } // Bool, true if argument is the name of an internal SQLite table @@ -2095,7 +2095,7 @@ try player.updateChanges(db) // does nothing if score has not changed For batch updates, execute an [SQL query](#executing-updates): ```swift -try db.execute("UPDATE players SET synchronized = 1") +try db.execute("UPDATE player SET synchronized = 1") ``` @@ -2158,7 +2158,7 @@ Details follow: ```swift struct Place { ... } try dbQueue.read { db in - let rows = try Row.fetchAll(db, "SELECT * FROM places") + let rows = try Row.fetchAll(db, "SELECT * FROM place") let places: [Place] = rows.map { row in return Place( id: row["id"], @@ -2176,7 +2176,7 @@ Details follow: ```swift struct Place: FetchableRecord { ... } try dbQueue.read { db in - let places = try Place.fetchAll(db, "SELECT * FROM places") + let places = try Place.fetchAll(db, "SELECT * FROM place") } ``` @@ -2186,7 +2186,7 @@ Details follow: ```swift struct Place: TableRecord { ... } - // SELECT * FROM places ORDER BY title + // SELECT * FROM place ORDER BY title let request = Place.order(Column("title")) ``` @@ -2296,14 +2296,14 @@ The `databaseTableName` type property is the name of a database table. `database ```swift extension Place : TableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" } ``` Adopting types can be fetched without SQL, using the [query interface](#the-query-interface): ```swift -// SELECT * FROM places WHERE name = 'Paris' +// SELECT * FROM place WHERE name = 'Paris' let paris = try Place.filter(nameColumn == "Paris").fetchOne(db) ``` @@ -2320,14 +2320,14 @@ try Country.fetchAll(db, keys: ["FR", "US"]) // [Country] When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// SELECT * FROM documents WHERE rowid = 1 +// SELECT * FROM document WHERE rowid = 1 try Document.fetchOne(db, key: 1) // Document? ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? ``` @@ -2520,7 +2520,7 @@ struct Player: Codable { // Adopt Record protocols... extension Player: FetchableRecord, PersistableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" } // ...and you can save and fetch players: @@ -2535,7 +2535,7 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: struct Place: FetchableRecord, PersistableRecord, Codable { - static let databaseTableName = "places" + static let databaseTableName = "place" var title: String var coordinate: CLLocationCoordinate2D // <- Not a simple value! @@ -2567,7 +2567,7 @@ struct Place: Codable { // Free database support! extension Place: FetchableRecord, PersistableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" } ``` @@ -2585,7 +2585,7 @@ struct Place: Codable { } extension Place: FetchableRecord, MutablePersistableRecord { - static let databaseTableName = "places" + static let databaseTableName = "place" mutating func didInsert(with rowID: Int64, for column: String?) { // Update id after insertion @@ -2625,7 +2625,7 @@ class Place: Record { /// The table name override class var databaseTableName: String { - return "places" + return "place" } /// The table columns @@ -2748,36 +2748,36 @@ The [five different policies](https://www.sqlite.org/lang_conflict.html) are: ab - At the table level ```swift - // CREATE TABLE players ( + // CREATE TABLE player ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE ON CONFLICT REPLACE // ) - try db.create(table: "players") { t in + try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("email", .text).unique(onConflict: .replace) // <-- } // Despite the unique index on email, both inserts succeed. // The second insert replaces the first row: - try db.execute("INSERT INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) - try db.execute("INSERT INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` - At the query level: ```swift - // CREATE TABLE players ( + // CREATE TABLE player ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // email TEXT UNIQUE // ) - try db.create(table: "players") { t in + try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("email", .text).unique() } // Again, despite the unique index on email, both inserts succeed. - try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) - try db.execute("INSERT OR REPLACE INTO players (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) + try db.execute("INSERT OR REPLACE INTO player (email) VALUES (?)", arguments: ["arthur@example.com"]) ``` When you want to handle conflicts at the query level, specify a custom `persistenceConflictPolicy` in your type that adopts the MutablePersistableRecord or PersistableRecord protocol. It will alter the INSERT and UPDATE queries run by the `insert`, `update` and `save` [persistence methods](#persistence-methods): @@ -2799,7 +2799,7 @@ struct Player : MutablePersistableRecord { update: .replace) } -// INSERT OR REPLACE INTO players (...) VALUES (...) +// INSERT OR REPLACE INTO player (...) VALUES (...) try player.insert(db) ``` @@ -2817,13 +2817,13 @@ try player.insert(db) ```swift // No explicit primary key -try db.create(table: "events") { t in +try db.create(table: "event") { t in t.column("message", .text) t.column("date", .datetime) } // No way to define an explicit primary key -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in t.column("title") t.column("author") t.column("body") @@ -2835,10 +2835,10 @@ The implicit primary key is stored in the hidden column `rowid`. Hidden means th Some GRDB methods will automatically use this hidden column when a table has no explicit primary key: ```swift -// SELECT * FROM events WHERE rowid = 1 +// SELECT * FROM event WHERE rowid = 1 let event = try Event.fetchOne(db, key: 1) -// DELETE FROM books WHERE rowid = 1 +// DELETE FROM book WHERE rowid = 1 try Book.deleteOne(db, key: 1) ``` @@ -2869,7 +2869,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu GRDB will then select the `rowid` column by default: ```swift - // SELECT *, rowid FROM events + // SELECT *, rowid FROM event let events = try Event.fetchAll(db) ``` @@ -2934,7 +2934,7 @@ We will show below how to declare a record type for the following database table ```swift try dbQueue.write { db in - try db.create(table: "places") { t in + try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text).notNull() t.column("favorite", .boolean).notNull().defaults(to: false) @@ -2977,7 +2977,7 @@ struct Place: Codable { // SQL generation extension Place: TableRecord { /// The table name - static let databaseTableName = "places" + static let databaseTableName = "place" } // Fetching methods @@ -3010,7 +3010,7 @@ struct Place { // SQL generation extension Place: TableRecord { /// The table name - static let databaseTableName = "places" + static let databaseTableName = "place" /// The table columns enum Columns: String, ColumnExpression { @@ -3073,7 +3073,7 @@ class Place: Record { /// The table name override class var databaseTableName: String { - return "places" + return "place" } /// The table columns @@ -3189,13 +3189,13 @@ let count = try request.fetchCount(db) // Int ³ See [SQL queries](#fetch-queries): ```swift -let player = try Player.fetchOne("SELECT * FROM players WHERE id = ?", arguments: [1]) // Player? +let player = try Player.fetchOne("SELECT * FROM player WHERE id = ?", arguments: [1]) // Player? ``` ⁴ See [Prepared Statements](#prepared-statements): ```swift -let statement = try db.makeSelectStatement("SELECT * FROM players WHERE id = ?") +let statement = try db.makeSelectStatement("SELECT * FROM player WHERE id = ?") let player = try Player.fetchOne(statement, arguments: [1]) // Player? ``` @@ -3208,7 +3208,7 @@ The Query Interface ```swift try dbQueue.write { db in // Update database schema - try db.create(table: "wines") { t in ... } + try db.create(table: "wine") { t in ... } // Fetch records let wines = try Wine.filter(origin == "Burgundy").order(price).fetchAll(db) @@ -3228,11 +3228,11 @@ Please bear in mind that the query interface can not generate all possible SQL q ```swift try dbQueue.write { db in // Update database schema (with SQL) - try db.execute("CREATE TABLE wines (...)") + try db.execute("CREATE TABLE wine (...)") // Fetch records (with SQL) let wines = try Wine.fetchAll(db, - "SELECT * FROM wines WHERE origin = ? ORDER BY price", + "SELECT * FROM wine WHERE origin = ? ORDER BY price", arguments: ["Burgundy"]) // Count (with an SQL snippet) @@ -3241,7 +3241,7 @@ try dbQueue.write { db in .fetchCount(db) // Delete (with SQL) - try db.execute("DELETE FROM wines WHERE corked") + try db.execute("DELETE FROM wine WHERE corked") } ``` @@ -3273,14 +3273,14 @@ Once granted with a [database connection](#database-connections), you can setup ### Create Tables ```swift -// CREATE TABLE places ( +// CREATE TABLE place ( // id INTEGER PRIMARY KEY AUTOINCREMENT, // title TEXT, // favorite BOOLEAN NOT NULL DEFAULT 0, // latitude DOUBLE NOT NULL, // longitude DOUBLE NOT NULL // ) -try db.create(table: "places") { t in +try db.create(table: "place") { t in t.autoIncrementedPrimaryKey("id") t.column("title", .text) t.column("favorite", .boolean).notNull().defaults(to: false) @@ -3291,13 +3291,7 @@ try db.create(table: "places") { t in The `create(table:)` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](#full-text-search), or use raw SQL. -SQLite has many reference documents about table creation: - -- [CREATE TABLE](https://www.sqlite.org/lang_createtable.html) -- [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html) -- [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html) -- [ON CONFLICT](https://www.sqlite.org/lang_conflict.html) -- [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html) +SQLite itself has many reference documents about table creation: [CREATE TABLE](https://www.sqlite.org/lang_createtable.html), [Datatypes In SQLite Version 3](https://www.sqlite.org/datatype3.html), [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html), [ON CONFLICT](https://www.sqlite.org/lang_conflict.html), [The WITHOUT ROWID Optimization](https://www.sqlite.org/withoutrowid.html). **Configure table creation**: @@ -3309,6 +3303,8 @@ try db.create(table: "example") { t in ... } try db.create(table: "example", temporary: true, ifNotExists: true) { t in ``` +> :bulb: **Tip**: when you create a database table, prefer giving it a name that is singular and camel-cased, such as `place`, `country`, or `postalAddress`. This is the prefered convention for database table names in GRDB. Other names such as `places` or `postal_address` are also valid, but you may have to perform extra configuration steps. + **Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): ```swift @@ -3344,8 +3340,8 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de // email TEXT UNIQUE, t.column("email", .text).unique() - // countryCode TEXT REFERENCES countries(code) ON DELETE CASCADE, - t.column("countryCode", .text).references("countries", onDelete: .cascade) + // countryCode TEXT REFERENCES country(code) ON DELETE CASCADE, + t.column("countryCode", .text).references("country", onDelete: .cascade) ``` > :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method. @@ -3395,10 +3391,10 @@ SQLite lets you rename tables, and add columns to existing tables: ```swift // ALTER TABLE referers RENAME TO referrers -try db.rename(table: "referers", to: "referrers") +try db.rename(table: "referer", to: "referrer") -// ALTER TABLE players ADD COLUMN url TEXT -try db.alter(table: "players") { t in +// ALTER TABLE player ADD COLUMN url TEXT +try db.alter(table: "player") { t in t.add(column: "url", .text) } ``` @@ -3469,7 +3465,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `all()`, `none()`: the requests for all rows, or no row. ```swift - // SELECT * FROM players + // SELECT * FROM player Player.all() ``` @@ -3478,50 +3474,50 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `select(expression, ...)` defines the selected columns. ```swift - // SELECT id, name FROM players + // SELECT id, name FROM player Player.select(idColumn, nameColumn) - // SELECT MAX(score) AS maxScore FROM players + // SELECT MAX(score) AS maxScore FROM player Player.select(max(scoreColumn).aliased("maxScore")) ``` - `distinct()` performs uniquing. ```swift - // SELECT DISTINCT name FROM players + // SELECT DISTINCT name FROM player Player.select(nameColumn).distinct() ``` - `filter(expression)` applies conditions. ```swift - // SELECT * FROM players WHERE id IN (1, 2, 3) + // SELECT * FROM player WHERE id IN (1, 2, 3) Player.filter([1,2,3].contains(idColumn)) - // SELECT * FROM players WHERE (name IS NOT NULL) AND (height > 1.75) + // SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75) Player.filter(nameColumn != nil && heightColumn > 1.75) ``` - `filter(key:)` and `filter(keys:)` apply conditions on primary keys and unique keys: ```swift - // SELECT * FROM players WHERE id = 1 + // SELECT * FROM player WHERE id = 1 Player.filter(key: 1) - // SELECT * FROM countries WHERE isoCode IN ('FR', 'US') + // SELECT * FROM country WHERE isoCode IN ('FR', 'US') Country.filter(keys: ["FR", "US"]) - // SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' + // SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) - // SELECT * FROM players WHERE email = 'arthur@example.com' + // SELECT * FROM player WHERE email = 'arthur@example.com' Player.filter(key: ["email": "arthur@example.com"]) ``` - `matching(pattern)` performs [full-text search](#full-text-search). ```swift - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database") Document.matching(pattern) ``` @@ -3531,7 +3527,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `group(expression, ...)` groups rows. ```swift - // SELECT name, MAX(score) FROM players GROUP BY name + // SELECT name, MAX(score) FROM player GROUP BY name Player .select(nameColumn, max(scoreColumn)) .group(nameColumn) @@ -3540,7 +3536,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `having(expression)` applies conditions on grouped rows. ```swift - // SELECT team, MAX(score) FROM players GROUP BY team HAVING MIN(score) >= 1000 + // SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000 Player .select(teamColumn, max(scoreColumn)) .group(teamColumn) @@ -3550,55 +3546,55 @@ You can now build requests with the following methods: `all`, `none`, `select`, - `order(ordering, ...)` sorts. ```swift - // SELECT * FROM players ORDER BY name + // SELECT * FROM player ORDER BY name Player.order(nameColumn) - // SELECT * FROM players ORDER BY score DESC, name + // SELECT * FROM player ORDER BY score DESC, name Player.order(scoreColumn.desc, nameColumn) ``` Each `order` call clears any previous ordering: ```swift - // SELECT * FROM players ORDER BY name + // SELECT * FROM player ORDER BY name Player.order(scoreColumn).order(nameColumn) ``` - `reversed()` reverses the eventual orderings. ```swift - // SELECT * FROM players ORDER BY score ASC, name DESC + // SELECT * FROM player ORDER BY score ASC, name DESC Player.order(scoreColumn.desc, nameColumn).reversed() ``` If no ordering was already specified, this method has no effect: ```swift - // SELECT * FROM players + // SELECT * FROM player Player.all().reversed() ``` - `limit(limit, offset: offset)` limits and pages results. ```swift - // SELECT * FROM players LIMIT 5 + // SELECT * FROM player LIMIT 5 Player.limit(5) - // SELECT * FROM players LIMIT 5 OFFSET 10 + // SELECT * FROM player LIMIT 5 OFFSET 10 Player.limit(5, offset: 10) ``` You can refine requests by chaining those methods: ```swift -// SELECT * FROM players WHERE (email IS NOT NULL) ORDER BY name +// SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name Player.order(nameColumn).filter(emailColumn != nil) ``` The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, `filter`, `matching`, and `having` methods extend the query: ```swift -Player // SELECT * FROM players +Player // SELECT * FROM player .filter(nameColumn != nil) // WHERE (name IS NOT NULL) .filter(emailColumn != nil) // AND (email IS NOT NULL) .order(nameColumn) // - ignored - @@ -3612,7 +3608,7 @@ Player // SELECT * FROM players Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): ```swift -// SELECT DATE(creationDate), COUNT(*) FROM players WHERE name = 'Arthur' GROUP BY date(creationDate) +// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) Player .select(sql: "DATE(creationDate), COUNT(*)") .filter(sql: "name = ?", arguments: ["Arthur"]) @@ -3625,7 +3621,7 @@ Player By default, query interface requests select all columns: ```swift -// SELECT * FROM players +// SELECT * FROM player let request = Player.all() ``` @@ -3634,10 +3630,10 @@ let request = Player.all() To specify the selection of a specific request, use the `select` method: ```swift -// SELECT id, name FROM players +// SELECT id, name FROM player let request = Player.select(Column("id"), Column("name")) -// SELECT *, rowid FROM players +// SELECT *, rowid FROM player let request = Player.select(AllColumns(), Column.rowID) ``` @@ -3645,19 +3641,19 @@ To specify the default selection for all requests built from a type, define the ```swift struct RestrictedPlayer : TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")] } struct ExtendedPlayer : TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } -// SELECT id, name FROM players +// SELECT id, name FROM player let request = RestrictedPlayer.all() -// SELECT *, rowid FROM players +// SELECT *, rowid FROM player let request = ExtendedPlayer.all() ``` @@ -3676,16 +3672,16 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Comparison operators are based on the Swift operators `==`, `!=`, `===`, `!==`, `<`, `<=`, `>`, `>=`: ```swift - // SELECT * FROM players WHERE (name = 'Arthur') + // SELECT * FROM player WHERE (name = 'Arthur') Player.filter(nameColumn == "Arthur") - // SELECT * FROM players WHERE (name IS NULL) + // SELECT * FROM player WHERE (name IS NULL) Player.filter(nameColumn == nil) - // SELECT * FROM players WHERE (score IS 1000) + // SELECT * FROM player WHERE (score IS 1000) Player.filter(scoreColumn === 1000) - // SELECT * FROM rectangles WHERE width < height + // SELECT * FROM rectangle WHERE width < height Rectangle.filter(widthColumn < heightColumn) ``` @@ -3696,7 +3692,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: SQLite arithmetic operators are derived from their Swift equivalent: ```swift - // SELECT ((temperature * 1.8) + 32) AS farenheit FROM players + // SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet Planet.select((temperatureColumn * 1.8 + 32).aliased("farenheit")) ``` @@ -3707,14 +3703,14 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: The SQL logical operators are derived from the Swift `&&`, `||` and `!`: ```swift - // SELECT * FROM players WHERE ((NOT verified) OR (score < 1000)) + // SELECT * FROM player WHERE ((NOT verified) OR (score < 1000)) Player.filter(!verifiedColumn || scoreColumn < 1000) ``` When you want to join a sequence of expressions with `AND` or `OR` operators, use `joined(operator:)`: ```swift - // SELECT * FROM players WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) + // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) let conditions = [ verifiedColumn, scoreColumn >= 1000, @@ -3725,10 +3721,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: When the sequence is empty, `joined(operator: .and)` returns true, and `joined(operator: .or)` returns false: ```swift - // SELECT * FROM players WHERE 1 + // SELECT * FROM player WHERE 1 Player.filter([].joined(operator: .and)) - // SELECT * FROM players WHERE 0 + // SELECT * FROM player WHERE 0 Player.filter([].joined(operator: .or)) ``` @@ -3737,22 +3733,22 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: To check inclusion in a Swift sequence (array, set, range…), call the `contains` method: ```swift - // SELECT * FROM players WHERE id IN (1, 2, 3) + // SELECT * FROM player WHERE id IN (1, 2, 3) Player.filter([1, 2, 3].contains(idColumn)) - // SELECT * FROM players WHERE id NOT IN (1, 2, 3) + // SELECT * FROM player WHERE id NOT IN (1, 2, 3) Player.filter(![1, 2, 3].contains(idColumn)) - // SELECT * FROM players WHERE score BETWEEN 0 AND 1000 + // SELECT * FROM player WHERE score BETWEEN 0 AND 1000 Player.filter((0...1000).contains(scoreColumn)) - // SELECT * FROM players WHERE (score >= 0) AND (score < 1000) + // SELECT * FROM player WHERE (score >= 0) AND (score < 1000) Player.filter((0..<1000).contains(scoreColumn)) - // SELECT * FROM players WHERE initial BETWEEN 'A' AND 'N' + // SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N' Player.filter(("A"..."N").contains(initialColumn)) - // SELECT * FROM players WHERE (initial >= 'A') AND (initial < 'N') + // SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N') Player.filter(("A"..<"N").contains(initialColumn)) ``` @@ -3763,7 +3759,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: The SQLite LIKE operator is available as the `like` method: ```swift - // SELECT * FROM players WHERE (email LIKE '%@example.com') + // SELECT * FROM player WHERE (email LIKE '%@example.com') Player.filter(emailColumn.like("%@example.com")) ``` @@ -3778,10 +3774,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let pattern = FTS3Pattern(matchingAllTokensIn: "SQLite database") - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) - // SELECT * FROM documents WHERE content MATCH 'sqlite database' + // SELECT * FROM document WHERE content MATCH 'sqlite database' Document.filter(contentColumn.match(pattern)) ``` @@ -3790,7 +3786,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let pattern = FTS5Pattern(matchingAllTokensIn: "SQLite database") - // SELECT * FROM documents WHERE documents MATCH 'sqlite database' + // SELECT * FROM document WHERE document MATCH 'sqlite database' Document.matching(pattern) ``` @@ -3802,13 +3798,13 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Those are based on the `abs`, `average`, `count`, `length`, `max`, `min` and `sum` Swift functions: ```swift - // SELECT MIN(score), MAX(score) FROM players + // SELECT MIN(score), MAX(score) FROM player Player.select(min(scoreColumn), max(scoreColumn)) - // SELECT COUNT(name) FROM players + // SELECT COUNT(name) FROM player Player.select(count(nameColumn)) - // SELECT COUNT(DISTINCT name) FROM players + // SELECT COUNT(DISTINCT name) FROM player Player.select(count(distinct: nameColumn)) ``` @@ -3817,10 +3813,10 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: Use the Swift `??` operator: ```swift - // SELECT IFNULL(name, 'Anonymous') FROM players + // SELECT IFNULL(name, 'Anonymous') FROM player Player.select(nameColumn ?? "Anonymous") - // SELECT IFNULL(name, email) FROM players + // SELECT IFNULL(name, email) FROM player Player.select(nameColumn ?? emailColumn) ``` @@ -3853,7 +3849,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code: ```swift let f = DatabaseFunction("f", ...) - // SELECT f(name) FROM players + // SELECT f(name) FROM player Player.select(f.apply(nameColumn)) ``` @@ -3911,60 +3907,60 @@ request.rx **Fetching records according to their primary key** is a very common task. It has a shortcut which accepts any single-column primary key: ```swift -// SELECT * FROM players WHERE id = 1 +// SELECT * FROM player WHERE id = 1 try Player.fetchOne(db, key: 1) // Player? -// SELECT * FROM players WHERE id IN (1, 2, 3) +// SELECT * FROM player WHERE id IN (1, 2, 3) try Player.fetchAll(db, keys: [1, 2, 3]) // [Player] -// SELECT * FROM players WHERE isoCode = 'FR' +// SELECT * FROM player WHERE isoCode = 'FR' try Country.fetchOne(db, key: "FR") // Country? -// SELECT * FROM countries WHERE isoCode IN ('FR', 'US') +// SELECT * FROM country WHERE isoCode IN ('FR', 'US') try Country.fetchAll(db, keys: ["FR", "US"]) // [Country] ``` When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// SELECT * FROM documents WHERE rowid = 1 +// SELECT * FROM document WHERE rowid = 1 try Document.fetchOne(db, key: 1) // Document? ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? -// SELECT * FROM players WHERE email = 'arthur@example.com' +// SELECT * FROM player WHERE email = 'arthur@example.com' try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player? ``` **When you want to build a request and plan to fetch from it later**, use the `filter(key:)` and `filter(keys:)` methods: ```swift -// SELECT * FROM players WHERE id = 1 +// SELECT * FROM player WHERE id = 1 let request = Player.filter(key: 1) let player = try request.fetchOne(db) // Player? -// SELECT * FROM players WHERE id IN (1, 2, 3) +// SELECT * FROM player WHERE id IN (1, 2, 3) let request = Player.filter(keys: [1, 2, 3]) let players = try request.fetchAll(db) // [Player] -// SELECT * FROM players WHERE isoCode = 'FR' +// SELECT * FROM player WHERE isoCode = 'FR' let request = Country.filter(key: "FR") let country = try request.fetchOne(db) // Country? -// SELECT * FROM countries WHERE isoCode IN ('FR', 'US') +// SELECT * FROM country WHERE isoCode IN ('FR', 'US') let request = Country.filter(keys: ["FR", "US"]) let countries = try request.fetchAll(db) // [Country] -// SELECT * FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) let citizenship = request.fetchOne(db) // Citizenship? -// SELECT * FROM players WHERE email = 'arthur@example.com' +// SELECT * FROM player WHERE email = 'arthur@example.com' let request = Player.filter(key: ["email": "arthur@example.com"]) let player = try request.fetchOne(db) // Player? ``` @@ -3985,16 +3981,16 @@ Player.filter(key: 1).rx **Requests can count.** The `fetchCount()` method returns the number of rows that would be returned by a fetch request: ```swift -// SELECT COUNT(*) FROM players +// SELECT COUNT(*) FROM player let count = try Player.fetchCount(db) // Int -// SELECT COUNT(*) FROM players WHERE email IS NOT NULL +// SELECT COUNT(*) FROM player WHERE email IS NOT NULL let count = try Player.filter(emailColumn != nil).fetchCount(db) -// SELECT COUNT(DISTINCT name) FROM players +// SELECT COUNT(DISTINCT name) FROM player let count = try Player.select(nameColumn).distinct().fetchCount(db) -// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM players) +// SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player) let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db) ``` @@ -4017,7 +4013,7 @@ let maxScore = row[1] as Int? **Requests can delete records**, with the `deleteAll()` method: ```swift -// DELETE FROM players WHERE email IS NULL +// DELETE FROM player WHERE email IS NULL let request = Player.filter(emailColumn == nil) try request.deleteAll(db) ``` @@ -4027,33 +4023,33 @@ try request.deleteAll(db) **Deleting records according to their primary key** is also quite common. It has a shortcut which accepts any single-column primary key: ```swift -// DELETE FROM players WHERE id = 1 +// DELETE FROM player WHERE id = 1 try Player.deleteOne(db, key: 1) -// DELETE FROM players WHERE id IN (1, 2, 3) +// DELETE FROM player WHERE id IN (1, 2, 3) try Player.deleteAll(db, keys: [1, 2, 3]) -// DELETE FROM players WHERE isoCode = 'FR' +// DELETE FROM player WHERE isoCode = 'FR' try Country.deleteOne(db, key: "FR") -// DELETE FROM countries WHERE isoCode IN ('FR', 'US') +// DELETE FROM country WHERE isoCode IN ('FR', 'US') try Country.deleteAll(db, keys: ["FR", "US"]) ``` When the table has no explicit primary key, GRDB uses the [hidden "rowid" column](#the-implicit-rowid-primary-key): ```swift -// DELETE FROM documents WHERE rowid = 1 +// DELETE FROM document WHERE rowid = 1 try Document.deleteOne(db, key: 1) ``` For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// DELETE FROM citizenships WHERE playerID = 1 AND countryISOCode = 'FR' +// DELETE FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' try Citizenship.deleteOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) -// DELETE FROM players WHERE email = 'arthur@example.com' +// DELETE FROM player WHERE email = 'arthur@example.com' Player.deleteOne(db, key: ["email": "arthur@example.com"]) ``` @@ -4204,7 +4200,7 @@ let request = Player.all() extension Player { static func filter(color: Color) -> SQLRequest { let request = SQLRequest( - "SELECT * FROM players WHERE color = ?" + "SELECT * FROM player WHERE color = ?" arguments: [color]) } } @@ -4246,7 +4242,7 @@ For example: ```swift let playerRequest = SQLRequest( - "SELECT * FROM players WHERE color = ?" + "SELECT * FROM player WHERE color = ?" arguments: [color]) try request.fetchAll(db) // [Player] ``` @@ -4281,22 +4277,22 @@ Inside each migration, you typically [define and update your database tables](#d ```swift var migrator = DatabaseMigrator() -// v1 database +// 1st migration migrator.registerMigration("v1") { db in - try db.create(table: "players") { t in ... } - try db.create(table: "books") { t in ... } + try db.create(table: "author") { t in ... } + try db.create(table: "book") { t in ... } try db.create(index: ...) } -// v2 database +// 2nd migration migrator.registerMigration("v2") { db in - try db.alter(table: "players") { t in ... } + try db.alter(table: "author") { t in ... } } // Migrations for future versions will be inserted here: // -// // v3 database -// migrator.registerMigration("v3") { db in +// // 3rd migration +// migrator.registerMigration("...") { db in // ... // } ``` @@ -4342,15 +4338,15 @@ SQLite does not support many schema changes, and won't let you drop a table colu Yet any kind of schema change is still possible. The SQLite documentation explains in detail how to do so: https://www.sqlite.org/lang_altertable.html#otheralter. This technique requires the temporary disabling of foreign key checks, and is supported by the `registerMigrationWithDeferredForeignKeyCheck` function: ```swift -// Add a NOT NULL constraint on players.name: +// Add a NOT NULL constraint on player.name: migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - try db.create(table: "new_players") { t in + try db.create(table: "new_player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() } - try db.execute("INSERT INTO new_players SELECT * FROM players") - try db.drop(table: "players") - try db.rename(table: "new_players", to: "players") + try db.execute("INSERT INTO new_player SELECT * FROM player") + try db.drop(table: "player") + try db.rename(table: "new_player", to: "player") } ``` @@ -4363,7 +4359,7 @@ While your migration code runs with disabled foreign key checks, those are re-en ```swift // Create full-text tables -try db.create(virtualTable: "books", using: FTS4()) { t in // or FTS3(), or FTS5() +try db.create(virtualTable: "book", using: FTS4()) { t in // or FTS3(), or FTS5() t.column("author") t.column("title") t.column("body") @@ -4372,7 +4368,7 @@ try db.create(virtualTable: "books", using: FTS4()) { t in // or FTS3(), or FTS5 // Populate full-text table with records or SQL try Book(...).insert(db) try db.execute( - "INSERT INTO books (author, title, body) VALUES (?, ?, ?)", + "INSERT INTO book (author, title, body) VALUES (?, ?, ?)", arguments: [...]) // Build search patterns @@ -4381,7 +4377,7 @@ let pattern = FTS3Pattern(matchingPhrase: "Moby-Dick") // Search with the query interface or SQL let books = try Book.matching(pattern).fetchAll(db) let books = try Book.fetchAll(db, - "SELECT * FROM books WHERE books MATCH ?", + "SELECT * FROM book WHERE book MATCH ?", arguments: [pattern]) ``` @@ -4454,13 +4450,13 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do Create tables with the `create(virtualTable:using:)` method: ```swift -// CREATE VIRTUAL TABLE documents USING fts3(content) -try db.create(virtualTable: "documents", using: FTS3()) { t in +// CREATE VIRTUAL TABLE document USING fts3(content) +try db.create(virtualTable: "document", using: FTS3()) { t in t.column("content") } -// CREATE VIRTUAL TABLE documents USING fts4(content) -try db.create(virtualTable: "documents", using: FTS4()) { t in +// CREATE VIRTUAL TABLE document USING fts4(content) +try db.create(virtualTable: "document", using: FTS4()) { t in t.column("content") } ``` @@ -4470,13 +4466,13 @@ try db.create(virtualTable: "documents", using: FTS4()) { t in You can specify a [tokenizer](#fts3-and-fts4-tokenizers): ```swift -// CREATE VIRTUAL TABLE books USING fts4( +// CREATE VIRTUAL TABLE book USING fts4( // tokenize=porter, // author, // title, // body // ) -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .porter t.column("author") t.column("title") @@ -4487,7 +4483,7 @@ try db.create(virtualTable: "books", using: FTS4()) { t in FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options): ```swift -// CREATE VIRTUAL TABLE books USING fts4( +// CREATE VIRTUAL TABLE book USING fts4( // content, // uuid, // content="", @@ -4497,7 +4493,7 @@ FTS4 supports [options](https://www.sqlite.org/fts3.html#fts4_options): // notindexed=uuid, // languageid=lid // ) -try db.create(virtualTable: "documents", using: FTS4()) { t in +try db.create(virtualTable: "document", using: FTS4()) { t in t.content = "" t.compress = "zip" t.uncompress = "unzip" @@ -4521,7 +4517,7 @@ See [SQLite documentation](https://www.sqlite.org/fts3.html) for more informatio SQLite ships with three built-in FTS3/4 tokenizers: `simple`, `porter` and `unicode61` that use different algorithms to match queries with indexed content: ```swift -try db.create(virtualTable: "books", using: FTS4()) { t in +try db.create(virtualTable: "book", using: FTS4()) { t in // Pick one: t.tokenizer = .simple // default t.tokenizer = .porter @@ -4546,7 +4542,7 @@ See below some examples of matches: - **simple** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .simple // default } ``` @@ -4560,7 +4556,7 @@ See below some examples of matches: - **porter** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .porter } ``` @@ -4572,7 +4568,7 @@ See below some examples of matches: - **unicode61** ```swift - try db.create(virtualTable: "books", using: FTS4()) { t in + try db.create(virtualTable: "book", using: FTS4()) { t in t.tokenizer = .unicode61() t.tokenizer = .unicode61(removeDiacritics: false) } @@ -4642,7 +4638,7 @@ FTS3Pattern are regular [values](#values). You can use them as query [arguments] ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE content MATCH ?", + "SELECT * FROM document WHERE content MATCH ?", arguments: [pattern]) ``` @@ -4666,8 +4662,8 @@ To use FTS5, you'll need a [custom SQLite build](Documentation/CustomSQLiteBuild Create FTS5 tables with the `create(virtualTable:using:)` method: ```swift -// CREATE VIRTUAL TABLE documents USING fts5(content) -try db.create(virtualTable: "documents", using: FTS5()) { t in +// CREATE VIRTUAL TABLE document USING fts5(content) +try db.create(virtualTable: "document", using: FTS5()) { t in t.column("content") } ``` @@ -4677,13 +4673,13 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in You can specify a [tokenizer](#fts5-tokenizers): ```swift -// CREATE VIRTUAL TABLE books USING fts5( +// CREATE VIRTUAL TABLE book USING fts5( // tokenize='porter', // author, // title, // body // ) -try db.create(virtualTable: "books", using: FTS5()) { t in +try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .porter() t.column("author") t.column("title") @@ -4694,7 +4690,7 @@ try db.create(virtualTable: "books", using: FTS5()) { t in FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization): ```swift -// CREATE VIRTUAL TABLE books USING fts5( +// CREATE VIRTUAL TABLE book USING fts5( // content, // uuid UNINDEXED, // content='table', @@ -4703,7 +4699,7 @@ FTS5 supports [options](https://www.sqlite.org/fts5.html#fts5_table_creation_and // columnsize=0, // detail=column // ) -try db.create(virtualTable: "documents", using: FTS5()) { t in +try db.create(virtualTable: "document", using: FTS5()) { t in t.column("content") t.column("uuid").notIndexed() t.content = "table" @@ -4726,7 +4722,7 @@ See [SQLite documentation](https://www.sqlite.org/fts5.html) for more informatio SQLite ships with three built-in FTS5 tokenizers: `ascii`, `porter` and `unicode61` that use different algorithms to match queries with indexed content. ```swift -try db.create(virtualTable: "books", using: FTS5()) { t in +try db.create(virtualTable: "book", using: FTS5()) { t in // Pick one: t.tokenizer = .unicode61() // default t.tokenizer = .unicode61(...) @@ -4752,7 +4748,7 @@ See below some examples of matches: - **unicode61** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .unicode61() t.tokenizer = .unicode61(removeDiacritics: false) } @@ -4767,7 +4763,7 @@ See below some examples of matches: - **ascii** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .ascii } ``` @@ -4781,7 +4777,7 @@ See below some examples of matches: - **porter** ```swift - try db.create(virtualTable: "books", using: FTS5()) { t in + try db.create(virtualTable: "book", using: FTS5()) { t in t.tokenizer = .porter() // porter wrapping unicode61 (the default) t.tokenizer = .porter(.ascii) // porter wrapping ascii t.tokenizer = .porter(.unicode61(removeDiacritics: false)) // porter wrapping unicode61 without diacritics stripping @@ -4825,11 +4821,11 @@ The `Database.makeFTS5Pattern(rawPattern:forTable:)` method validates your raw p ```swift // OK: FTS5Pattern -try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "sqlite", forTable: "book") // DatabaseError: syntax error near \"AND\" -try db.makeFTS5Pattern(rawPattern: "AND", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "AND", forTable: "book") // DatabaseError: no such column: missing -try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "books") +try db.makeFTS5Pattern(rawPattern: "missing: sqlite", forTable: "book") ``` The FTS5Pattern initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application: @@ -4857,7 +4853,7 @@ FTS5Pattern are regular [values](#values). You can use them as query [arguments] ```swift let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE documents MATCH ?", + "SELECT * FROM document WHERE document MATCH ?", arguments: [pattern]) ``` @@ -4875,7 +4871,7 @@ let documents = try Document.matching(pattern).fetchAll(db) ```swift // SQL let documents = try Document.fetchAll(db, - "SELECT * FROM documents WHERE documents MATCH ? ORDER BY rank", + "SELECT * FROM document WHERE document MATCH ? ORDER BY rank", arguments: [pattern]) // Query Interface @@ -4897,7 +4893,7 @@ The two tables must be kept up-to-date, so that the full-text index matches the ```swift // A regular table -try db.create(table: "books") { t in +try db.create(table: "book") { t in t.column("author", .text) t.column("title", .text) t.column("content", .text) @@ -4905,8 +4901,8 @@ try db.create(table: "books") { t in } // A full-text table synchronized with the regular table -try db.create(virtualTable: "books_ft", using: FTS4()) { t in // or FTS5() - t.synchronize(withTable: "books") +try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5() + t.synchronize(withTable: "book") t.column("author") t.column("title") t.column("content") @@ -4932,26 +4928,26 @@ To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5Sy ```swift // Create tables -try db.create(table: "books") { t in +try db.create(table: "book") { t in ... } -try db.create(virtualTable: "books_ft", using: FTS4()) { t in - t.synchronize(withTable: "books") +try db.create(virtualTable: "book_ft", using: FTS4()) { t in + t.synchronize(withTable: "book") ... } // Drop full-text table -try db.drop(table: "books_ft") -try db.dropFTS4SynchronizationTriggers(forTable: "books_ft") +try db.drop(table: "book_ft") +try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") ``` > :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table: > > ```swift > // Drop full-text table -> try db.drop(table: "books_ft") -> try db.dropFTS4SynchronizationTriggers(forTable: "books_ft") -> try db.dropFTS4SynchronizationTriggers(forTable: "books") // Support for GRDB <= 2.3.1 +> try db.drop(table: "book_ft") +> try db.dropFTS4SynchronizationTriggers(forTable: "book_ft") +> try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1 > ``` @@ -4966,7 +4962,7 @@ That is because SQLite will throw an error when you try to perform a full-text s ```swift // SQLite error 1: unable to use function MATCH in the requested context -// SELECT * FROM books WHERE books MATCH '...' +// SELECT * FROM book WHERE book MATCH '...' let books = Book.matching(pattern).fetchAll(db) ``` @@ -4974,11 +4970,11 @@ The solution is to perform a joined request, using raw SQL: ```swift let sql = """ - SELECT books.* - FROM books - JOIN books_ft ON - books_ft.rowid = books.rowid AND - books_ft MATCH ? + SELECT book.* + FROM book + JOIN book_ft + ON book_ft.rowid = book.rowid + AND book_ft MATCH ? """ let books = Book.fetchAll(db, sql, arguments: [pattern]) ``` @@ -5018,10 +5014,10 @@ In this chapter, we will focus on the extraction of information from complex row ```sql -- How to consume the left, middle, and right parts of those rows? -SELECT players.*, teams.*, MAX(rounds.score) AS maxScore -FROM players -LEFT JOIN teams ON ... -LEFT JOIN rounds ON ... +SELECT player.*, team.*, MAX(round.score) AS maxScore +FROM player +LEFT JOIN team ON ... +LEFT JOIN round ON ... GROUP BY ... ``` @@ -5029,7 +5025,7 @@ We will not talk about *building* joined queries. **So what are we talking about?** -It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: `id` from table `players`, `id` from table `teams`, etc. +It is difficult to consume rows fetched from complex joined queries, because they often contain several columns with the same name: `id` from table `player`, `id` from table `team`, etc. When such ambiguity happens, GRDB row accessors always favor the leftmost matching column. This means that `row["id"]` would give a player id, whithout any obvious way to access the team id. @@ -5037,10 +5033,10 @@ A classical technique to avoid this ambiguity is to give each column a unique na ```sql -- A classical technique -SELECT players.id AS players_id, players.name AS players_name, teams.id AS teams_id, teams.name AS teams_name, teams.color AS teams_color, MAX(rounds.score) AS maxScore -FROM players -LEFT JOIN teams ON ... -LEFT JOIN rounds ON ... +SELECT player.id AS player_id, player.name AS player_name, team.id AS team_id, team.name AS team_name, team.color AS team_color, MAX(round.score) AS maxScore +FROM player +LEFT JOIN team ON ... +LEFT JOIN round ON ... GROUP BY ... ``` @@ -5048,11 +5044,11 @@ This technique works pretty well, but it has three drawbacks: 1. The selection becomes hard to read and understand. 2. Such queries are difficult to write by hand. -3. The mangled names are a *very* bad fit for [FetchableRecord] types that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM teams ...`, it should be able to read `SELECT ..., teams.*, ...` as well. +3. The mangled names are a *very* bad fit for [FetchableRecord] types that expect specific column names. After all, if the `Team` record type can read `SELECT * FROM team ...`, it should be able to read `SELECT ..., team.*, ...` as well. We thus need another technique. **Below we'll see how to split rows into slices, and preserve column names.** -`SELECT players.*, teams.*, MAX(rounds.score) AS maxScore FROM ...` will be splitted into three slices: one that contains player's columns, one that contains team's columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the `Player.init(row:)` initializer. In the same way, the Team record type could read the second slice. +`SELECT player.*, team.*, MAX(round.score) AS maxScore FROM ...` will be splitted into three slices: one that contains player's columns, one that contains team's columns, and a remaining slice that contains remaining column(s). The Player record type will be able to read the first slice, which contains the colums expected by the `Player.init(row:)` initializer. In the same way, the Team record type could read the second slice. Unlike the name-mangling technique, splitting rows keeps SQL legible, accepts your hand-crafted SQL queries, and plays as nicely as possible with your existing [record types](#records). @@ -5073,30 +5069,30 @@ At the very beginning, there is an SQL query: ```swift try dbQueue.read { db in let sql = """ - SELECT players.*, teams.*, MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + SELECT player.*, team.*, MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ ``` -We need an adapter that extracts players' columns, in a slice that has as many columns as there are columns in the players table. That's [RangeRowAdapter](#rangerowadapter): +We need an adapter that extracts player columns, in a slice that has as many columns as there are columns in the player table. That's [RangeRowAdapter](#rangerowadapter): ```swift - // SELECT players.*, teams.*, ... - // <-------> - let playersWidth = try db.columns(in: "players").count - let playerAdapter = RangeRowAdapter(0 ..< playersWidth) + // SELECT player.*, team.*, ... + // <------> + let playerWidth = try db.columns(in: "player").count + let playerAdapter = RangeRowAdapter(0 ..< playerWidth) ``` -We also need an adapter that extracts teams' columns: +We also need an adapter that extracts team columns: ```swift - // SELECT players.*, teams.*, ... - // <-----> - let teamsWidth = try db.columns(in: "teams").count - let teamAdapter = RangeRowAdapter(playersWidth ..< (playersWidth + teamsWidth)) + // SELECT player.*, team.*, ... + // <----> + let teamWidth = try db.columns(in: "team").count + let teamAdapter = RangeRowAdapter(playerWidth ..< (playerWidth + teamWidth)) ``` We merge those two adapters in a single [ScopeAdapter](#scopeadapter) that will allow us to access both sliced rows: @@ -5188,23 +5184,23 @@ extension PlayerInfo { static func fetchAll(_ db: Database) throws -> [PlayerInfo] { ``` -To acknowledge that both Player and Team records may customize their selection of the "players" and "teams" columns, we'll write our SQL in a slightly different way: +To acknowledge that both Player and Team records may customize their selection of the "player" and "team" columns, we'll write our SQL in a slightly different way: ```swift // Let Player and Team customize their selection: let sql = """ SELECT - \(Player.selectionSQL()), -- instead of players.* - \(Team.selectionSQL()), -- instead of teams.* - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + \(Player.selectionSQL()), -- instead of player.* + \(Team.selectionSQL()), -- instead of team.* + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ ``` -`Player.selectionSQL()` will output `players.*`, unless Player defines a [customized selection](#columns-selected-by-a-request). +`Player.selectionSQL()` will output `player.*`, unless Player defines a [customized selection](#columns-selected-by-a-request). > :point_up: **Note**: you may also use SQL table aliases: > @@ -5214,14 +5210,14 @@ To acknowledge that both Player and Team records may customize their selection o > \(Player.selectionSQL(alias: "p")), > \(Team.selectionSQL(alias: "t")), > MAX(r.score) AS maxScore -> FROM players p -> LEFT JOIN teams t ON ... -> LEFT JOIN rounds r ON ... +> FROM player p +> LEFT JOIN team t ON ... +> LEFT JOIN round r ON ... > GROUP BY ... > """ > ``` -Now is the time to build adapters (taking in account the customized selection of both players and teams). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: +Now is the time to build adapters (taking in account the customized selection of both player and team). We use the `splittingRowAdapters` global function, which builds row adapters of desired widths: ```swift let adapters = try splittingRowAdapters(columnCounts: [ @@ -5233,7 +5229,7 @@ Now is the time to build adapters (taking in account the customized selection of Scopes.team: adapters[1]]) ``` -> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for players, one for teams, and one for the remaining columns. +> :point_up: **Note**: `splittingRowAdapters` returns as many adapters as necessary to fully split a row. In the example above, it returns *three* adapters: one for player, one for team, and one for the remaining columns. And finally, we can fetch player infos: @@ -5299,10 +5295,10 @@ extension PlayerInfo { SELECT \(Player.selectionSQL()), \(Team.selectionSQL()), - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ return SQLRequest(sql).adapted { db in @@ -5349,12 +5345,12 @@ You can consume complex joined queries with Codable records as well. As a demons ```swift struct Player: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "players" + static let databaseTableName = "player" var id: Int64 var name: String } struct Team: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "teams" + static let databaseTableName = "team" var id: Int64 var name: String var color: Color @@ -5372,10 +5368,10 @@ extension PlayerInfo { SELECT \(Player.selectionSQL()), \(Team.selectionSQL()), - MAX(rounds.score) AS maxScore - FROM players - LEFT JOIN teams ON ... - LEFT JOIN rounds ON ... + MAX(round.score) AS maxScore + FROM player + LEFT JOIN team ON ... + LEFT JOIN round ON ... GROUP BY ... """ return SQLRequest(sql).adapted { db in @@ -5620,18 +5616,18 @@ See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e63 **Transaction observers can avoid being notified of database changes they are not interested in.** -The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "players" database table: +The filtering happens in the `observes(eventsOfKind:)` method, which tells whether the observer wants notification of specific kinds of changes, or not. For example, here is how an observer can focus on the changes that happen on the "player" database table: ```swift class PlayerObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "players" table. - return eventKind.tableName == "players" + // Only observe changes to the "player" table. + return eventKind.tableName == "player" } func databaseDidChange(with event: DatabaseEvent) { // This method is only called for changes that happen to - // the "players" table. + // the "player" table. } } ``` @@ -5641,14 +5637,14 @@ Generally speaking, the `observes(eventsOfKind:)` method can distinguish inserti ```swift class PlayerScoreObserver: TransactionObserver { func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - // Only observe changes to the "score" column of the "players" table. + // Only observe changes to the "score" column of the "player" table. switch eventKind { case .insert(let tableName): - return tableName == "players" + return tableName == "player" case .delete(let tableName): - return tableName == "players" + return tableName == "player" case .update(let tableName, let columnNames): - return tableName == "players" && columnNames.contains("score") + return tableName == "player" && columnNames.contains("score") } } } @@ -5714,14 +5710,14 @@ Finally, an observer may ignore all database changes until the end of the curren ```swift class PlayerObserver: TransactionObserver { - var playersTableWasModified = false + var playerTableWasModified = false func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - return eventKind.tableName == "players" + return eventKind.tableName == "player" } func databaseDidChange(with event: DatabaseEvent) { - playersTableWasModified = true + playerTableWasModified = true // It is pointless to keep on tracking further changes: stopObservingDatabaseChangesUntilNextTransaction() @@ -5795,21 +5791,21 @@ let controller = FetchedRecordsController( // Using SQL, and eventual arguments: let controller = FetchedRecordsController( dbQueue, - sql: "SELECT * FROM players ORDER BY name WHERE countryIsoCode = ?", + sql: "SELECT * FROM player ORDER BY name WHERE countryIsoCode = ?", arguments: ["FR"]) ``` The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request. ```swift -let controller = FetchedRecordsController( +let controller = FetchedRecordsController( dbQueue, sql: """ - SELECT players.name, COUNT(books.id) AS bookCount - FROM players - LEFT JOIN books ON books.authorId = players.id - GROUP BY players.id - ORDER BY players.name + SELECT author.name, COUNT(book.id) AS bookCount + FROM author + LEFT JOIN book ON book.authorId = author.id + GROUP BY author.id + ORDER BY author.name """) ``` @@ -6269,7 +6265,7 @@ Considering that a local database is not some JSON loaded from a remote server, ```swift do { try db.execute( - "INSERT INTO pets (masterId, name) VALUES (?, ?)", + "INSERT INTO pet (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) } catch let error as DatabaseError { // The SQLite error code: 19 (SQLITE_CONSTRAINT) @@ -6282,11 +6278,11 @@ do { error.message // The eventual erroneous SQL query - // "INSERT INTO pets (masterId, name) VALUES (?, ?)" + // "INSERT INTO pet (masterId, name) VALUES (?, ?)" error.sql // Full error description: - // "SQLite error 19 with statement `INSERT INTO pets (masterId, name) + // "SQLite error 19 with statement `INSERT INTO pet (masterId, name) // VALUES (?, ?)` arguments [1, "Bobby"]: FOREIGN KEY constraint failed"" error.description } @@ -6386,11 +6382,11 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are - **The database can't guarantee that the code does what it says:** ```swift - // fatal error: table players has no unique index on column email + // fatal error: table player has no unique index on column email try Player.deleteOne(db, key: ["email": "arthur@example.com"]) ``` - Solution: add a unique index to the players.email column, or use the `deleteAll` method to make it clear that you may delete more than one row: + Solution: add a unique index to the player.email column, or use the `deleteAll` method to make it clear that you may delete more than one row: ```swift try Player.filter(Column("email") == "arthur@example.com").deleteAll(db) @@ -6524,7 +6520,7 @@ GRDB comes with five extra collations that leverage unicode-aware comparisons ba A collation can be applied to a table column. All comparisons involving this column will then automatically trigger the comparison function: ```swift -try db.create(table: "players") { t in +try db.create(table: "player") { t in // Guarantees case-insensitive email unicity t.column("email", .text).unique().collate(.nocase) @@ -6543,7 +6539,7 @@ If you can't or don't want to define the comparison behavior of a column (see wa ```swift let collation = DatabaseCollation.localizedCaseInsensitiveCompare let players = try Player.fetchAll(db, - "SELECT * FROM players ORDER BY name COLLATE \(collation.name))") + "SELECT * FROM player ORDER BY name COLLATE \(collation.name))") let players = try Player.order(nameColumn.collating(collation)).fetchAll(db) ``` @@ -7081,10 +7077,10 @@ Obviously, no code is faster than any code. **Don't fetch columns you don't use** ```swift -// SELECT * FROM players +// SELECT * FROM player try Player.fetchAll(db) -// SELECT id, name FROM players +// SELECT id, name FROM player try Player.select(idColumn, nameColumn).fetchAll(db) ``` @@ -7144,10 +7140,10 @@ Consider a simple use case: your store application has to display a list of auth The following code is inefficient. It is an example of the [N+1 problem](http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue), because it performs one query to load the authors, and then N queries, as many as there are authors. This turns very inefficient as the number of authors grows: ```swift -// SELECT * FROM authors +// SELECT * FROM author let authors = try Author.fetchAll(db) for author in authors { - // SELECT COUNT(*) FROM books WHERE authorId = ... + // SELECT COUNT(*) FROM book WHERE authorId = ... author.bookCount = try Book.filter(authorIdColumn == author.id).fetchCount(db) } ``` @@ -7156,10 +7152,10 @@ Instead, perform *a single query*: ```swift let sql = """ - SELECT authors.*, COUNT(books.id) AS bookCount - FROM authors - LEFT JOIN books ON books.authorId = authors.id - GROUP BY authors.id + SELECT author.*, COUNT(book.id) AS bookCount + FROM author + LEFT JOIN book ON book.authorId = author.id + GROUP BY author.id """ let authors = try Author.fetchAll(db, sql) ``` @@ -7210,7 +7206,7 @@ For example, when fetching values, prefer loading columns by index: let players = try Player.fetchAll(db) // Column indexes -// SELECT id, name, email FROM players +// SELECT id, name, email FROM player let request = Player.select(idColumn, nameColumn, emailColumn) let rows = try Row.fetchCursor(db, request) while let row = try rows.next() { @@ -7231,7 +7227,7 @@ for player in players { } // Prepared statement -let insertStatement = db.prepareStatement("INSERT INTO players (name, email) VALUES (?, ?)") +let insertStatement = db.prepareStatement("INSERT INTO player (name, email) VALUES (?, ?)") for player in players { // Only use the unsafe arguments setter if you are sure that you provide // all statement arguments. A mistake can store unexpected values in @@ -7316,7 +7312,7 @@ try dbQueue.read { db in let sqlRequest = try SQLRequest(db, request: request) print(sqlRequest.sql) - // Prints SELECT * FROM wines WHERE origin = ? ORDER BY price + // Prints SELECT * FROM wine WHERE origin = ? ORDER BY price print(sqlRequest.arguments) // Prints ["Burgundy"] } @@ -7334,7 +7330,7 @@ try dbQueue.read { db in .filter(Column("origin") == "Burgundy") .order(Column("price") .fetchAll(db) - // Prints SELECT * FROM wines WHERE origin = 'Burgundy' ORDER BY price + // Prints SELECT * FROM wine WHERE origin = 'Burgundy' ORDER BY price } ``` From 1bf7f670088af03036af8904e33c1af659cb59bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 20:32:18 +0200 Subject: [PATCH 216/348] Update inline documentation with singular table names --- GRDB/Core/Database+Schema.swift | 28 +++--- GRDB/Core/Database+Statements.swift | 24 ++--- GRDB/Core/Database.swift | 2 +- GRDB/Core/DatabaseCollation.swift | 2 +- GRDB/Core/DatabaseFunction.swift | 4 +- GRDB/Core/DatabasePool.swift | 24 ++--- GRDB/Core/DatabaseQueue.swift | 8 +- GRDB/Core/DatabaseReader.swift | 18 ++-- GRDB/Core/DatabaseRegion.swift | 12 +-- GRDB/Core/DatabaseSnapshot.swift | 2 +- GRDB/Core/DatabaseValueConvertible.swift | 4 +- GRDB/Core/DatabaseWriter.swift | 6 +- GRDB/Core/FetchRequest.swift | 8 +- GRDB/Core/Row.swift | 4 +- GRDB/Core/Statement.swift | 6 +- GRDB/Core/StatementColumnConvertible.swift | 4 +- GRDB/Core/TransactionObserver.swift | 19 ++-- GRDB/FTS/FTS3.swift | 14 +-- GRDB/FTS/FTS3TokenizerDescriptor.swift | 10 +-- GRDB/FTS/FTS4.swift | 26 +++--- GRDB/FTS/FTS5.swift | 18 ++-- GRDB/FTS/FTS5CustomTokenizer.swift | 4 +- GRDB/FTS/FTS5Pattern.swift | 8 +- GRDB/FTS/FTS5TokenizerDescriptor.swift | 10 +-- GRDB/Migration/DatabaseMigrator.swift | 89 ++++++++++--------- .../Association/Association.swift | 3 +- .../Association/ForeignKeyRequest.swift | 1 - .../FTS3+QueryInterfaceRequest.swift | 4 +- GRDB/QueryInterface/FTS5+QueryInterface.swift | 4 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 1 + .../QueryInterfaceRequest+Association.swift | 2 +- .../QueryInterfaceRequest.swift | 48 +++++----- GRDB/QueryInterface/RequestProtocols.swift | 36 ++++---- .../SQLCollatedExpression.swift | 12 +-- .../SQLExpression+QueryInterface.swift | 2 - .../SQLSelectable+QueryInterface.swift | 4 +- .../QueryInterface/Support/SQLOperators.swift | 6 +- GRDB/QueryInterface/TableDefinition.swift | 56 ++++++------ GRDB/QueryInterface/VirtualTableModule.swift | 10 +-- GRDB/Record/FetchableRecord+Decodable.swift | 1 - GRDB/Record/FetchableRecord+TableRecord.swift | 6 +- GRDB/Record/FetchableRecord.swift | 14 +-- GRDB/Record/FetchedRecordsController.swift | 11 ++- GRDB/Record/PersistableRecord.swift | 12 +-- GRDB/Record/Record.swift | 8 +- GRDB/Record/TableRecord.swift | 28 +++--- TODO.md | 1 + 47 files changed, 312 insertions(+), 312 deletions(-) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index fe86b618e..fb0e98d66 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -327,11 +327,11 @@ extension Database { /// This type closely matches the information returned by the /// `table_info` pragma. /// -/// > CREATE TABLE players ( +/// > CREATE TABLE player ( /// id INTEGER PRIMARY KEY, /// firstName TEXT, /// lastName TEXT) -/// > PRAGMA table_info("players") +/// > PRAGMA table_info("player") /// cid name type notnull dflt_value pk /// ---- ----- ------- -------- ---------- --- /// 0 id INTEGER 0 NULL 1 @@ -362,14 +362,14 @@ public struct ColumnInfo : FetchableRecord { /// For example: /// /// try db.execute(""" - /// CREATE TABLE players( + /// CREATE TABLE player( /// id INTEGER PRIMARY KEY, /// name TEXT DEFAULT 'Anonymous', /// score INT DEFAULT 0, /// creationDate DATE DEFAULT CURRENT_TIMESTAMP /// ) /// """) - /// let columnInfos = try db.columns(in: "players") + /// let columnInfos = try db.columns(in: "player") /// columnInfos[0].defaultValueSQL // nil /// columnInfos[1].defaultValueSQL // "'Anoynymous'" /// columnInfos[2].defaultValueSQL // "0" @@ -424,38 +424,38 @@ public struct IndexInfo { /// /// When the table's primary key is the rowid: /// -/// // CREATE TABLE items (name TEXT) -/// let pk = try db.primaryKey("items") +/// // CREATE TABLE item (name TEXT) +/// let pk = try db.primaryKey("item") /// pk.columns // ["rowid"] /// pk.rowIDColumn // nil /// pk.isRowID // true /// -/// // CREATE TABLE citizens ( +/// // CREATE TABLE citizen ( /// // id INTEGER PRIMARY KEY, /// // name TEXT /// // ) -/// let pk = try db.primaryKey("citizens")! +/// let pk = try db.primaryKey("citizen")! /// pk.columns // ["id"] /// pk.rowIDColumn // "id" /// pk.isRowID // true /// /// When the table's primary key is not the rowid: /// -/// // CREATE TABLE countries ( +/// // CREATE TABLE country ( /// // isoCode TEXT NOT NULL PRIMARY KEY /// // name TEXT /// // ) -/// let pk = db.primaryKey("countries")! +/// let pk = db.primaryKey("country")! /// pk.columns // ["isoCode"] /// pk.rowIDColumn // nil /// pk.isRowID // false /// -/// // CREATE TABLE citizenships ( -/// // citizenID INTEGER NOT NULL REFERENCES citizens(id) -/// // countryIsoCode TEXT NOT NULL REFERENCES countries(isoCode) +/// // CREATE TABLE citizenship ( +/// // citizenID INTEGER NOT NULL REFERENCES citizen(id) +/// // countryIsoCode TEXT NOT NULL REFERENCES country(isoCode) /// // PRIMARY KEY (citizenID, countryIsoCode) /// // ) -/// let pk = db.primaryKey("citizenships")! +/// let pk = db.primaryKey("citizenship")! /// pk.columns // ["citizenID", "countryIsoCode"] /// pk.rowIDColumn // nil /// pk.isRowID // false diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 4053f9535..7918fae44 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,12 +1,12 @@ import Foundation extension Database { - + // MARK: - Statements - + /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") + /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -19,7 +19,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?", prepFlags: 0) + /// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0) /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -34,7 +34,7 @@ extension Database { /// Returns a prepared statement that can be reused. /// - /// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") + /// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// @@ -55,7 +55,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)") + /// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -68,7 +68,7 @@ extension Database { /// Returns a new prepared statement that can be reused. /// - /// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)", prepFlags: 0) + /// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0) /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -83,7 +83,7 @@ extension Database { /// Returns a prepared statement that can be reused. /// - /// let statement = try db.cachedUpdateStatement("INSERT INTO players (name) VALUES (?)") + /// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// @@ -105,13 +105,13 @@ extension Database { /// Executes one or several SQL statements, separated by semi-colons. /// /// try db.execute( - /// "INSERT INTO players (name) VALUES (:name)", + /// "INSERT INTO player (name) VALUES (:name)", /// arguments: ["name": "Arthur"]) /// /// try db.execute(""" - /// INSERT INTO players (name) VALUES (?); - /// INSERT INTO players (name) VALUES (?); - /// INSERT INTO players (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); + /// INSERT INTO player (name) VALUES (?); /// """, arguments; ['Arthur', 'Barbara', 'Craig']) /// /// This method may throw a DatabaseError. diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index c93f4841b..cdde29f8b 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -879,7 +879,7 @@ extension Database { /// An SQL column type. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// } diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 41c6520af..432293690 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -16,7 +16,7 @@ public final class DatabaseCollation { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// db.add(collation: collation) - /// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard") /// /// - parameters: /// - name: The function name. diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 5e64eb366..5cf33ea11 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -363,10 +363,10 @@ public protocol DatabaseAggregate { /// aggregate function. /// /// -- One value - /// SELECT maxLength(name) FROM players + /// SELECT maxLength(name) FROM player /// /// -- Two values - /// SELECT maxFullNameLength(firstName, lastName) FROM players + /// SELECT maxFullNameLength(firstName, lastName) FROM player /// /// This method is never called after the finalize() method has been called. mutating func step(_ dbValues: [DatabaseValue]) throws diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 5d650d89a..29dee73e4 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -224,14 +224,14 @@ extension DatabasePool : DatabaseReader { /// /// try dbPool.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `wines` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// // `wine` table is modified between the two requests: + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// try dbPool.read { db in /// // Now this value may be different: - /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// This method is *not* reentrant. @@ -266,8 +266,8 @@ extension DatabasePool : DatabaseReader { /// try dbPool.unsafeRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iteration is safe, though: @@ -303,8 +303,8 @@ extension DatabasePool : DatabaseReader { /// try dbPool.unsafeReentrantRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iteration is safe, though: @@ -346,12 +346,12 @@ extension DatabasePool : DatabaseReader { /// database updates are *not visible* inside the block. /// /// try dbPool.write { db in - /// try db.execute("DELETE FROM players") + /// try db.execute("DELETE FROM player") /// try dbPool.readFromCurrentState { db in /// // Guaranteed to be zero - /// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + /// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! /// } - /// try db.execute("INSERT INTO players ...") + /// try db.execute("INSERT INTO player ...") /// } /// /// This method blocks the current thread until the isolation guarantee has @@ -611,7 +611,7 @@ extension DatabasePool : DatabaseReader { /// } /// dbPool.add(collation: collation) /// try dbPool.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { collations.update(with: collation) diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index fac705911..600ed95c5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -10,7 +10,7 @@ public final class DatabaseQueue: DatabaseWriter { #if os(iOS) private weak var application: UIApplication? #endif - + // MARK: - Configuration /// The database configuration @@ -291,7 +291,7 @@ extension DatabaseQueue { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// // INSERT INTO players ... + /// // INSERT INTO player ... /// let players = try dbQueue.inDatabase { db in /// try Player(...).insert(db) /// } @@ -307,7 +307,7 @@ extension DatabaseQueue { /// Synchronously executes a block in a protected dispatch queue, and /// returns its result. /// - /// // INSERT INTO players ... + /// // INSERT INTO player ... /// try dbQueue.unsafeReentrantWrite { db in /// try Player(...).insert(db) /// } @@ -350,7 +350,7 @@ extension DatabaseQueue { /// } /// dbQueue.add(collation: collation) /// try dbQueue.write { db in - /// try db.execute("CREATE TABLE files (name TEXT COLLATE LOCALIZED_STANDARD") + /// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD") /// } public func add(collation: DatabaseCollation) { writer.sync { $0.add(collation: collation) } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5a33d8f20..b3222c6f0 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -31,14 +31,14 @@ public protocol DatabaseReader : class { /// /// try reader.read { db in /// // Those two values are guaranteed to be equal, even if the - /// // `wines` table is modified between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// // `wine` table is modified between the two requests: + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// try reader.read { db in /// // Now this value may be different: - /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds @@ -61,8 +61,8 @@ public protocol DatabaseReader : class { /// try reader.unsafeRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iterations are isolated, though: @@ -92,8 +92,8 @@ public protocol DatabaseReader : class { /// try reader.unsafeReentrantRead { db in /// // Those two values may be different because some other thread /// // may have inserted or deleted a wine between the two requests: - /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! - /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")! + /// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! + /// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")! /// } /// /// Cursor iterations are isolated, though: @@ -144,7 +144,7 @@ public protocol DatabaseReader : class { /// return (string1 as NSString).localizedStandardCompare(string2) /// } /// reader.add(collation: collation) - /// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard") + /// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard") func add(collation: DatabaseCollation) /// Remove a collation. diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 99a2d092a..b1e7383ec 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -18,27 +18,27 @@ /// /// - `SelectStatement.fetchedRegion`: /// -/// let statement = db.makeSelectStatement("SELECT name, score FROM players") +/// let statement = db.makeSelectStatement("SELECT name, score FROM player") /// print(statement.fetchedRegion) -/// // prints "players(name,score)" +/// // prints "player(name,score)" /// /// - `Request.fetchedRegion(_:)` /// /// let request = Player.filter(key: 1) /// try print(request.fetchedRegion(db)) -/// // prints "players(*)[1]" +/// // prints "player(*)[1]" /// /// Database regions returned by requests can be more precise than regions /// returned by select statements. Especially, regions returned by statements /// don't know about rowids: /// /// // A plain statement -/// let statement = db.makeSelectStatement("SELECT * FROM players WHERE id = 1") -/// statement.fetchedRegion // "players(*)" +/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1") +/// statement.fetchedRegion // "player(*)" /// /// // A query interface request that executes the same statement: /// let request = Player.filter(key: 1) -/// try request.fetchedRegion(db) // "players(*)[1]" +/// try request.fetchedRegion(db) // "player(*)[1]" public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? private init(tableRegions: [String: TableRegion]?) { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 0a949573f..35bed7e2c 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -110,7 +110,7 @@ extension DatabaseSnapshot { /// } /// snapshot.add(collation: collation) /// let files = try snapshot.read { db in - /// try File.fetchAll(db, "SELECT * FROM files ORDER BY name COLLATE localized_standard") + /// try File.fetchAll(db, "SELECT * FROM file ORDER BY name COLLATE localized_standard") /// } public func add(collation: DatabaseCollation) { serializedDatabase.sync { $0.add(collation: collation) } diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index eb951b785..e5e35095b 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -42,7 +42,7 @@ extension DatabaseValueConvertible { /// For example: /// /// try dbQueue.read { db in -/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM links") +/// let urls: DatabaseValueCursor = try URL.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL /// print(url) /// } @@ -82,7 +82,7 @@ public final class DatabaseValueCursor : Cursor /// For example: /// /// try dbQueue.read { db in -/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM links") +/// let urls: NullableDatabaseValueCursor = try Optional.fetchCursor(db, "SELECT url FROM link") /// while let url = urls.next() { // URL? /// print(url) /// } diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index a9d308d30..d60a88c93 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -73,12 +73,12 @@ public protocol DatabaseWriter : DatabaseReader { /// For example: /// /// try writer.write { db in - /// try db.execute("DELETE FROM players") + /// try db.execute("DELETE FROM player") /// try writer.readFromCurrentState { db in /// // Guaranteed to be zero - /// try Int.fetchOne(db, "SELECT COUNT(*) FROM players")! + /// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")! /// } - /// try db.execute("INSERT INTO players ...") + /// try db.execute("INSERT INTO player ...") /// } func readFromCurrentState(_ block: @escaping (Database) -> Void) throws } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index bcea72d7e..cd03312c3 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -185,8 +185,8 @@ public struct SQLRequest : FetchRequest { /// Creates a request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. @@ -215,8 +215,8 @@ public struct SQLRequest : FetchRequest { /// Creates an SQL request from an SQL string, optional arguments, and /// optional row adapter. /// - /// let request = SQLRequest("SELECT * FROM players") - /// let request = SQLRequest("SELECT * FROM players WHERE id = ?", arguments: [1]) + /// let request = SQLRequest("SELECT * FROM player") + /// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1]) /// /// - parameters: /// - sql: An SQL query. diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 242637cd5..5c385ec99 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -583,7 +583,7 @@ extension Row { /// A cursor of database rows. For example: /// /// try dbQueue.read { db in -/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM players") +/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player") /// } public final class RowCursor : Cursor { public let statement: SelectStatement @@ -690,7 +690,7 @@ extension Row { /// Returns a cursor over rows fetched from an SQL query. /// - /// let rows = try Row.fetchCursor(db, "SELECT id, name FROM players") // RowCursor + /// let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor /// while let row = try rows.next() { // Row /// let id: Int64 = row[0] /// let name: String = row[1] diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 2c3a6d773..092b3e623 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -289,7 +289,7 @@ extension AuthorizedStatement { /// You create SelectStatement with the Database.makeSelectStatement() method: /// /// try dbQueue.read { db in -/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM players WHERE score > ?") +/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?") /// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])! /// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])! /// } @@ -375,7 +375,7 @@ extension SelectStatement: AuthorizedStatement { } /// For example: /// /// try dbQueue.read { db in -/// let statement = db.makeSelectStatement("SELECT * FROM players") +/// let statement = db.makeSelectStatement("SELECT * FROM player") /// let cursor: StatementCursor = statement.cursor() /// } public final class StatementCursor: Cursor { @@ -414,7 +414,7 @@ public final class StatementCursor: Cursor { /// You create UpdateStatement with the Database.makeUpdateStatement() method: /// /// try dbQueue.inTransaction { db in -/// let statement = try db.makeUpdateStatement("INSERT INTO players (name) VALUES (?)") +/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)") /// try statement.execute(arguments: ["Arthur"]) /// try statement.execute(arguments: ["Barbara"]) /// return .commit diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index 2a1dc14e7..fa7ef5446 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -75,7 +75,7 @@ extension StatementColumnConvertible { /// For example: /// /// try dbQueue.read { db in -/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM players") +/// let names: ColumnCursor = try String.fetchCursor(db, "SELECT name FROM player") /// while let name = names.next() { // String /// print(name) /// } @@ -121,7 +121,7 @@ public final class ColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM players") +/// let emails: NullableColumnCursor = try Optional.fetchCursor(db, "SELECT email FROM player") /// while let email = emails.next() { // String? /// print(email ?? "") /// } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index f27921111..0b50b9f80 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -29,13 +29,12 @@ extension Database { /// Registers a closure to be executed after the next or current /// transaction completion. /// - /// dbQueue.inTransaction { db in + /// try dbQueue.write { db in /// db.afterNextTransactionCommit { _ in - /// print("commit did succeed") + /// print("success") /// } /// ... - /// return .commit // prints "commit did succeed" - /// } + /// } // prints "success" /// /// If the transaction is rollbacked, the closure is not executed. /// @@ -100,11 +99,11 @@ extension Database { /// /// Then a statement is executed: /// -/// try db.execute("INSERT INTO documents ...") +/// try db.execute("INSERT INTO document ...") /// /// The observation process starts when the statement is *compiled*: /// sqlite3_set_authorizer tells that the statement performs insertion into the -/// `documents` table. Generally speaking, statements may have many effects, by +/// `document` table. Generally speaking, statements may have many effects, by /// the mean of foreign key actions and SQL triggers. SQLite takes care of /// exposing all those effects to sqlite3_set_authorizer. /// @@ -129,7 +128,7 @@ extension Database { /// /// Then another statement is executed: /// -/// try db.execute("INSERT INTO documents ...") +/// try db.execute("INSERT INTO document ...") /// /// This time, when the statement is *executed* and SQLite tells that a row has /// been inserted, the broker buffers the change event instead of immediately @@ -738,14 +737,14 @@ extension TransactionObserver { /// For example: /// /// class PlayerObserver: TransactionObserver { - /// var playersTableWasModified = false + /// var playerTableWasModified = false /// /// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { - /// return eventKind.tableName == "players" + /// return eventKind.tableName == "player" /// } /// /// func databaseDidChange(with event: DatabaseEvent) { - /// playersTableWasModified = true + /// playerTableWasModified = true /// /// // It is pointless to keep on tracking further changes: /// stopObservingDatabaseChangesUntilNextTransaction() diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 6e2e06ff8..5098d5967 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -1,15 +1,15 @@ /// FTS3 lets you define "fts3" virtual tables. /// -/// // CREATE VIRTUAL TABLE documents USING fts3(content) -/// try db.create(virtualTable: "documents", using: FTS3()) { t in +/// // CREATE VIRTUAL TABLE document USING fts3(content) +/// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } public struct FTS3 : VirtualTableModule { /// Creates a FTS3 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts3(content) - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// // CREATE VIRTUAL TABLE document USING fts3(content) + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } public init() { @@ -54,7 +54,7 @@ public struct FTS3 : VirtualTableModule { /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// -/// try db.create(virtualTable: "documents", using: FTS3()) { t in // t is FTS3TableDefinition +/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition /// t.column("content") /// } public final class FTS3TableDefinition { @@ -62,7 +62,7 @@ public final class FTS3TableDefinition { /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.tokenizer = .porter /// } /// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables @@ -70,7 +70,7 @@ public final class FTS3TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS3()) { t in + /// try db.create(virtualTable: "document", using: FTS3()) { t in /// t.column("content") /// } /// diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index d4387dd07..24ce4fff9 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -1,6 +1,6 @@ /// An FTS3 tokenizer, suitable for FTS3 and FTS4 table definitions: /// -/// db.create(virtualTable: "books", using: FTS4()) { t in +/// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple // FTS3TokenizerDescriptor /// } /// @@ -16,7 +16,7 @@ public struct FTS3TokenizerDescriptor { /// The "simple" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .simple /// } /// @@ -25,7 +25,7 @@ public struct FTS3TokenizerDescriptor { /// The "porter" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .porter /// } /// @@ -35,7 +35,7 @@ public struct FTS3TokenizerDescriptor { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// The "unicode61" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .unicode61() /// } /// @@ -54,7 +54,7 @@ public struct FTS3TokenizerDescriptor { #else /// The "unicode61" tokenizer. /// - /// db.create(virtualTable: "books", using: FTS4()) { t in + /// db.create(virtualTable: "book", using: FTS4()) { t in /// t.tokenizer = .unicode61() /// } /// diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index 7fea3dc75..fded83706 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -1,7 +1,7 @@ /// FTS4 lets you define "fts4" virtual tables. /// -/// // CREATE VIRTUAL TABLE documents USING fts4(content) -/// try db.create(virtualTable: "documents", using: FTS4()) { t in +/// // CREATE VIRTUAL TABLE document USING fts4(content) +/// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -11,8 +11,8 @@ public struct FTS4 : VirtualTableModule { /// Creates a FTS4 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts4(content) - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// // CREATE VIRTUAL TABLE document USING fts4(content) + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -137,7 +137,7 @@ public struct FTS4 : VirtualTableModule { /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// -/// try db.create(virtualTable: "documents", using: FTS4()) { t in // t is FTS4TableDefinition +/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition /// t.column("content") /// } /// @@ -153,7 +153,7 @@ public final class FTS4TableDefinition { /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.tokenizer = .porter /// } /// @@ -201,8 +201,8 @@ public final class FTS4TableDefinition { /// Support for the FTS5 `prefix` option /// - /// // CREATE VIRTUAL TABLE documents USING FTS4(content, prefix='2 4'); - /// db.create(virtualTable: "documents", using:FTS4()) { t in + /// // CREATE VIRTUAL TABLE document USING FTS4(content, prefix='2 4'); + /// db.create(virtualTable: "document", using:FTS4()) { t in /// t.prefixes = [2, 4] /// t.column("content") /// } @@ -212,7 +212,7 @@ public final class FTS4TableDefinition { /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") /// } /// @@ -242,7 +242,7 @@ public final class FTS4TableDefinition { /// /// You get instances of this class when you create an FTS4 table: /// -/// try db.create(virtualTable: "documents", using: FTS4()) { t in +/// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("content") // FTS4ColumnDefinition /// } /// @@ -261,7 +261,7 @@ public final class FTS4ColumnDefinition { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } @@ -280,7 +280,7 @@ public final class FTS4ColumnDefinition { #else /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } @@ -300,7 +300,7 @@ public final class FTS4ColumnDefinition { /// Uses the column as the Int32 language id hidden column. /// - /// try db.create(virtualTable: "documents", using: FTS4()) { t in + /// try db.create(virtualTable: "document", using: FTS4()) { t in /// t.column("a") /// t.column("lid").asLanguageId() /// } diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index 5dcf53824..2af8a6da0 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,8 +1,8 @@ #if SQLITE_ENABLE_FTS5 /// FTS5 lets you define "fts5" virtual tables. /// - /// // CREATE VIRTUAL TABLE documents USING fts5(content) - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -12,8 +12,8 @@ /// Creates a FTS5 module suitable for the Database /// `create(virtualTable:using:)` method. /// - /// // CREATE VIRTUAL TABLE documents USING fts5(content) - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// // CREATE VIRTUAL TABLE document USING fts5(content) + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -156,7 +156,7 @@ /// You don't create instances of this class. Instead, you use the Database /// `create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in // t is FTS5TableDefinition + /// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition /// t.column("content") /// } /// @@ -172,7 +172,7 @@ /// The virtual table tokenizer /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// @@ -254,7 +254,7 @@ /// Appends a table column. /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") /// } /// @@ -284,7 +284,7 @@ /// /// You get instances of this class when you create an FTS5 table: /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("content") // FTS5ColumnDefinition /// } /// @@ -300,7 +300,7 @@ /// Excludes the column from the full-text index. /// - /// try db.create(virtualTable: "documents", using: FTS5()) { t in + /// try db.create(virtualTable: "document", using: FTS5()) { t in /// t.column("a") /// t.column("b").notIndexed() /// } diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index eea47f9bb..fb604300b 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -11,7 +11,7 @@ /// VIRTUAL TABLE statement. In the example below, the arguments will /// be `["arg1", "arg2"]`. /// - /// CREATE VIRTUAL TABLE documents USING fts5( + /// CREATE VIRTUAL TABLE document USING fts5( /// tokenize='custom arg1 arg2' /// ) /// @@ -26,7 +26,7 @@ /// /// class MyTokenizer : FTS5CustomTokenizer { ... } /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"]) /// t.tokenizer = tokenizer /// } diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 1e7231990..ca94574c6 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -65,7 +65,7 @@ // that pattern. do { try DatabaseQueue().inDatabase { db in - try db.create(virtualTable: "documents", using: FTS5()) { t in + try db.create(virtualTable: "document", using: FTS5()) { t in if allowedColumns.isEmpty { t.column("__grdb__") } else { @@ -74,7 +74,7 @@ } } } - try db.makeSelectStatement("SELECT * FROM documents WHERE documents MATCH ?") + try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?") .cursor(arguments: [rawPattern]) .next() // error on next() for invalid patterns } @@ -97,8 +97,8 @@ /// /// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax /// - /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "documents") // OK - /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "documents") // malformed MATCH expression: [AND] + /// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK + /// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND] public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern { return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name }) } diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 9752d9dd0..95c0e0431 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -1,7 +1,7 @@ #if SQLITE_ENABLE_FTS5 /// An FTS5 tokenizer, suitable for FTS5 table definitions: /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor /// } /// @@ -33,7 +33,7 @@ /// Creates an FTS5 tokenizer descriptor. /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"]) /// t.tokenizer = tokenizer /// } @@ -47,7 +47,7 @@ /// The "ascii" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .ascii() /// } /// @@ -66,7 +66,7 @@ /// The "porter" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .porter() /// } /// @@ -85,7 +85,7 @@ /// An "unicode61" tokenizer /// - /// db.create(virtualTable: "books", using: FTS5()) { t in + /// db.create(virtualTable: "book", using: FTS5()) { t in /// t.tokenizer = .unicode61() /// } /// diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index 7e8ba9b1a..00f0100ab 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -9,34 +9,37 @@ /// /// var migrator = DatabaseMigrator() /// -/// // v1.0 database -/// migrator.registerMigration("createAuthors") { db in -/// try db.execute(""" -/// CREATE TABLE authors ( -/// id INTEGER PRIMARY KEY, -/// creationDate TEXT, -/// name TEXT NOT NULL -/// ) -/// """) +/// // 1st migration +/// migrator.registerMigration("createLibrary") { db in +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("creationDate", .datetime) +/// t.column("name", .text).notNull() +/// } +/// +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) +/// .notNull() +/// .references("author", onDelete: .cascade) +/// t.column("title", .text).notNull() +/// } /// } /// -/// migrator.registerMigration("createBooks") { db in -/// try db.execute(""" -/// CREATE TABLE books ( -/// uuid TEXT PRIMARY KEY, -/// authorID INTEGER NOT NULL -/// REFERENCES authors(id) -/// ON DELETE CASCADE ON UPDATE CASCADE, -/// title TEXT NOT NULL -/// ) -/// """) -/// } -/// -/// // v2.0 database +/// // 2nd migration /// migrator.registerMigration("AddBirthYearToAuthors") { db in -/// try db.execute("ALTER TABLE authors ADD COLUMN birthYear INT") +/// try db.alter(table: "author") { t +/// t.add(column: "birthYear", .integer) +/// } /// } /// +/// // Migrations for future versions will be inserted here: +/// // +/// // // 3rd migration +/// // migrator.registerMigration("...") { db in +/// // ... +/// // } +/// /// try migrator.migrate(dbQueue) public struct DatabaseMigrator { @@ -46,14 +49,12 @@ public struct DatabaseMigrator { /// Registers a migration. /// - /// migrator.registerMigration("createPlayers") { db in - /// try db.execute(""" - /// CREATE TABLE players ( - /// id INTEGER PRIMARY KEY, - /// creationDate TEXT, - /// name TEXT NOT NULL - /// ) - /// """) + /// migrator.registerMigration("createAuthors") { db in + /// try db.create(table: "author") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("creationDate", .datetime) + /// t.column("name", .text).notNull() + /// } /// } /// /// - parameters: @@ -69,12 +70,13 @@ public struct DatabaseMigrator { /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.execute(""" - /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); - /// INSERT INTO new_players SELECT * FROM players; - /// DROP TABLE players; - /// ALTER TABLE new_players RENAME TO players; - /// """) + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute("INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") /// } /// /// While your migration code runs with disabled foreign key checks, those @@ -96,12 +98,13 @@ public struct DatabaseMigrator { /// /// // Add a NOT NULL constraint on players.name: /// migrator.registerMigrationWithDeferredForeignKeyCheck("AddNotNullCheckOnName") { db in - /// try db.execute(""" - /// CREATE TABLE new_players (id INTEGER PRIMARY KEY, name TEXT NOT NULL); - /// INSERT INTO new_players SELECT * FROM players; - /// DROP TABLE players; - /// ALTER TABLE new_players RENAME TO players; - /// """) + /// try db.create(table: "new_player") { t in + /// t.autoIncrementedPrimaryKey("id") + /// t.column("name", .text).notNull() + /// } + /// try db.execute("INSERT INTO new_player SELECT * FROM player") + /// try db.drop(table: "player") + /// try db.rename(table: "new_player", to: "player") /// } /// /// While your migration code runs with disabled foreign key checks, those diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index bd94d6551..8023699f2 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -48,6 +48,7 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { /// } func forKey(_ key: String) -> Self + // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: var request: AssociationRequest { get } @@ -271,7 +272,7 @@ extension Association where LeftAssociated: MutablePersistableRecord { /// For example: /// /// struct Team: { - /// static let players = hasMany(Book.self) + /// static let players = hasMany(Player.self) /// var players: QueryInterfaceRequest { /// return request(for: Team.players) /// } diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift index a7fb3a325..014c07b8c 100644 --- a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -80,7 +80,6 @@ struct ForeignKeyRequest { } } - /// The (origin, destination) column pairs that join a left table to a right table. /// :nodoc: typealias ForeignKeyMapping = [(origin: String, destination: String)] diff --git a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift index 8370c844f..0c1d56aaa 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterfaceRequest.swift @@ -5,7 +5,7 @@ extension QueryInterfaceRequest { /// Creates a request with a full-text predicate added to the eventual /// set of already applied predicates. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.all() /// request = request.matching(pattern) /// @@ -28,7 +28,7 @@ extension TableRecord { /// Returns a QueryInterfaceRequest with a matching predicate. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.matching(pattern) /// /// If the search pattern is nil, the request does not match any diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index 3fb0005b3..2affcfe44 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -6,7 +6,7 @@ /// Creates a request with a full-text predicate added to the eventual /// set of already applied predicates. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.all() /// request = request.matching(pattern) /// @@ -33,7 +33,7 @@ /// Returns a QueryInterfaceRequest with a matching predicate. /// - /// // SELECT * FROM books WHERE books MATCH '...' + /// // SELECT * FROM book WHERE book MATCH '...' /// var request = Book.matching(pattern) /// /// If the search pattern is nil, the request does not match any diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index dcb675dec..1eb8ec312 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -216,6 +216,7 @@ extension QueryInterfaceQuery { } extension QueryInterfaceQuery { + /// precondition: self is the result of finalizedQuery func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String { var sql = "SELECT" diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 7b4fc8073..32dafae77 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -48,7 +48,7 @@ extension MutablePersistableRecord { /// For example: /// /// struct Team: { - /// static let players = hasMany(Book.self) + /// static let players = hasMany(Player.self) /// var players: QueryInterfaceRequest { /// return request(for: Team.players) /// } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 9cfa76eb5..38ab39e52 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -49,13 +49,13 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select([Column("id"), Column("email")]) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select([Column("id")]) /// .select([Column("email")]) @@ -65,11 +65,11 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request which returns distinct rows. /// - /// // SELECT DISTINCT * FROM players + /// // SELECT DISTINCT * FROM player /// var request = Player.all() /// request = request.distinct() /// - /// // SELECT DISTINCT name FROM players + /// // SELECT DISTINCT name FROM player /// var request = Player.select(Column("name")) /// request = request.distinct() public func distinct() -> QueryInterfaceRequest { @@ -79,7 +79,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE 1 + /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest { @@ -99,13 +99,13 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order([Column("name")]) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order([Column("email")]) /// .reversed() @@ -116,13 +116,13 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM players ORDER BY name DESC + /// // SELECT * FROM player ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() /// /// If no ordering was applied, the returned request is identical. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() public func reversed() -> QueryInterfaceRequest { @@ -131,7 +131,7 @@ extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, Aggregating /// Creates a request which fetches *limit* rows, starting at *offset*. /// - /// // SELECT * FROM players LIMIT 1 + /// // SELECT * FROM player LIMIT 1 /// var request = Player.all() /// request = request.limit(1) /// @@ -214,7 +214,7 @@ extension TableRecord { /// Creates a request which fetches all records. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let request = Player.all() /// /// The selection defaults to all columns. This default can be changed for @@ -234,7 +234,7 @@ extension TableRecord { /// Creates a request which selects *selection*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select(Column("id"), Column("email")) public static func select(_ selection: SQLSelectable...) -> QueryInterfaceRequest { return all().select(selection) @@ -242,7 +242,7 @@ extension TableRecord { /// Creates a request which selects *selection*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select([Column("id"), Column("email")]) public static func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest { return all().select(selection) @@ -250,7 +250,7 @@ extension TableRecord { /// Creates a request which selects *sql*. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// let request = Player.select(sql: "id, email") public static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest { return all().select(sql: sql, arguments: arguments) @@ -258,7 +258,7 @@ extension TableRecord { /// Creates a request with the provided *predicate*. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(Column("email") == "arthur@example.com") /// /// The selection defaults to all columns. This default can be changed for @@ -270,7 +270,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id = 1 + /// // SELECT * FROM player WHERE id = 1 /// let request = Player.filter(key: 1) /// /// The selection defaults to all columns. This default can be changed for @@ -282,7 +282,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM players WHERE id IN (1, 2, 3) + /// // SELECT * FROM player WHERE id IN (1, 2, 3) /// let request = Player.filter(keys: [1, 2, 3]) /// /// The selection defaults to all columns. This default can be changed for @@ -294,7 +294,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM passports WHERE personId = 1 AND countryCode = 'FR' + /// // SELECT * FROM passport WHERE personId = 1 AND countryCode = 'FR' /// let request = Passport.filter(key: ["personId": 1, "countryCode": "FR"]) /// /// When executed, this request raises a fatal error if there is no unique @@ -309,7 +309,7 @@ extension TableRecord { /// Creates a request with the provided primary key *predicate*. /// - /// // SELECT * FROM passports WHERE (personId = 1 AND countryCode = 'FR') OR ... + /// // SELECT * FROM passport WHERE (personId = 1 AND countryCode = 'FR') OR ... /// let request = Passport.filter(keys: [["personId": 1, "countryCode": "FR"], ...]) /// /// When executed, this request raises a fatal error if there is no unique @@ -324,7 +324,7 @@ extension TableRecord { /// Creates a request with the provided *predicate*. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// let request = Player.filter(sql: "email = ?", arguments: ["arthur@example.com"]) /// /// The selection defaults to all columns. This default can be changed for @@ -337,7 +337,7 @@ extension TableRecord { /// Creates a request sorted according to the /// provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order(Column("name")) /// /// The selection defaults to all columns. This default can be changed for @@ -350,7 +350,7 @@ extension TableRecord { /// Creates a request sorted according to the /// provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order([Column("name")]) /// /// The selection defaults to all columns. This default can be changed for @@ -362,7 +362,7 @@ extension TableRecord { /// Creates a request sorted according to *sql*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// let request = Player.order(sql: "name") /// /// The selection defaults to all columns. This default can be changed for @@ -375,7 +375,7 @@ extension TableRecord { /// Creates a request which fetches *limit* rows, starting at /// *offset*. /// - /// // SELECT * FROM players LIMIT 1 + /// // SELECT * FROM player LIMIT 1 /// let request = Player.limit(1) /// /// The selection defaults to all columns. This default can be changed for diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index cb05debc5..8ae46b0a4 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -4,13 +4,13 @@ public protocol SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select([Column("id"), Column("email")]) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select([Column("id")]) /// .select([Column("email")]) @@ -20,13 +20,13 @@ public protocol SelectionRequest { extension SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select(Column("id"), Column("email")) /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select(Column("id")) /// .select(Column("email")) @@ -36,13 +36,13 @@ extension SelectionRequest { /// Creates a request with a new net of selected columns. /// - /// // SELECT id, email FROM players + /// // SELECT id, email FROM player /// var request = Player.all() /// request = request.select(sql: "id, email") /// /// Any previous selection is replaced: /// - /// // SELECT email FROM players + /// // SELECT email FROM player /// request /// .select(sql: "id") /// .select(sql: "email") @@ -58,7 +58,7 @@ public protocol FilteredRequest { /// Creates a request with the provided *predicate promise* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE 1 + /// // SELECT * FROM player WHERE 1 /// var request = Player.all() /// request = request.filter { db in true } func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self @@ -68,7 +68,7 @@ extension FilteredRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// var request = Player.all() /// request = request.filter(Column("email") == "arthur@example.com") public func filter(_ predicate: SQLExpressible) -> Self { @@ -78,7 +78,7 @@ extension FilteredRequest { /// Creates a request with the provided *predicate* added to the /// eventual set of already applied predicates. /// - /// // SELECT * FROM players WHERE email = 'arthur@example.com' + /// // SELECT * FROM player WHERE email = 'arthur@example.com' /// var request = Player.all() /// request = request.filter(sql: "email = ?", arguments: ["arthur@example.com"]) public func filter(sql: String, arguments: StatementArguments? = nil) -> Self { @@ -87,7 +87,7 @@ extension FilteredRequest { /// Creates a request that matches nothing. /// - /// // SELECT * FROM players WHERE 0 + /// // SELECT * FROM player WHERE 0 /// var request = Player.all() /// request = request.none() public func none() -> Self { @@ -248,13 +248,13 @@ extension AggregatingRequest { public protocol OrderedRequest { /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order([Column("name")]) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order([Column("email")]) /// .reversed() @@ -263,13 +263,13 @@ public protocol OrderedRequest { /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM players ORDER BY name DESC + /// // SELECT * FROM player ORDER BY name DESC /// var request = Player.all().order(Column("name")) /// request = request.reversed() /// /// If no ordering was applied, the returned request is identical. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// var request = Player.all() /// request = request.reversed() func reversed() -> Self @@ -278,13 +278,13 @@ public protocol OrderedRequest { extension OrderedRequest { /// Creates a request with the provided *orderings*. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order(Column("name")) /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order(Column("email")) /// .reversed() @@ -295,13 +295,13 @@ extension OrderedRequest { /// Creates a request with the provided *sql* used for sorting. /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// var request = Player.all() /// request = request.order(sql: "name") /// /// Any previous ordering is replaced: /// - /// // SELECT * FROM players ORDER BY name + /// // SELECT * FROM player ORDER BY name /// request /// .order(sql: "email") /// .order(sql: "name") diff --git a/GRDB/QueryInterface/SQLCollatedExpression.swift b/GRDB/QueryInterface/SQLCollatedExpression.swift index 9bd319b8c..d56036c13 100644 --- a/GRDB/QueryInterface/SQLCollatedExpression.swift +++ b/GRDB/QueryInterface/SQLCollatedExpression.swift @@ -5,8 +5,8 @@ /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// -/// // SELECT * FROM players WHERE email = 'arthur@example.com' COLLATE NOCASE -/// Players.filter(email == "arthur@example.com") +/// // SELECT * FROM player WHERE email = 'arthur@example.com' COLLATE NOCASE +/// Player.filter(email == "arthur@example.com") public struct SQLCollatedExpression { /// The tainted expression public let expression: SQLExpression @@ -18,8 +18,8 @@ public struct SQLCollatedExpression { /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// - /// // SELECT * FROM players ORDER BY email COLLATE NOCASE ASC - /// Players.order(email.asc) + /// // SELECT * FROM player ORDER BY email COLLATE NOCASE ASC + /// Player.order(email.asc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var asc: SQLOrderingTerm { @@ -30,8 +30,8 @@ public struct SQLCollatedExpression { /// /// let email: SQLCollatedExpression = Column("email").collating(.nocase) /// - /// // SELECT * FROM players ORDER BY email COLLATE NOCASE DESC - /// Players.order(email.desc) + /// // SELECT * FROM player ORDER BY email COLLATE NOCASE DESC + /// Player.order(email.desc) /// /// See https://github.com/groue/GRDB.swift/#the-query-interface public var desc: SQLOrderingTerm { diff --git a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift index 96b22ad5a..9cf63ab84 100644 --- a/GRDB/QueryInterface/SQLExpression+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLExpression+QueryInterface.swift @@ -142,8 +142,6 @@ public struct SQLUnaryOperator : Hashable { /// SQLExpressionUnary is an expression made of an unary operator and /// an operand expression. /// -/// SQLExpressionUnary(.not, Column("favorite")) -/// /// :nodoc: public struct SQLExpressionUnary : SQLExpression { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) diff --git a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift index 9c9817244..411b88829 100644 --- a/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLSelectable+QueryInterface.swift @@ -8,11 +8,11 @@ /// For example: /// /// struct Player : TableRecord { -/// static var databaseTableName = "players" +/// static var databaseTableName = "player" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } /// -/// // SELECT *, rowid FROM players +/// // SELECT *, rowid FROM player /// let request = Player.all() public struct AllColumns { public init() { } diff --git a/GRDB/QueryInterface/Support/SQLOperators.swift b/GRDB/QueryInterface/Support/SQLOperators.swift index a333f30b7..0dd16b0f2 100644 --- a/GRDB/QueryInterface/Support/SQLOperators.swift +++ b/GRDB/QueryInterface/Support/SQLOperators.swift @@ -754,7 +754,7 @@ extension Sequence where Element == SQLExpression { /// /// For example: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// // WHERE (registered /// // AND (score >= 1000) /// // AND (name IS NOT NULL)) @@ -767,10 +767,10 @@ extension Sequence where Element == SQLExpression { /// When the sequence is empty, `joined(operator: .and)` returns true, /// and `joined(operator: .or)` returns false: /// - /// // SELECT * FROM players WHERE 1 + /// // SELECT * FROM player WHERE 1 /// Player.filter([].joined(operator: .and)) /// - /// // SELECT * FROM players WHERE 0 + /// // SELECT * FROM player WHERE 0 /// Player.filter([].joined(operator: .or)) public func joined(operator: SQLLogicalBinaryOperator) -> SQLExpression { let expressions = Array(self) diff --git a/GRDB/QueryInterface/TableDefinition.swift b/GRDB/QueryInterface/TableDefinition.swift index 1602b707e..ca8b231df 100644 --- a/GRDB/QueryInterface/TableDefinition.swift +++ b/GRDB/QueryInterface/TableDefinition.swift @@ -5,7 +5,7 @@ extension Database { #if GRDBCUSTOMSQLITE || GRDBCIPHER /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -34,7 +34,7 @@ extension Database { #else /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -66,7 +66,7 @@ extension Database { /// Creates a database table. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("title", .text) /// t.column("favorite", .boolean).notNull().default(false) @@ -103,7 +103,7 @@ extension Database { /// Modifies a database table. /// - /// try db.alter(table: "players") { t in + /// try db.alter(table: "player") { t in /// t.add(column: "url", .text) /// } /// @@ -223,7 +223,7 @@ extension Database { /// You don't create instances of this class. Instead, you use the Database /// `create(table:)` method: /// -/// try db.create(table: "players") { t in // t is TableDefinition +/// try db.create(table: "player") { t in // t is TableDefinition /// t.column(...) /// } /// @@ -250,7 +250,7 @@ public final class TableDefinition { /// Defines the auto-incremented primary key. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// } /// @@ -282,7 +282,7 @@ public final class TableDefinition { /// Appends a table column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text) /// } /// @@ -301,7 +301,7 @@ public final class TableDefinition { /// Defines the table primary key. /// - /// try db.create(table: "citizenships") { t in + /// try db.create(table: "citizenship") { t in /// t.column("citizenID", .integer) /// t.column("countryCode", .text) /// t.primaryKey(["citizenID", "countryCode"]) @@ -323,7 +323,7 @@ public final class TableDefinition { /// Adds a unique key. /// - /// try db.create(table: "pointOfInterests") { t in + /// try db.create(table: "place") { t in /// t.column("latitude", .double) /// t.column("longitude", .double) /// t.uniqueKey(["latitude", "longitude"]) @@ -344,7 +344,7 @@ public final class TableDefinition { /// t.column("issueDate", .date) /// t.column("citizenID", .integer) /// t.column("countryCode", .text) - /// t.foreignKey(["citizenID", "countryCode"], references: "citizenships", onDelete: .cascade) + /// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade) /// } /// /// See https://www.sqlite.org/foreignkeys.html @@ -365,7 +365,7 @@ public final class TableDefinition { /// Adds a CHECK constraint. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("personalPhone", .text) /// t.column("workPhone", .text) /// let personalPhone = Column("personalPhone") @@ -382,7 +382,7 @@ public final class TableDefinition { /// Adds a CHECK constraint. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("personalPhone", .text) /// t.column("workPhone", .text) /// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL") @@ -509,7 +509,7 @@ public final class TableDefinition { /// You don't create instances of this class. Instead, you use the Database /// `alter(table:)` method: /// -/// try db.alter(table: "players") { t in // t is TableAlteration +/// try db.alter(table: "player") { t in // t is TableAlteration /// t.add(column: ...) /// } /// @@ -524,7 +524,7 @@ public final class TableAlteration { /// Appends a column to the table. /// - /// try db.alter(table: "players") { t in + /// try db.alter(table: "player") { t in /// t.add(column: "url", .text) /// } /// @@ -566,11 +566,11 @@ public final class TableAlteration { /// /// You get instances of this class when you create or alter a database table: /// -/// try db.create(table: "players") { t in +/// try db.create(table: "player") { t in /// t.column(...) // ColumnDefinition /// } /// -/// try db.alter(table: "players") { t in +/// try db.alter(table: "player") { t in /// t.add(column: ...) // ColumnDefinition /// } /// @@ -599,7 +599,7 @@ public final class ColumnDefinition { /// Adds a primary key constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("id", .integer).primaryKey() /// } /// @@ -619,7 +619,7 @@ public final class ColumnDefinition { /// Adds a NOT NULL constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).notNull() /// } /// @@ -636,7 +636,7 @@ public final class ColumnDefinition { /// Adds a UNIQUE constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).unique() /// } /// @@ -653,7 +653,7 @@ public final class ColumnDefinition { /// Adds an index of the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).indexed() /// } /// @@ -670,7 +670,7 @@ public final class ColumnDefinition { /// Adds a CHECK constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).check { length($0) > 0 } /// } /// @@ -687,7 +687,7 @@ public final class ColumnDefinition { /// Adds a CHECK constraint on the column. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).check(sql: "LENGTH(name) > 0") /// } /// @@ -705,7 +705,7 @@ public final class ColumnDefinition { /// Defines the default column value. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).defaults(to: "Anonymous") /// } /// @@ -721,7 +721,7 @@ public final class ColumnDefinition { /// Defines the default column value. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP") /// } /// @@ -739,7 +739,7 @@ public final class ColumnDefinition { // Defines the default column collation. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("email", .text).collate(.nocase) /// } /// @@ -755,7 +755,7 @@ public final class ColumnDefinition { // Defines the default column collation. /// - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.column("name", .text).collate(.localizedCaseInsensitiveCompare) /// } /// @@ -771,8 +771,8 @@ public final class ColumnDefinition { /// Defines a foreign key. /// - /// try db.create(table: "books") { t in - /// t.column("authorId", .integer).references("authors", onDelete: .cascade) + /// try db.create(table: "book") { t in + /// t.column("authorId", .integer).references("author", onDelete: .cascade) /// } /// /// See https://www.sqlite.org/foreignkeys.html diff --git a/GRDB/QueryInterface/VirtualTableModule.swift b/GRDB/QueryInterface/VirtualTableModule.swift index 053460a3b..3814a1132 100644 --- a/GRDB/QueryInterface/VirtualTableModule.swift +++ b/GRDB/QueryInterface/VirtualTableModule.swift @@ -2,7 +2,7 @@ /// the `Database.create(virtualTable:using:)` method: /// /// let module = ... -/// try db.create(virtualTable: "items", using: module) { t in +/// try db.create(virtualTable: "item", using: module) { t in /// ... /// } /// @@ -13,7 +13,7 @@ public protocol VirtualTableModule { /// The type of the closure argument in the /// `Database.create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "items", using: module) { t in + /// try db.create(virtualTable: "item", using: module) { t in /// // t is TableDefinition /// } associatedtype TableDefinition @@ -24,7 +24,7 @@ public protocol VirtualTableModule { /// Returns a table definition that is passed as the closure argument in the /// `Database.create(virtualTable:using:)` method: /// - /// try db.create(virtualTable: "items", using: module) { t in + /// try db.create(virtualTable: "item", using: module) { t in /// // t is the result of makeTableDefinition() /// } func makeTableDefinition() -> TableDefinition @@ -70,7 +70,7 @@ extension Database { /// Creates a virtual database table. /// /// let module = ... - /// try db.create(virtualTable: "pointOfInterests", using: module) { t in + /// try db.create(virtualTable: "book", using: module) { t in /// ... /// } /// @@ -80,7 +80,7 @@ extension Database { /// Use this method to create full-text tables using the FTS3, FTS4, or /// FTS5 modules: /// - /// try db.create(virtualTable: "books", using: FTS4()) { t in + /// try db.create(virtualTable: "book", using: FTS4()) { t in /// t.column("title") /// t.column("author") /// t.column("body") diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index e6135260c..44e510cfa 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -273,4 +273,3 @@ extension FetchableRecord where Self: Decodable { try! self.init(from: RowDecoder(row: row, codingPath: [])) } } - diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 9cda45372..937736486 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -4,7 +4,7 @@ extension FetchableRecord where Self: TableRecord { /// A cursor over all records fetched from the database. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let players = try Player.fetchCursor(db) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -30,7 +30,7 @@ extension FetchableRecord where Self: TableRecord { /// An array of all records fetched from the database. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let players = try Player.fetchAll(db) // [Player] /// /// The selection defaults to all columns. This default can be changed for @@ -45,7 +45,7 @@ extension FetchableRecord where Self: TableRecord { /// The first found record. /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// let player = try Player.fetchOne(db) // Player? /// /// The selection defaults to all columns. This default can be changed for diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 31cc9bd1b..b4212b398 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -36,7 +36,7 @@ public protocol FetchableRecord { /// /// struct Player : FetchableRecord { ... } /// try dbQueue.read { db in -/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM players") +/// let players: RecordCursor = try Player.fetchCursor(db, "SELECT * FROM player") /// } public final class RecordCursor : Cursor { private let statement: SelectStatement @@ -73,7 +73,7 @@ extension FetchableRecord { /// A cursor over records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let players = try Player.fetchCursor(statement) // Cursor of Player /// while let player = try players.next() { // Player /// ... @@ -96,7 +96,7 @@ extension FetchableRecord { /// Returns an array of records fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let players = try Player.fetchAll(statement) // [Player] /// /// - parameters: @@ -111,7 +111,7 @@ extension FetchableRecord { /// Returns a single record fetched from a prepared statement. /// - /// let statement = try db.makeSelectStatement("SELECT * FROM players") + /// let statement = try db.makeSelectStatement("SELECT * FROM player") /// let player = try Player.fetchOne(statement) // Player? /// /// - parameters: @@ -131,7 +131,7 @@ extension FetchableRecord { /// Returns a cursor over records fetched from an SQL query. /// - /// let players = try Player.fetchCursor(db, "SELECT * FROM players") // Cursor of Player + /// let players = try Player.fetchCursor(db, "SELECT * FROM player") // Cursor of Player /// while let player = try players.next() { // Player /// ... /// } @@ -154,7 +154,7 @@ extension FetchableRecord { /// Returns an array of records fetched from an SQL query. /// - /// let players = try Player.fetchAll(db, "SELECT * FROM players") // [Player] + /// let players = try Player.fetchAll(db, "SELECT * FROM player") // [Player] /// /// - parameters: /// - db: A database connection. @@ -169,7 +169,7 @@ extension FetchableRecord { /// Returns a single record fetched from an SQL query. /// - /// let player = try Player.fetchOne(db, "SELECT * FROM players") // Player? + /// let player = try Player.fetchOne(db, "SELECT * FROM player") // Player? /// /// - parameters: /// - db: A database connection. diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 38cbb0118..904895c9c 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -18,7 +18,7 @@ public final class FetchedRecordsController { /// /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// @@ -402,17 +402,17 @@ extension FetchedRecordsController where Record: TableRecord { /// /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red]) /// /// The records are compared by primary key (single-column primary key, /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// - /// // Assuming the wines table has an `id` primary key: + /// // Assuming the wine table has an `id` primary key: /// let controller = FetchedRecordsController( /// dbQueue, - /// sql: "SELECT * FROM wines WHERE color = ? ORDER BY name", + /// sql: "SELECT * FROM wine WHERE color = ? ORDER BY name", /// arguments: [Color.red], /// isSameRecord: { (wine1, wine2) in wine1.id == wine2.id }) /// @@ -451,7 +451,7 @@ extension FetchedRecordsController where Record: TableRecord { /// compound primary key, or implicit rowid). For a database table which /// has an `id` primary key, this initializer is equivalent to: /// - /// // Assuming the wines table has an `id` primary key: + /// // Assuming the wine table has an `id` primary key: /// let controller = FetchedRecordsController( /// dbQueue, /// request: request, @@ -1049,4 +1049,3 @@ private final class Item : FetchableRecord, Equatable { return lhs.row == rhs.row } } - diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index e5d9cfd5b..b33cd862b 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -623,16 +623,16 @@ extension MutablePersistableRecord { /// Delete records identified by their primary keys; returns the number of /// deleted rows. /// - /// // DELETE FROM players WHERE id IN (1, 2, 3) + /// // DELETE FROM player WHERE id IN (1, 2, 3) /// try Player.deleteAll(db, keys: [1, 2, 3]) /// - /// // DELETE FROM countries WHERE code IN ('FR', 'US', 'DE') + /// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE') /// try Country.deleteAll(db, keys: ["FR", "US", "DE"]) /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// - /// // DELETE FROM documents WHERE rowid IN (1, 2, 3) + /// // DELETE FROM document WHERE rowid IN (1, 2, 3) /// try Document.deleteAll(db, keys: [1, 2, 3]) /// /// - parameters: @@ -652,16 +652,16 @@ extension MutablePersistableRecord { /// Delete a record, identified by its primary key; returns whether a /// database row was deleted. /// - /// // DELETE FROM players WHERE id = 123 + /// // DELETE FROM player WHERE id = 123 /// try Player.deleteOne(db, key: 123) /// - /// // DELETE FROM countries WHERE code = 'FR' + /// // DELETE FROM country WHERE code = 'FR' /// try Country.deleteOne(db, key: "FR") /// /// When the table has no explicit primary key, GRDB uses the hidden /// "rowid" column: /// - /// // DELETE FROM documents WHERE rowid = 1 + /// // DELETE FROM document WHERE rowid = 1 /// try Document.deleteOne(db, key: 1) /// /// - parameters: diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index ad24dc289..021a15a66 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -32,7 +32,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// /// class Player : Record { /// override class var databaseTableName: String { - /// return "players" + /// return "player" /// } /// } /// @@ -64,7 +64,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// /// Unless this method is overriden, requests select all columns: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) /// /// You can override this property and provide an explicit list @@ -76,7 +76,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// } /// } /// - /// // SELECT id, name FROM players + /// // SELECT id, name FROM player /// try RestrictedPlayer.fetchAll(db) /// /// You can also add extra columns such as the `rowid` column: @@ -87,7 +87,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// } /// } /// - /// // SELECT *, rowid FROM players + /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) open class var databaseSelection: [SQLSelectable] { return [AllColumns()] diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index b3350f557..60c9478d4 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -12,10 +12,10 @@ public protocol TableRecord { /// The name of the database table used to build requests. /// /// struct Player : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// } /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) static var databaseTableName: String { get } @@ -23,28 +23,28 @@ public protocol TableRecord { /// /// Unless said otherwise, requests select all columns: /// - /// // SELECT * FROM players + /// // SELECT * FROM player /// try Player.fetchAll(db) /// /// You can provide a custom implementation and provide an explicit list /// of columns: /// /// struct RestrictedPlayer : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// static var databaseSelection = [Column("id"), Column("name")] /// } /// - /// // SELECT id, name FROM players + /// // SELECT id, name FROM player /// try RestrictedPlayer.fetchAll(db) /// /// You can also add extra columns such as the `rowid` column: /// /// struct ExtendedPlayer : TableRecord { - /// static var databaseTableName = "players" + /// static var databaseTableName = "player" /// static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] /// } /// - /// // SELECT *, rowid FROM players + /// // SELECT *, rowid FROM player /// try ExtendedPlayer.fetchAll(db) static var databaseSelection: [SQLSelectable] { get } } @@ -77,14 +77,14 @@ extension TableRecord { /// For example: /// /// struct Player: TableRecord { - /// static let databaseTableName = "players" + /// static let databaseTableName = "player" /// } /// - /// // SELECT "players".* FROM players - /// let sql = "SELECT \(Player.selectionSQL()) FROM players" + /// // SELECT "player".* FROM player + /// let sql = "SELECT \(Player.selectionSQL()) FROM player" /// - /// // SELECT "p".* FROM players AS p - /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM players AS p" + /// // SELECT "p".* FROM player AS p + /// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p" public static func selectionSQL(alias: String? = nil) -> String { let alias = TableAlias(tableName: databaseTableName, userName: alias) let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) } @@ -99,11 +99,11 @@ extension TableRecord { /// For example: /// /// struct Player: TableRecord { - /// static let databaseTableName = "players" + /// static let databaseTableName = "player" /// } /// /// try dbQueue.write { db in - /// try db.create(table: "players") { t in + /// try db.create(table: "player") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("name", .text) /// t.column("score", .integer) diff --git a/TODO.md b/TODO.md index 56270c5d9..82ed24851 100644 --- a/TODO.md +++ b/TODO.md @@ -30,6 +30,7 @@ GRDB 3.0 - [ ] If required by associations, make reversed() make nothing when there is no alraedy applied ordering - [ ] Fix matchingRowIds - [ ] Simplify Range extensions for Swift 4.1 +- [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 Not sure From fa00b8ad99c357c2b7ccceb452d29dcefa9f9dc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 1 May 2018 21:44:43 +0200 Subject: [PATCH 217/348] Associations and Joins documentation --- Documentation/AssociationsBasics.md | 2 ++ README.md | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index ba314792a..a8440f888 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -109,6 +109,8 @@ let request = Book.including(optional: Book.author) let bookInfos = BookInfo.fetchAll(db, request) ``` +Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because Your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter. + The Types of Associations ========================= diff --git a/README.md b/README.md index de4dc8e02..9efb31247 100644 --- a/README.md +++ b/README.md @@ -3258,6 +3258,7 @@ So don't miss the [SQL API](#sqlite-api). - [Fetching Aggregated Values](#fetching-aggregated-values) - [Delete Requests](#delete-requests) - [Custom Requests](#custom-requests) +- [Associations and Joins](Documentation/AssociationsBasics.md) ## Database Schema @@ -5021,7 +5022,7 @@ LEFT JOIN round ON ... GROUP BY ... ``` -We will not talk about *building* joined queries. +We will not talk about *generating* joined queries, which is covered in [Associations](Documentation/AssociationsBasics.md). **So what are we talking about?** From 06f9a4601c6a3709818c67e80b37fdeb61859ecb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 07:43:16 +0200 Subject: [PATCH 218/348] TODO --- README.md | 2 +- TODO.md | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9efb31247..c1b788c85 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)]( **Latest release**: March 30, 2018 • version 2.10.0 • [CHANGELOG](CHANGELOG.md) -**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4+ / Xcode 9.3+ +**Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.1+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | diff --git a/TODO.md b/TODO.md index f44c41784..e51e2857b 100644 --- a/TODO.md +++ b/TODO.md @@ -21,7 +21,6 @@ GRDB 3.0 - [ ] Introduce some record protocol with an associated primary key type. Restrict filter(key:) methods to this type. Allow distinguishing FooId from BarId types. - [ ] Replace Column with TypedColumn. How to avoid code duplication (repeated types)? Keypaths? - [ ] HiddenColumnsAdapter -- [ ] PR for OffsettedAdapter - [ ] Find a common name for DatabaseQueue.inDatabase / DatabasePool.writeWithoutTransaction: - writeRaw, rawWrite, pureWrite, plainWrite, directWrite, basicWrite - sync @@ -31,6 +30,8 @@ GRDB 3.0 - [ ] Simplify Range extensions for Swift 4.1 - [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 - [ ] hide ScopeAdapter(base, scopes), because base.addingScopes has a better implementation +- [ ] Drop iOS 8 compatibility, due to lack of Xcode support +- [ ] Joins and full-text tables Not sure From e184963b8fef4df34065a9375193e7f387dfd512 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 13:40:33 +0200 Subject: [PATCH 219/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 133 +++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 Documentation/GRDB2MigrationGuide.md diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md new file mode 100644 index 000000000..c168452f1 --- /dev/null +++ b/Documentation/GRDB2MigrationGuide.md @@ -0,0 +1,133 @@ +Migrating From GRDB 2 to GRDB 3 +=============================== + +GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications. + +- [How To Upgrade] +- [Database Schema Recommendations] +- [If You Target iOS 8] +- [If You Use Database Queues] +- [If You Use Database Pools] + + +## How to Upgrade + +Target the "GRDB3" branch: + +### CocoaPods + +Update your Podfile: + +```ruby +pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift', branch: 'GRDB3' +# pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' +``` + +### Swift Package Manager + +Update your Package.swift file: + +``` +let package = Package( + dependencies: [ + .package(url: "https://github.com/groue/GRDB.swift.git", branch: "GRDB3") + ] +) +``` + +### Manually + +Update your local copy of GRDB: + +```sh +git checkout GRDB3 +git pull +``` + + +## Database Schema Recommendations + +GRDB 2 was totally schema-agnostic, and would gladly accept any database. + +GRDB 3 still accepts any database, but brings two schema recommendations: + +- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused. + + When ids can be reused, high-level database observation tools such as [FetchedRecordsController] or [RxGRDB] that ship with GRDB may see an update when a row is deleted, then replaced, in a single database transaction. Depending on your application needs, this may be OK. Or not. + + GRDB3 thus comes with this new *good pratice*: use the new `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: + + ```diff + try db.create(table: "author") { t in + - t.column("id", .integer).primaryKey() // GRDB 2 + + t.autoIncrementedPrimaryKey("id") // GRDB 3 recommendation + t.column("name", .text).notNull() + } + ``` + +- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. + + This will help you using the new [Associations] feature when you need it. + + Database table names that follow another naming convention are OK, but you will need to perform extra configuration. + +Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema: + +```swift +var migrator = DatabaseMigrator() + +// GRDB 2 migration +migrator.registerMigration("initial") { db in + try db.create(table: "authors") { t in + t.column("id", .integer).primaryKey() + t.column("name", .text).notNull() + } + try db.create(table: "books") { t in + t.column("id", .integer).primaryKey() + t.column("authorId", .integer).notNull().references("authors") + t.column("title", .text).notNull() + } +} + +// GRDB 3 migration: +// - table names look like Swift identifiers (singular and camelCased) +// - integer primary keys are auto-incremented +// +// Use registerMigrationWithDeferredForeignKeyCheck in order to disable +// foreign key checks during the migration: +migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer).notNull().references("author") + t.column("title", .text).notNull() + } + try db.execute(""" + INSERT INTO author SELECT * FROM authors; + INSERT INTO book SELECT * FROM books; + """) + try db.drop(table: "authors") + try db.drop(table: "books") +} +``` + + +## If You Target iOS 8 +## If You Use Database Queues +## If You Use Database Pools + + + + +[How To Upgrade]: #how-to-upgrade +[Database Schema Recommendations]: #database-schema-recommendations +[If You Target iOS 8]: #if-you-target-ios-8 +[If You Use Database Queues]: #if-you-use-database-queues +[If You Use Database Pools]: #if-you-use-database-pools +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[Associations]: AssociationsBasics.md +[DatabaseMigrator]: ../README.md#migrations \ No newline at end of file From 287422f2f8cb44764c775029aa178b94d71a6c0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 13:59:15 +0200 Subject: [PATCH 220/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index c168452f1..eb23d7d01 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -27,7 +27,7 @@ pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift', branch: 'GRDB3' Update your Package.swift file: -``` +```swift let package = Package( dependencies: [ .package(url: "https://github.com/groue/GRDB.swift.git", branch: "GRDB3") @@ -53,7 +53,7 @@ GRDB 3 still accepts any database, but brings two schema recommendations: - :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused. - When ids can be reused, high-level database observation tools such as [FetchedRecordsController] or [RxGRDB] that ship with GRDB may see an update when a row is deleted, then replaced, in a single database transaction. Depending on your application needs, this may be OK. Or not. + When ids can be reused, high-level database observation tools such as [FetchedRecordsController] or [RxGRDB] may see an update when a row is deleted, then replaced, in a single database transaction. Depending on your application needs, this may be OK. Or not. GRDB3 thus comes with this new *good pratice*: use the new `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: @@ -116,12 +116,19 @@ migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in ## If You Target iOS 8 + +GRDB 3 is only supported on iOS 9+. + +That is because the library requires Swift 4.1, which ships with Xcode 9.3, unable to run tests before iOS 9. + +> :construction_worker: Beta note: GRDB 3 currently still *runs* on iOS8, although untested. I won't delete the code that targets older versions of SQLite and iOS until I grab some feedback. + + ## If You Use Database Queues + ## If You Use Database Pools - - [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations [If You Target iOS 8]: #if-you-target-ios-8 From e3ab3a991ee0390dc8b69ec85aaa96a12006e5d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 18:47:34 +0200 Subject: [PATCH 221/348] WIP: GRDB2MigrationGuide.md --- Documentation/AssociationsBasics.md | 2 +- Documentation/GRDB2MigrationGuide.md | 11 +++++------ README.md | 15 ++++++++++++--- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index a8440f888..1a27d2d08 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -275,7 +275,7 @@ Those conventions help associations be convenient and, generally, "just work". W **Database table names should be singular and camel-cased.** -This is the same convention as Swift identifiers for variables and properties. For example: `book`, `author`, `postalAddress`. +Make them look like Swift identifiers: `book`, `author`, `postalAddress`. This convention helps fetching values from associations. It is used, for example, in the sample code below, where we load all pairs of books along with their authors: diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index eb23d7d01..a4559ee61 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -53,9 +53,9 @@ GRDB 3 still accepts any database, but brings two schema recommendations: - :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused. - When ids can be reused, high-level database observation tools such as [FetchedRecordsController] or [RxGRDB] may see an update when a row is deleted, then replaced, in a single database transaction. Depending on your application needs, this may be OK. Or not. + When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. - GRDB3 thus comes with this new *good pratice*: use the new `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: + GRDB3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: ```diff try db.create(table: "author") { t in @@ -67,9 +67,7 @@ GRDB 3 still accepts any database, but brings two schema recommendations: - :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. - This will help you using the new [Associations] feature when you need it. - - Database table names that follow another naming convention are OK, but you will need to perform extra configuration. + This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema: @@ -137,4 +135,5 @@ That is because the library requires Swift 4.1, which ships with Xcode 9.3, unab [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Associations]: AssociationsBasics.md -[DatabaseMigrator]: ../README.md#migrations \ No newline at end of file +[DatabaseMigrator]: ../README.md#migrations +[database observation tools]: ../README.md#database-changes-observation \ No newline at end of file diff --git a/README.md b/README.md index c1b788c85..84a2223c5 100644 --- a/README.md +++ b/README.md @@ -3304,7 +3304,9 @@ try db.create(table: "example") { t in ... } try db.create(table: "example", temporary: true, ifNotExists: true) { t in ``` -> :bulb: **Tip**: when you create a database table, prefer giving it a name that is singular and camel-cased, such as `place`, `country`, or `postalAddress`. This is the prefered convention for database table names in GRDB. Other names such as `places` or `postal_address` are also valid, but you may have to perform extra configuration steps. +> :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. +> +> This will help you using the new [Associations](Documentation/AssociationsBasics.md) feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. **Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): @@ -3345,9 +3347,16 @@ Use an individual column as **primary**, **unique**, or **foreign key**. When de t.column("countryCode", .text).references("country", onDelete: .cascade) ``` -> :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method. +> :bulb: **Tip**: when you need an integer primary key that automatically generates unique values, it is highly recommended that you use the `autoIncrementedPrimaryKey` method: > -> Such primary key prevents the reuse of ids, and is an excellent guard against data races that could happen when your application processes ids in an asynchronous way. The auto-incremented primary key provides the guarantee that a given id can't reference a row that is different from the one it used to be at the beginning of the asynchronous process, even if this row gets deleted and a new one is inserted in between. +> ```swift +> try db.create(table: "example") { t in +> t.autoIncrementedPrimaryKey("id") +> ... +> } +> ``` +> +> The reason for this recommendation is that auto-incremented primary keys prevent the reuse of ids. This prevents your app or [database observation tools](#database-changes-observation) to think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. **Create an index** on the column: From 33ec30438d844968ee50ed51a57d8441d54282d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 19:52:26 +0200 Subject: [PATCH 222/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 54 +++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a4559ee61..50dc84248 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -124,6 +124,57 @@ That is because the library requires Swift 4.1, which ships with Xcode 9.3, unab ## If You Use Database Queues +With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` DatabaseQueue methods: + +```swift +// Typical GRDB 2 +let players = try dbQueue.inDatabase { db in + try Player.fetchAll(db) +} + +try dbQueue.inDatabase { db in + try player.updateChanges(db) +} + +var balance: Amount! = nil +try dbQueue.inTransaction { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + balance = try sourceAccount.fetchBalance(db) + return .commit +} +``` + +The code above still runs, unchanged, in GRDB 3. + +Yet it is now recommended that you use the `read` and `write` methods instead: + +```swift +// GRDB 3 +let players = try dbQueue.read { db in + try Player.fetchAll(db) +} + +try dbQueue.write { db in + try player.updateChanges(db) +} + +let balance = try dbQueue.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return try sourceAccount.fetchBalance(db) +} +``` + +The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of GRDB 2, inherited from FMDB. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. + +With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen. + +When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are applied, or, should any error happen, none at all. + +Of course, precise transaction handling is still possible. Check the updated [Transactions and Savepoints] chapter. + + ## If You Use Database Pools @@ -136,4 +187,5 @@ That is because the library requires Swift 4.1, which ships with Xcode 9.3, unab [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Associations]: AssociationsBasics.md [DatabaseMigrator]: ../README.md#migrations -[database observation tools]: ../README.md#database-changes-observation \ No newline at end of file +[database observation tools]: ../README.md#database-changes-observation +[Transactions and Savepoints]: ../README.md#transactions-and-savepoints From fa04627ece442551f477c87f24c9e4fd5cefe81f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 19:57:36 +0200 Subject: [PATCH 223/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 50dc84248..7ff4edbe6 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -124,10 +124,10 @@ That is because the library requires Swift 4.1, which ships with Xcode 9.3, unab ## If You Use Database Queues -With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` DatabaseQueue methods: +With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods: ```swift -// Typical GRDB 2 +// GRDB 2 let players = try dbQueue.inDatabase { db in try Player.fetchAll(db) } @@ -166,13 +166,13 @@ let balance = try dbQueue.write { db in } ``` -The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of GRDB 2, inherited from FMDB. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. +The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of GRDB 2, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen. When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are applied, or, should any error happen, none at all. -Of course, precise transaction handling is still possible. Check the updated [Transactions and Savepoints] chapter. +Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter. ## If You Use Database Pools @@ -189,3 +189,5 @@ Of course, precise transaction handling is still possible. Check the updated [Tr [DatabaseMigrator]: ../README.md#migrations [database observation tools]: ../README.md#database-changes-observation [Transactions and Savepoints]: ../README.md#transactions-and-savepoints +[DatabaseQueue]: ../README.md#database-queues +[FMDB]: http://github.com/ccgus/fmdb \ No newline at end of file From a5d56d38d670790392668f444617a411de0ae4c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 20:03:56 +0200 Subject: [PATCH 224/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 7ff4edbe6..603880950 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -8,6 +8,8 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [If You Target iOS 8] - [If You Use Database Queues] - [If You Use Database Pools] +- [If You Use Database Snapshots] +- [If You Use RxGRDB] ## How to Upgrade @@ -166,7 +168,7 @@ let balance = try dbQueue.write { db in } ``` -The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of GRDB 2, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. +The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot. With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen. @@ -178,11 +180,19 @@ Of course, precise transaction handling sometimes matter. Check the updated [Tra ## If You Use Database Pools +## If You Use Database Snapshots + + +## If You Use RxGRDB + + [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations [If You Target iOS 8]: #if-you-target-ios-8 [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools +[If You Use Database Snapshots]: #if-you-use-database-snapshots +[If You Use RxGRDB]: #if-you-use-rxgrdb [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Associations]: AssociationsBasics.md From 0aa75f418f6bd0c1a9c46cc79377634bace8c57f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 21:27:03 +0200 Subject: [PATCH 225/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 61 +++++++++++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 603880950..c8e45adc5 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -172,13 +172,71 @@ The purpose of the new `read` and `write` methods is to soothe the "transaction With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen. -When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are applied, or, should any error happen, none at all. +When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all. Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter. ## If You Use Database Pools +With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods: + +```swift +// GRDB 2 +let players = try dbPool.read { db in + try Player.fetchAll(db) +} + +try dbPool.write { db in + try player.updateChanges(db) +} + +var balance: Amount! = nil +try dbPool.writeInTransaction { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + balance = try sourceAccount.fetchBalance(db) + return .commit +} +``` + +In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below: + +```swift +// GRDB 3 +let balance = try dbPool.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) + return try sourceAccount.fetchBalance(db) +} +``` + +Side effect: you can no longer open explicit transactions inside a `write` block: + +```swift +// GRDB 2: OK +// GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: +// cannot start a transaction within a transaction +try dbPool.write { db in + db.inTransaction { ... } +} +``` + +When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter. + +The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database: + +```swift +// GRDB 2: unsafe +// GRDB 3: safe +try dbPool.write { db in + try Credit(destinationAccout, amount).insert(db) + try Debit(sourceAccount, amount).insert(db) +} +``` + +Now `write` automatically wraps your changes in a transaction, with the guarantee that concurrent reads can't see them until they are all written to disk. + ## If You Use Database Snapshots @@ -200,4 +258,5 @@ Of course, precise transaction handling sometimes matter. Check the updated [Tra [database observation tools]: ../README.md#database-changes-observation [Transactions and Savepoints]: ../README.md#transactions-and-savepoints [DatabaseQueue]: ../README.md#database-queues +[DatabasePool]: ../README.md#database-pools [FMDB]: http://github.com/ccgus/fmdb \ No newline at end of file From c7a1daa8e516fd6b52d4f2dde98f3e85fe99804e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 2 May 2018 21:55:53 +0200 Subject: [PATCH 226/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 31 +++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index c8e45adc5..11d2167a2 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -240,6 +240,33 @@ Now `write` automatically wraps your changes in a transaction, with the guarante ## If You Use Database Snapshots +With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example: + +```swift +// GRDB 2 +let snapshot: DatabaseSnapshot = try dbPool.write { db in + try Player.deleteAll() + return dbPool.makeSnapshot() +} + +// Guaranteed to be zero +let count = try snapshot.read { db in + try Player.fetchCount(db) +} +``` + +GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction." + +To avoid this error, you will need [precise transaction handling]: + +```swift +// GRDB 3 +let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in + try Player.deleteAll() + return dbPool.makeSnapshot() +} +``` + ## If You Use RxGRDB @@ -257,6 +284,8 @@ Now `write` automatically wraps your changes in a transaction, with the guarante [DatabaseMigrator]: ../README.md#migrations [database observation tools]: ../README.md#database-changes-observation [Transactions and Savepoints]: ../README.md#transactions-and-savepoints +[precise transaction handling]: ../README.md#transactions-and-savepoints [DatabaseQueue]: ../README.md#database-queues [DatabasePool]: ../README.md#database-pools -[FMDB]: http://github.com/ccgus/fmdb \ No newline at end of file +[database snapshots]: ../README.md#database-snapshots +[FMDB]: http://github.com/ccgus/fmdb From ebb1eba96f3a22e9a275294a54e7c748513cf791 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 08:34:02 +0200 Subject: [PATCH 227/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 11d2167a2..8062e1fd7 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -3,9 +3,15 @@ Migrating From GRDB 2 to GRDB 3 GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications. +**For all users** + - [How To Upgrade] +- [iOS 8 Sunsetting] - [Database Schema Recommendations] -- [If You Target iOS 8] +- [Record Protocols Renaming] + +**By topic** + - [If You Use Database Queues] - [If You Use Database Pools] - [If You Use Database Snapshots] @@ -47,6 +53,11 @@ git pull ``` +## iOS 8 Sunsetting + +GRDB 3 is only tested on iOS 9+. Code that targets older versions of SQLite and iOS is still there, but is not supported. + + ## Database Schema Recommendations GRDB 2 was totally schema-agnostic, and would gladly accept any database. @@ -115,13 +126,16 @@ migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in ``` -## If You Target iOS 8 +## Record Protocols Renaming -GRDB 3 is only supported on iOS 9+. +GRDB 3 has renamed the [record protocols]: -That is because the library requires Swift 4.1, which ships with Xcode 9.3, unable to run tests before iOS 9. +- `RowConvertible` -> `FetchableRecord` +- `TableMapping` -> `TableRecord` +- `Persistable` -> `PersistableRecord` +- `MutablePersistable` -> `MutablePersistableRecord` -> :construction_worker: Beta note: GRDB 3 currently still *runs* on iOS8, although untested. I won't delete the code that targets older versions of SQLite and iOS until I grab some feedback. +After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits. ## If You Use Database Queues @@ -273,7 +287,8 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations -[If You Target iOS 8]: #if-you-target-ios-8 +[Record Protocols Renaming]: #record-protocols-renaming +[iOS 8 Sunsetting]: @ios-8-sunsetting [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools [If You Use Database Snapshots]: #if-you-use-database-snapshots @@ -289,3 +304,4 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in [DatabasePool]: ../README.md#database-pools [database snapshots]: ../README.md#database-snapshots [FMDB]: http://github.com/ccgus/fmdb +[record protocols]: ../README.md##record-protocols-overview \ No newline at end of file From da38df6bd61052a0c80204cd3ae5cbdd80ac96a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 08:51:31 +0200 Subject: [PATCH 228/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 42 +++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 8062e1fd7..0d67a1948 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -15,6 +15,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [If You Use Database Queues] - [If You Use Database Pools] - [If You Use Database Snapshots] +- [If You Define Custom Requests] - [If You Use RxGRDB] @@ -282,6 +283,42 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in ``` +## If You Define Custom Requests + +[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need. + +You may, for example, use `SQLRequest`: + +```swift +// GRDB 2 +extension Player { + static func filter(color: Color) -> AnyTypedRequest { + let sql = "SELECT * FROM players WHERE color = ?" + let request = SQLRequest(sql, arguments: [color]) + return request.asRequest(of: Player.self) + } +} + +let players = try Player.filter(color: .red).fetchAll(db) +``` + +The `AnyTypedRequest` type is no longer available, and SQLRequest is now a generic type: + +```swift +// GRDB 3 +extension Player { + static func filter(color: Color) -> SQLRequest { + let sql = "SELECT * FROM players WHERE color = ?" + return SQLRequest(sql, arguments: [color]) + } +} + +let players = try Player.filter(color: .red).fetchAll(db) +``` + +For other incompatible changes, let the compiler fixits guide you. + + ## If You Use RxGRDB @@ -292,6 +329,7 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools [If You Use Database Snapshots]: #if-you-use-database-snapshots +[If You Define Custom Requests]: #if-you-define-custom-requests [If You Use RxGRDB]: #if-you-use-rxgrdb [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB @@ -304,4 +342,6 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in [DatabasePool]: ../README.md#database-pools [database snapshots]: ../README.md#database-snapshots [FMDB]: http://github.com/ccgus/fmdb -[record protocols]: ../README.md##record-protocols-overview \ No newline at end of file +[record protocols]: ../README.md##record-protocols-overview +[Custom requests]: ../README.md##custom-requests +[query interface]: ../README.md##the-query-interface From 26b9030eaab16d3e1979113280079cd2a63cb552 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 08:53:19 +0200 Subject: [PATCH 229/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 0d67a1948..95cbbdfd2 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -342,6 +342,6 @@ For other incompatible changes, let the compiler fixits guide you. [DatabasePool]: ../README.md#database-pools [database snapshots]: ../README.md#database-snapshots [FMDB]: http://github.com/ccgus/fmdb -[record protocols]: ../README.md##record-protocols-overview -[Custom requests]: ../README.md##custom-requests -[query interface]: ../README.md##the-query-interface +[record protocols]: ../README.md#record-protocols-overview +[Custom requests]: ../README.md#custom-requests +[query interface]: ../README.md#the-query-interface From 31e927f9da977a00c32a35e9cd5b19323474ba1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 08:54:50 +0200 Subject: [PATCH 230/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 95cbbdfd2..4c01a8989 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -302,7 +302,7 @@ extension Player { let players = try Player.filter(color: .red).fetchAll(db) ``` -The `AnyTypedRequest` type is no longer available, and SQLRequest is now a generic type: +The `AnyTypedRequest` type is no longer available, and `SQLRequest` is now a generic type: ```swift // GRDB 3 From 1c9db9ec1070d9c2a16d80aa458534690d46921a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 08:55:52 +0200 Subject: [PATCH 231/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 4c01a8989..a76807e48 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -15,7 +15,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [If You Use Database Queues] - [If You Use Database Pools] - [If You Use Database Snapshots] -- [If You Define Custom Requests] +- [If You Use Custom Requests] - [If You Use RxGRDB] @@ -283,7 +283,7 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in ``` -## If You Define Custom Requests +## If You Use Custom Requests [Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need. @@ -329,7 +329,7 @@ For other incompatible changes, let the compiler fixits guide you. [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools [If You Use Database Snapshots]: #if-you-use-database-snapshots -[If You Define Custom Requests]: #if-you-define-custom-requests +[If You Use Custom Requests]: #if-you-use-custom-requests [If You Use RxGRDB]: #if-you-use-rxgrdb [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB From 231906e5ea49efc5c7bc84077444ddd3a47e353f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 3 May 2018 10:17:38 +0200 Subject: [PATCH 232/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a76807e48..a3e8ee519 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -233,7 +233,7 @@ Side effect: you can no longer open explicit transactions inside a `write` block // GRDB 3: SQLite error 1 with statement `BEGIN DEFERRED TRANSACTION`: // cannot start a transaction within a transaction try dbPool.write { db in - db.inTransaction { ... } + try db.inTransaction { ... } } ``` @@ -250,7 +250,7 @@ try dbPool.write { db in } ``` -Now `write` automatically wraps your changes in a transaction, with the guarantee that concurrent reads can't see them until they are all written to disk. +Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk. ## If You Use Database Snapshots From 6a4382c3237e0b1b03fb9a2c7593224afe9e9e4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 4 May 2018 08:32:51 +0200 Subject: [PATCH 233/348] TODO --- TODO.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/TODO.md b/TODO.md index e51e2857b..010fa5da5 100644 --- a/TODO.md +++ b/TODO.md @@ -30,8 +30,20 @@ GRDB 3.0 - [ ] Simplify Range extensions for Swift 4.1 - [ ] https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/6 - [ ] hide ScopeAdapter(base, scopes), because base.addingScopes has a better implementation -- [ ] Drop iOS 8 compatibility, due to lack of Xcode support - [ ] Joins and full-text tables +- [ ] DatabaseRequest should be part of RxGRDB, as DatabaseRegionConvertible. Rename fetchedRegion(_:) to databaseRegion(_:). SelectStatementRequest hasn't much traction left: remove? +- [ ] Provide a way to extend both QueryInterfaceRequest and Association: + + ```swift + extension ??? where ??? = Player { + func filter(color: Color) -> Self { + return filter(Column("color") == color) + } + } + let players = Player.all().filter(color: .red) + let players = Player.filter(color: .red) // Possible ?? + let teamPlayers = Team.players.filter(color: .red) + ``` Not sure From babaefca8fe1fc3060e3f4fd2fefc5a631c53bd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 4 May 2018 10:48:56 +0200 Subject: [PATCH 234/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a3e8ee519..a9f97e30a 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -88,7 +88,7 @@ Since you are reading this guide, your application has already defined its datab ```swift var migrator = DatabaseMigrator() -// GRDB 2 migration +// Existing GRDB 2 migration: migrator.registerMigration("initial") { db in try db.create(table: "authors") { t in t.column("id", .integer).primaryKey() @@ -101,12 +101,14 @@ migrator.registerMigration("initial") { db in } } -// GRDB 3 migration: -// - table names look like Swift identifiers (singular and camelCased) -// - integer primary keys are auto-incremented +// New GRDB 3 migration: +// - Rename tables so that they look like Swift identifiers (singular and camelCased) +// - Make integer primary keys auto-incremented // -// Use registerMigrationWithDeferredForeignKeyCheck in order to disable -// foreign key checks during the migration: +// Since several tables are recreated from scratch, referential integrity +// constraints may break during the process. The +// registerMigrationWithDeferredForeignKeyCheck method makes sure that foreign +// key checks are temporarily disabled, and checked at the end: migrator.registerMigrationWithDeferredForeignKeyCheck("GRDB3") { db in try db.create(table: "author") { t in t.autoIncrementedPrimaryKey("id") From cdad6fa3136450254df4933213b16904cbeb0b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 4 May 2018 14:19:27 +0200 Subject: [PATCH 235/348] Introduce DerivableRequest --- GRDB.xcodeproj/project.pbxproj | 6 ++ .../Association/Association.swift | 24 +++--- .../Association/AssociationRequest.swift | 2 +- .../Association/BelongsToAssociation.swift | 59 +++++++------ .../Association/HasManyAssociation.swift | 59 +++++++------ .../Association/HasOneAssociation.swift | 59 +++++++------ .../QueryInterfaceRequest+Association.swift | 20 ++--- .../QueryInterfaceRequest.swift | 4 +- GRDB/QueryInterface/RequestProtocols.swift | 12 +++ GRDBCipher.xcodeproj/project.pbxproj | 10 +++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ Tests/GRDBTests/DerivableRequestTests.swift | 85 +++++++++++++++++++ Tests/GRDBTests/SQLRequestTests.swift | 2 +- 13 files changed, 244 insertions(+), 104 deletions(-) create mode 100644 Tests/GRDBTests/DerivableRequestTests.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 4a264ad8d..760ef2cb5 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -657,6 +657,8 @@ 56E5D82D1B4D438800430942 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; }; 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */; }; 56E8CE111BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */; }; + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; }; 56EA86951C91DFE7002BB4DF /* DatabaseReaderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */; }; 56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 56EB0AB31BCD787300A3DC55 /* DataMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */; }; @@ -1098,6 +1100,7 @@ 56E5D7F91B4D422D00430942 /* GRDBOSXTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1348,6 +1351,7 @@ children = ( 5653EABF20944B1300F46237 /* Association */, 56B6EF55208CB4E3002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -2561,6 +2565,7 @@ 562756471E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 569531381C919DF700CF1A2B /* DatabasePoolFunctionTests.swift in Sources */, 56A238481B9C74A90082EB20 /* RowCopiedFromStatementTests.swift in Sources */, + 56EA63C6209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 5674A71A1F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 5698AC071D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, @@ -2722,6 +2727,7 @@ 56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */, 56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */, 562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, + 56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */, 56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */, 5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, 56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 8023699f2..4fc93f130 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -2,9 +2,9 @@ /// /// The base protocol for all associations that define a connection between two /// record types. -public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { - associatedtype LeftAssociated - associatedtype RightAssociated +public protocol Association: DerivableRequest { + associatedtype OriginRowDecoder + associatedtype RowDecoder /// The association key defines how rows fetched from this association /// should be consumed. @@ -50,14 +50,14 @@ public protocol Association: SelectionRequest, FilteredRequest, OrderedRequest { // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: - var request: AssociationRequest { get } + var request: AssociationRequest { get } // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: func joinCondition(_ db: Database) throws -> JoinCondition /// :nodoc: - func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self + func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> Self } extension Association { @@ -240,33 +240,33 @@ extension Association { /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) -> Self where A.LeftAssociated == RightAssociated { + public func including(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.optional, association) } } /// Creates an association that includes another one. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) -> Self where A.LeftAssociated == RightAssociated { + public func including(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.required, association) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> Self where A.LeftAssociated == RightAssociated { + public func joining(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.optional, association.select([])) } } /// Creates an association that joins another one. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) -> Self where A.LeftAssociated == RightAssociated { + public func joining(required association: A) -> Self where A.OriginRowDecoder == RowDecoder { return mapRequest { $0.joining(.required, association.select([])) } } } -extension Association where LeftAssociated: MutablePersistableRecord { +extension Association where OriginRowDecoder: MutablePersistableRecord { /// Support for MutablePersistableRecord.request(for:). /// /// For example: @@ -280,11 +280,11 @@ extension Association where LeftAssociated: MutablePersistableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - func request(from record: LeftAssociated) -> QueryInterfaceRequest { + func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { // Turn `JOIN associated ON associated.recordId = record.id` // into `FROM associated WHERE associated.recordId = 1` let associationAlias = TableAlias() - let recordAlias = TableAlias(tableName: LeftAssociated.databaseTableName) + let recordAlias = TableAlias(tableName: OriginRowDecoder.databaseTableName) return QueryInterfaceRequest(request) .aliased(associationAlias) .filter { db in diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index ba9f08ade..789e1326a 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -37,7 +37,7 @@ extension AssociationRequest { func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> AssociationRequest - where A.LeftAssociated == T + where A.OriginRowDecoder == T { let join = AssociationJoin( joinOperator: joinOperator, diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 7a6623eaa..b20853c8d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -1,21 +1,23 @@ -public struct BelongsToAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord +public struct BelongsToAssociation : Association, TableRequest where + Origin: TableRecord, + Destination: TableRecord { - public typealias LeftAssociated = Left - public typealias RightAssociated = Right + fileprivate let foreignKeyRequest: ForeignKeyRequest + // Association conformance + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } - - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest + public var request: AssociationRequest - public func forKey(_ key: String) -> BelongsToAssociation { + public func forKey(_ key: String) -> BelongsToAssociation { var association = self association.key = key return association @@ -27,41 +29,46 @@ public struct BelongsToAssociation : Association, TableRequest wher } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> BelongsToAssociation { var association = self association.request = transform(request) return association } + + // TableRequest conformance + + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { // TODO: Make it public if and only if we really want to build an association from any request - static func belongsTo( - _ rightRequest: QueryInterfaceRequest, + static func belongsTo( + _ request: QueryInterfaceRequest, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation - where Right: TableRecord + -> BelongsToAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( originTable: databaseTableName, - destinationTable: Right.databaseTableName, + destinationTable: Destination.databaseTableName, foreignKey: foreignKey) return BelongsToAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) + foreignKeyRequest: foreignKeyRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(request)) } /// TODO - public static func belongsTo( - _ right: Right.Type, + public static func belongsTo( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation - where Right: TableRecord + -> BelongsToAssociation + where Destination: TableRecord { - return belongsTo(Right.all(), key: key, using: foreignKey) + return belongsTo(Destination.all(), key: key, using: foreignKey) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 4c9d88edf..3143efadc 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -1,21 +1,23 @@ -public struct HasManyAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord +public struct HasManyAssociation : Association, TableRequest where + Origin: TableRecord, + Destination: TableRecord { - public typealias LeftAssociated = Left - public typealias RightAssociated = Right + fileprivate let foreignKeyRequest: ForeignKeyRequest + // Association conformance + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination + public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } + public var request: AssociationRequest - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest - - public func forKey(_ key: String) -> HasManyAssociation { + public func forKey(_ key: String) -> HasManyAssociation { var association = self association.key = key return association @@ -27,41 +29,46 @@ public struct HasManyAssociation : Association, TableRequest where } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasManyAssociation { var association = self association.request = transform(request) return association } + + // TableRequest conformance + + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { // TODO: Make it public if and only if we really want to build an association from any request - static func hasMany( - _ rightRequest: QueryInterfaceRequest, + static func hasMany( + _ request: QueryInterfaceRequest, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasManyAssociation - where Right: TableRecord + -> HasManyAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( - originTable: Right.databaseTableName, + originTable: Destination.databaseTableName, destinationTable: databaseTableName, foreignKey: foreignKey) return HasManyAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) + foreignKeyRequest: foreignKeyRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(request)) } /// TODO - public static func hasMany( - _ right: Right.Type, + public static func hasMany( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasManyAssociation - where Right: TableRecord + -> HasManyAssociation + where Destination: TableRecord { - return hasMany(Right.all(), key: key, using: foreignKey) + return hasMany(Destination.all(), key: key, using: foreignKey) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b3c70de9e..9fe310bf9 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -1,21 +1,23 @@ -public struct HasOneAssociation : Association, TableRequest where - Left: TableRecord, - Right: TableRecord +public struct HasOneAssociation : Association, TableRequest where + Origin: TableRecord, + Destination: TableRecord { - public typealias LeftAssociated = Left - public typealias RightAssociated = Right + fileprivate let foreignKeyRequest: ForeignKeyRequest + + // Association conformance + + /// :nodoc: + public typealias OriginRowDecoder = Origin + + /// :nodoc: + public typealias RowDecoder = Destination public var key: String /// :nodoc: - public var databaseTableName: String { return RightAssociated.databaseTableName } + public var request: AssociationRequest - /// :nodoc: - public var request: AssociationRequest - - let foreignKeyRequest: ForeignKeyRequest - - public func forKey(_ key: String) -> HasOneAssociation { + public func forKey(_ key: String) -> HasOneAssociation { var association = self association.key = key return association @@ -27,41 +29,46 @@ public struct HasOneAssociation : Association, TableRequest where } /// :nodoc: - public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { + public func mapRequest(_ transform: (AssociationRequest) -> AssociationRequest) -> HasOneAssociation { var association = self association.request = transform(request) return association } + + // TableRequest conformance + + /// :nodoc: + public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { // TODO: Make it public if and only if we really want to build an association from any request - static func hasOne( - _ rightRequest: QueryInterfaceRequest, + static func hasOne( + _ request: QueryInterfaceRequest, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasOneAssociation - where Right: TableRecord + -> HasOneAssociation + where Destination: TableRecord { let foreignKeyRequest = ForeignKeyRequest( - originTable: Right.databaseTableName, + originTable: Destination.databaseTableName, destinationTable: databaseTableName, foreignKey: foreignKey) return HasOneAssociation( - key: key ?? Right.databaseTableName, - request: AssociationRequest(rightRequest), - foreignKeyRequest: foreignKeyRequest) + foreignKeyRequest: foreignKeyRequest, + key: key ?? Destination.databaseTableName, + request: AssociationRequest(request)) } /// TODO - public static func hasOne( - _ right: Right.Type, + public static func hasOne( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) - -> HasOneAssociation - where Right: TableRecord + -> HasOneAssociation + where Destination: TableRecord { - return hasOne(Right.all(), key: key, using: foreignKey) + return hasOne(Destination.all(), key: key, using: foreignKey) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift index 32dafae77..cf627a845 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest+Association.swift @@ -1,7 +1,7 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { func joining(_ joinOperator: AssociationJoinOperator, _ association: A) -> QueryInterfaceRequest - where A.LeftAssociated == RowDecoder + where A.OriginRowDecoder == RowDecoder { let join = AssociationJoin( joinOperator: joinOperator, @@ -16,28 +16,28 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord { /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + public func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.optional, association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + public func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.required, association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + public func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.optional, association.select([])) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == RowDecoder { + public func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder { return joining(.required, association.select([])) } } @@ -56,7 +56,7 @@ extension MutablePersistableRecord { /// /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] - public func request(for association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public func request(for association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return association.request(from: self) } } @@ -68,28 +68,28 @@ extension TableRecord { /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association does not /// require that the associated database table contains a matching row. - public static func including(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func including(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().including(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are selected. The returned association requires /// that the associated database table contains a matching row. - public static func including(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func including(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().including(required: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association does not /// require that the associated database table contains a matching row. - public static func joining(optional association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func joining(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().joining(optional: association) } /// Creates a request that includes an association. The columns of the /// associated record are not selected. The returned association requires /// that the associated database table contains a matching row. - public static func joining(required association: A) -> QueryInterfaceRequest where A.LeftAssociated == Self { + public static func joining(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == Self { return all().joining(required: association) } } diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index 38ab39e52..d6af81c04 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -43,7 +43,7 @@ extension QueryInterfaceRequest : FetchRequest { } } -extension QueryInterfaceRequest : SelectionRequest, FilteredRequest, AggregatingRequest, OrderedRequest { +extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { // MARK: Request Derivation @@ -192,7 +192,7 @@ extension QueryInterfaceRequest: TableRequest where RowDecoder: TableRecord { } } -extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord { +extension QueryInterfaceRequest where T: MutablePersistableRecord { // MARK: Deleting diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 8ae46b0a4..02db9a401 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -319,3 +319,15 @@ extension OrderedRequest { return order([expression]) } } + +// MARK: - DerivableRequest + +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// The base protocol for all requests that can be refined: +/// +/// extension DerivableRequest where RowDecoder: Player { +/// } +public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { + associatedtype RowDecoder +} diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index c498b799b..6286c1471 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -824,6 +824,10 @@ 56DAA2DF1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F131E859068008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F161E85906C008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */; }; 56F26C241CEE3F34007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; }; 56F3E74A1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; 56F3E74B1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -1164,6 +1168,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1416,6 +1421,7 @@ children = ( 5653EBA420961FD300F46237 /* Association */, 56B6EF62208CB762002F0ACB /* ColumnExpressionTests.swift */, + 56EA63CB209C7F31009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -2263,6 +2269,7 @@ 560FC56C1CB00B880014AA8E /* UpdateStatementTests.swift in Sources */, 5653EBE020961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 560FC56D1CB00B880014AA8E /* DatabaseMigratorTests.swift in Sources */, + 56EA63CC209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 560FC5701CB00B880014AA8E /* DatabasePoolCollationTests.swift in Sources */, 560FC5711CB00B880014AA8E /* RecordPrimaryKeySingleTests.swift in Sources */, 560FC5721CB00B880014AA8E /* StatementColumnConvertibleTests.swift in Sources */, @@ -2424,6 +2431,7 @@ 5671562F1CB16729007DC145 /* RecordPrimaryKeySingleTests.swift in Sources */, 5653EBE120961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 567156301CB16729007DC145 /* StatementColumnConvertibleTests.swift in Sources */, + 56EA63CD209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */, 5672DE5B1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */, 56B021CB1D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */, @@ -2695,6 +2703,7 @@ 56AFCA3E1CB1AA9900F48B96 /* DatabasePoolCollationTests.swift in Sources */, 5653EBE220961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56FF455B1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, + 56EA63CE209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 56AFCA3F1CB1AA9900F48B96 /* RecordPrimaryKeySingleTests.swift in Sources */, 56AFCA411CB1AA9900F48B96 /* StatementColumnConvertibleTests.swift in Sources */, 56AFCA421CB1AA9900F48B96 /* DatabasePoolFunctionTests.swift in Sources */, @@ -2856,6 +2865,7 @@ 56AFCA931CB1ABC800F48B96 /* UpdateStatementTests.swift in Sources */, 5653EBE320961FE800F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 56AFCA941CB1ABC800F48B96 /* DatabaseMigratorTests.swift in Sources */, + 56EA63CF209C7F31009715B8 /* DerivableRequestTests.swift in Sources */, 5657AB641D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, 56FF455C1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */, 56AFCA971CB1ABC800F48B96 /* DatabasePoolCollationTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 90f2ee9c5..fcf06e10f 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -318,6 +318,8 @@ 56DAA2E01DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; }; 56E06F141E859069008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; 56E06F171E85906D008AE2A4 /* Fixits-0.102.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */; }; + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; 56ED8A7F1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; }; 56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; }; @@ -827,6 +829,7 @@ 56E06F051E859064008AE2A4 /* Fixits-0.102.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Fixits-0.102.0.swift"; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DerivableRequestTests.swift; sourceTree = ""; }; 56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderTests.swift; sourceTree = ""; }; 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = ""; }; 56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = ""; }; @@ -1062,6 +1065,7 @@ children = ( 5653EB5620961F8900F46237 /* Association */, 56B6EF5E208CB746002F0ACB /* ColumnExpressionTests.swift */, + 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */, 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */, 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */, 5698AC021D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift */, @@ -1938,6 +1942,7 @@ F3BA80F81CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */, 5653EB7D20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698AC0A1D9B9FCF0056AF8C /* QueryInterfaceExtensibilityTests.swift in Sources */, + 56EA63CA209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA80E91CFB3016003DC1BA /* RowAdapterTests.swift in Sources */, 562393371DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 5674A7161F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */, @@ -2209,6 +2214,7 @@ F3BA80E61CFB3012003DC1BA /* DatabaseFunctionTests.swift in Sources */, 5653EB7C20961FB200F46237 /* AssociationBelongsToSQLTests.swift in Sources */, 5698ACDA1DA925430056AF8C /* RowTestCase.swift in Sources */, + 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */, F3BA811D1CFB305F003DC1BA /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, F3BA80AD1CFB2FA6003DC1BA /* DataMemoryTests.swift in Sources */, 5698ACB91DA6285E0056AF8C /* FTS3TokenizerTests.swift in Sources */, diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift new file mode 100644 index 000000000..bc5a9381a --- /dev/null +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -0,0 +1,85 @@ +import XCTest +#if GRDBCIPHER +import GRDBCipher +#elseif GRDBCUSTOMSQLITE +import GRDBCustomSQLite +#else +import GRDB +#endif + +private struct Author: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var name: String + var country: String + + static let databaseTableName = "author" + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} +private struct Book: FetchableRecord, PersistableRecord, Codable { + var id: Int64 + var authorId: Int64 + var title: String + + static let databaseTableName = "book" + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} + +private var libraryMigrator: DatabaseMigrator = { + var migrator = DatabaseMigrator() + migrator.registerMigration("library") { db in + try db.create(table: "author") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + t.column("country", .text).notNull() + } + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer).notNull().references("author") + t.column("title", .text).notNull() + } + } + migrator.registerMigration("fixture") { db in + try Author(id: 1, name: "Melville", country: "US").insert(db) + try Author(id: 2, name: "Proust", country: "FR").insert(db) + try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) + try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) + try Book(id: 3, authorId: 2, title: "Le Côté de Guermantes").insert(db) + } + return migrator +}() + +// One extension... +extension DerivableRequest where RowDecoder == Author { + func filter(country: String) -> Self { + return filter(Column("country") == country) + } +} + +class DerivableRequestTests: GRDBTestCase { + func testDerivation() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // ... for two requests (1) + let frenchAuthorNames = try Author.all() + .filter(country: "FR") + .fetchAll(db) + .map { $0.name } + XCTAssertEqual(frenchAuthorNames, ["Proust"]) + + // ... for two requests (2) + let frenchBookTitles = try Book + .joining(required: Book.author.filter(country: "FR")) + .order(Column("title")) + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann", "Le Côté de Guermantes"]) + } + } +} diff --git a/Tests/GRDBTests/SQLRequestTests.swift b/Tests/GRDBTests/SQLRequestTests.swift index 68c2beb6a..d54e3d1ab 100644 --- a/Tests/GRDBTests/SQLRequestTests.swift +++ b/Tests/GRDBTests/SQLRequestTests.swift @@ -65,7 +65,7 @@ class SQLRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let request = CustomRequest() - let sqlRequest = try SQLRequest(db, request: request) + let sqlRequest = try SQLRequest(db, request: request) XCTAssertEqual(sqlRequest.sql, "SELECT ? AS a, ? AS b") XCTAssertEqual(sqlRequest.arguments, [1, "foo"]) XCTAssertEqual(try sqlRequest.fetchOne(db)!, ["a": 1, "b": "foo"]) From 264bceee2a6321a72c3dbb26517ee9437d2231df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 4 May 2018 14:28:29 +0200 Subject: [PATCH 236/348] Cleanup --- .../Association/BelongsToAssociation.swift | 42 +++++++----------- .../Association/HasManyAssociation.swift | 42 +++++++----------- .../Association/HasOneAssociation.swift | 44 +++++++------------ GRDB/QueryInterface/RequestProtocols.swift | 5 +-- 4 files changed, 47 insertions(+), 86 deletions(-) diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index b20853c8d..b2f7b111d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -1,10 +1,5 @@ -public struct BelongsToAssociation : Association, TableRequest where - Origin: TableRecord, - Destination: TableRecord -{ - fileprivate let foreignKeyRequest: ForeignKeyRequest - - // Association conformance +public struct BelongsToAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest /// :nodoc: public typealias OriginRowDecoder = Origin @@ -25,7 +20,7 @@ public struct BelongsToAssociation : Association, TableRequ /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: true).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: @@ -34,17 +29,17 @@ public struct BelongsToAssociation : Association, TableRequ association.request = transform(request) return association } - - // TableRequest conformance - +} + +extension BelongsToAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func belongsTo( - _ request: QueryInterfaceRequest, + /// TODO + public static func belongsTo( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> BelongsToAssociation @@ -55,20 +50,13 @@ extension TableRecord { destinationTable: Destination.databaseTableName, foreignKey: foreignKey) - return BelongsToAssociation( + let joinConditionRequest = ForeignKeyJoinConditionRequest( foreignKeyRequest: foreignKeyRequest, + originIsLeft: true) + + return BelongsToAssociation( + joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, - request: AssociationRequest(request)) - } - - /// TODO - public static func belongsTo( - _ destination: Destination.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> BelongsToAssociation - where Destination: TableRecord - { - return belongsTo(Destination.all(), key: key, using: foreignKey) + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 3143efadc..249593787 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -1,10 +1,5 @@ -public struct HasManyAssociation : Association, TableRequest where - Origin: TableRecord, - Destination: TableRecord -{ - fileprivate let foreignKeyRequest: ForeignKeyRequest - - // Association conformance +public struct HasManyAssociation: Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest /// :nodoc: public typealias OriginRowDecoder = Origin @@ -25,7 +20,7 @@ public struct HasManyAssociation : Association, TableReques /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: @@ -34,17 +29,17 @@ public struct HasManyAssociation : Association, TableReques association.request = transform(request) return association } - - // TableRequest conformance - +} + +extension HasManyAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func hasMany( - _ request: QueryInterfaceRequest, + /// TODO + public static func hasMany( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasManyAssociation @@ -55,20 +50,13 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - return HasManyAssociation( + let joinConditionRequest = ForeignKeyJoinConditionRequest( foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + + return HasManyAssociation( + joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, - request: AssociationRequest(request)) - } - - /// TODO - public static func hasMany( - _ destination: Destination.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> HasManyAssociation - where Destination: TableRecord - { - return hasMany(Destination.all(), key: key, using: foreignKey) + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 9fe310bf9..b5ef7be12 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -1,11 +1,6 @@ -public struct HasOneAssociation : Association, TableRequest where - Origin: TableRecord, - Destination: TableRecord -{ - fileprivate let foreignKeyRequest: ForeignKeyRequest - - // Association conformance - +public struct HasOneAssociation : Association { + fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest + /// :nodoc: public typealias OriginRowDecoder = Origin @@ -25,7 +20,7 @@ public struct HasOneAssociation : Association, TableRequest /// :nodoc: public func joinCondition(_ db: Database) throws -> JoinCondition { - return try ForeignKeyJoinConditionRequest(foreignKeyRequest: foreignKeyRequest, originIsLeft: false).fetch(db) + return try joinConditionRequest.fetch(db) } /// :nodoc: @@ -34,17 +29,17 @@ public struct HasOneAssociation : Association, TableRequest association.request = transform(request) return association } - - // TableRequest conformance - +} + +extension HasOneAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } } extension TableRecord { - // TODO: Make it public if and only if we really want to build an association from any request - static func hasOne( - _ request: QueryInterfaceRequest, + /// TODO + public static func hasOne( + _ destination: Destination.Type, key: String? = nil, using foreignKey: ForeignKey? = nil) -> HasOneAssociation @@ -55,20 +50,13 @@ extension TableRecord { destinationTable: databaseTableName, foreignKey: foreignKey) - return HasOneAssociation( + let joinConditionRequest = ForeignKeyJoinConditionRequest( foreignKeyRequest: foreignKeyRequest, + originIsLeft: false) + + return HasOneAssociation( + joinConditionRequest: joinConditionRequest, key: key ?? Destination.databaseTableName, - request: AssociationRequest(request)) - } - - /// TODO - public static func hasOne( - _ destination: Destination.Type, - key: String? = nil, - using foreignKey: ForeignKey? = nil) - -> HasOneAssociation - where Destination: TableRecord - { - return hasOne(Destination.all(), key: key, using: foreignKey) + request: AssociationRequest(Destination.all())) } } diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 02db9a401..3588a77d3 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -324,10 +324,7 @@ extension OrderedRequest { /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) /// -/// The base protocol for all requests that can be refined: -/// -/// extension DerivableRequest where RowDecoder: Player { -/// } +/// The base protocol for all requests that can be refined. public protocol DerivableRequest: SelectionRequest, FilteredRequest, OrderedRequest { associatedtype RowDecoder } From 2d008b8c54eac1a892585208b85f20c8dfec0f92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 4 May 2018 08:56:57 +0200 Subject: [PATCH 237/348] Yet another request protocols update, in order to empower RxGRDB --- CHANGELOG.md | 4 +- GRDB/Core/DatabaseRegion.swift | 12 +-- GRDB/Core/FetchRequest.swift | 80 ++++++++--------- GRDB/Core/Statement.swift | 6 +- GRDB/Core/StatementAuthorizer.swift | 8 +- GRDB/Legacy/Fixits-3.0.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 14 +-- .../QueryInterfaceRequest.swift | 4 +- GRDB/Record/FetchedRecordsController.swift | 4 +- Tests/GRDBTests/ColumnExpressionTests.swift | 20 ++--- Tests/GRDBTests/DatabaseRegionTests.swift | 86 +++++++++---------- Tests/GRDBTests/SelectStatementTests.swift | 2 +- 12 files changed, 115 insertions(+), 127 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ffba504c4..3cdd1b3ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,11 +46,11 @@ Release Notes + associatedtype RowDecoder + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + func fetchCount(_ db: Database) throws -> Int -+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion ++ func databaseRegion(_ db: Database) throws -> DatabaseRegion +} +extension FetchRequest { + func fetchCount(_ db: Database) throws -> Int -+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion ++ func databaseRegion(_ db: Database) throws -> DatabaseRegion + func asRequest(of type: T.Type) -> AnyFetchRequest + func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest +} diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index b1e7383ec..ebb9fbbca 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -16,16 +16,16 @@ /// You don't create a database region directly. Instead, you use one of /// those methods: /// -/// - `SelectStatement.fetchedRegion`: +/// - `SelectStatement.databaseRegion`: /// /// let statement = db.makeSelectStatement("SELECT name, score FROM player") -/// print(statement.fetchedRegion) +/// print(statement.databaseRegion) /// // prints "player(name,score)" /// -/// - `Request.fetchedRegion(_:)` +/// - `Request.databaseRegion(_:)` /// /// let request = Player.filter(key: 1) -/// try print(request.fetchedRegion(db)) +/// try print(request.databaseRegion(db)) /// // prints "player(*)[1]" /// /// Database regions returned by requests can be more precise than regions @@ -34,11 +34,11 @@ /// /// // A plain statement /// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1") -/// statement.fetchedRegion // "player(*)" +/// statement.databaseRegion // "player(*)" /// /// // A query interface request that executes the same statement: /// let request = Player.filter(key: 1) -/// try request.fetchedRegion(db) // "player(*)[1]" +/// try request.databaseRegion(db) // "player(*)[1]" public struct DatabaseRegion: CustomStringConvertible, Equatable { private let tableRegions: [String: TableRegion]? private init(tableRegions: [String: TableRegion]?) { diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index cd03312c3..cf8995872 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -1,17 +1,17 @@ -// MARK: - DatabaseRequest +// MARK: - FetchRequest -/// The protocol for all types that request database values. -public protocol DatabaseRequest { - /// Returns the database region that the request looks into. - /// - /// - parameter db: A database connection. - func fetchedRegion(_ db: Database) throws -> DatabaseRegion -} - -// MARK: - SelectStatementRequest - -/// The protocol for all requests that run from a single select statement. -public protocol SelectStatementRequest: DatabaseRequest { +/// The protocol for all requests that run from a single select statement, and +/// tell how fetched rows should be interpreted. +/// +/// struct Player: FetchableRecord { ... } +/// let request: ... // Some FetchRequest that fetches Player +/// try request.fetchCursor(db) // Cursor of Player +/// try request.fetchAll(db) // [Player] +/// try request.fetchOne(db) // Player? +public protocol FetchRequest { + /// The type that tells how fetched database rows should be interpreted. + associatedtype RowDecoder + /// Returns a tuple that contains a prepared statement that is ready to be /// executed, and an eventual row adapter. /// @@ -30,9 +30,19 @@ public protocol SelectStatementRequest: DatabaseRequest { /// /// - parameter db: A database connection. func fetchCount(_ db: Database) throws -> Int + + /// Returns the database region that the request looks into. + /// + /// - parameter db: A database connection. + func databaseRegion(_ db: Database) throws -> DatabaseRegion } -extension SelectStatementRequest { +extension FetchRequest { + /// Returns an adapted request. + public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { + return AdaptedFetchRequest(self, adapter) + } + /// Returns the number of rows fetched by the request. /// /// This default implementation builds a naive SQL query based on the @@ -51,31 +61,9 @@ extension SelectStatementRequest { /// returned by the `prepare` method. /// /// - parameter db: A database connection. - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { let (statement, _) = try prepare(db) - return statement.fetchedRegion - } -} - -// MARK: - FetchRequest - -/// The protocol for all requests that run from a single select statement, and -/// tell how fetched rows should be interpreted. -/// -/// struct Player: FetchableRecord { ... } -/// let request: ... // Some FetchRequest that fetches Player -/// try request.fetchCursor(db) // Cursor of Player -/// try request.fetchAll(db) // [Player] -/// try request.fetchOne(db) // Player? -public protocol FetchRequest: SelectStatementRequest { - /// The type that tells how fetched database rows should be interpreted. - associatedtype RowDecoder -} - -extension FetchRequest { - /// Returns an adapted request. - public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest { - return AdaptedFetchRequest(self, adapter) + return statement.databaseRegion } } @@ -111,8 +99,8 @@ public struct AdaptedFetchRequest : FetchRequest { } /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try base.fetchedRegion(db) + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try base.databaseRegion(db) } } @@ -127,13 +115,13 @@ public struct AnyFetchRequest : FetchRequest { private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?) private let _fetchCount: (Database) throws -> Int - private let _fetchedRegion: (Database) throws -> DatabaseRegion + private let _databaseRegion: (Database) throws -> DatabaseRegion /// Creates a request that wraps and forwards operations to `request`. public init(_ request: Request) { _prepare = request.prepare _fetchCount = request.fetchCount - _fetchedRegion = request.fetchedRegion + _databaseRegion = request.databaseRegion } /// Creates a request whose `prepare()` method wraps and forwards @@ -149,9 +137,9 @@ public struct AnyFetchRequest : FetchRequest { return try Int.fetchOne(db, sql, arguments: statement.arguments)! } - _fetchedRegion = { db in + _databaseRegion = { db in let (statement, _) = try prepare(db) - return statement.fetchedRegion + return statement.databaseRegion } } @@ -166,8 +154,8 @@ public struct AnyFetchRequest : FetchRequest { } /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try _fetchedRegion(db) + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try _databaseRegion(db) } } diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index 092b3e623..cb3e30cd7 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -295,7 +295,7 @@ extension AuthorizedStatement { /// } public final class SelectStatement : Statement { /// The database region that the statement looks into. - public private(set) var fetchedRegion: DatabaseRegion + public private(set) var databaseRegion: DatabaseRegion /// Creates a prepared statement. /// @@ -316,7 +316,7 @@ public final class SelectStatement : Statement { prepFlags: Int32, authorizer: StatementCompilationAuthorizer) throws { - self.fetchedRegion = DatabaseRegion() + self.databaseRegion = DatabaseRegion() try super.init( database: database, statementStart: statementStart, @@ -326,7 +326,7 @@ public final class SelectStatement : Statement { GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.") - self.fetchedRegion = authorizer.region + self.databaseRegion = authorizer.databaseRegion } /// The number of columns in the resulting rows. diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 208150c5a..080820908 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -18,7 +18,7 @@ protocol StatementAuthorizer : class { /// A class that gathers information about one statement during its compilation. final class StatementCompilationAuthorizer : StatementAuthorizer { /// What this statements reads - var region = DatabaseRegion() + var databaseRegion = DatabaseRegion() /// What this statements writes var databaseEventKinds: [DatabaseEventKind] = [] @@ -66,10 +66,10 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { guard let columnName = cString2.map({ String(cString: $0) }) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table - region.formUnion(DatabaseRegion(table: tableName)) + databaseRegion.formUnion(DatabaseRegion(table: tableName)) } else { // SELECT column FROM table - region.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) + databaseRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) } return SQLITE_OK @@ -135,7 +135,7 @@ final class StatementCompilationAuthorizer : StatementAuthorizer { guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK } guard let cString2 = cString2 else { return SQLITE_OK } if sqlite3_stricmp(cString2, "COUNT") == 0 { - region = .fullDatabase + databaseRegion = .fullDatabase } return SQLITE_OK diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index 78f41549f..c4c25bc68 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -34,7 +34,7 @@ extension SelectStatement { public typealias SelectionInfo = DatabaseRegion /// :nodoc: - @available(*, unavailable, renamed:"fetchedRegion") + @available(*, unavailable, renamed:"databaseRegion") public var selectionInfo: DatabaseRegion { preconditionFailure() } } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 1eb8ec312..f63053f91 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -329,37 +329,37 @@ extension QueryInterfaceQuery { /// The database region that the request looks into. /// precondition: self is the result of finalizedQuery - func fetchedRegion(_ db: Database) throws -> DatabaseRegion { + func databaseRegion(_ db: Database) throws -> DatabaseRegion { let statement = try makeSelectStatement(db) - let region = statement.fetchedRegion + let databaseRegion = statement.databaseRegion // Can we intersect the region with rowIds? // // Give up unless request feeds from a single database table guard case .table(tableName: let tableName, alias: _) = source else { // TODO: try harder - return region + return databaseRegion } // Give up unless primary key is rowId let primaryKeyInfo = try db.primaryKey(tableName) guard primaryKeyInfo.isRowID else { - return region + return databaseRegion } // Give up unless there is a where clause guard let filter = try filterPromise.resolve(db) else { - return region + return databaseRegion } // The filter knows better guard let rowIds = filter.matchedRowIds(rowIdName: primaryKeyInfo.rowIDColumn) else { - return region + return databaseRegion } // Database regions are case-insensitive: use the canonical table name let canonicalTableName = try db.canonicalTableName(tableName) - return region.tableIntersection(canonicalTableName, rowIds: rowIds) + return databaseRegion.tableIntersection(canonicalTableName, rowIds: rowIds) } private var countQuery: QueryInterfaceQuery { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index d6af81c04..a7ab4b20d 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -38,8 +38,8 @@ extension QueryInterfaceRequest : FetchRequest { /// /// - parameter db: A database connection. /// :nodoc: - public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - return try query.finalizedQuery.fetchedRegion(db) + public func databaseRegion(_ db: Database) throws -> DatabaseRegion { + return try query.finalizedQuery.databaseRegion(db) } } diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 904895c9c..48dce6b61 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -105,7 +105,7 @@ public final class FetchedRecordsController { self.itemsAreIdenticalFactory = itemsAreIdenticalFactory self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - let region = try request.fetchedRegion(db) + let region = try request.databaseRegion(db) let itemsAreIdentical = try itemsAreIdenticalFactory(db) return (region, itemsAreIdentical) } @@ -165,7 +165,7 @@ public final class FetchedRecordsController { public func setRequest(_ request: Request) throws where Request: FetchRequest, Request.RowDecoder == Record { self.request = ItemRequest(request) (self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in - let region = try request.fetchedRegion(db) + let region = try request.databaseRegion(db) let itemsAreIdentical = try itemsAreIdenticalFactory(db) return (region, itemsAreIdentical) } diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index dae9e253e..22334f88f 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -58,11 +58,11 @@ class ColumnExpressionTests: GRDBTestCase { } // Test rowId column identification - try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.Columns.id).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") + try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "players(id,name,score)[1,2,3]") // Test specific column updates let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) @@ -120,11 +120,11 @@ class ColumnExpressionTests: GRDBTestCase { } // Test rowId column identification - try XCTAssertEqual(Player.filter(key: 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.Columns.id).fetchedRegion(db).description, "players(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).fetchedRegion(db).description, "players(id,name,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).fetchedRegion(db).description, "players(id,name,score)[1,2,3]") + try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "players(id,name,score)[1]") + try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "players(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "players(id,name,score)[1,2,3]") // Test specific column updates let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 4edded5e1..4f7d992ee 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -265,19 +265,19 @@ class DatabaseRegionTests : GRDBTestCase { let statement = try db.makeSelectStatement("SELECT foo.name FROM FOO JOIN BAR ON fooId = foo.id") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"]) .union(DatabaseRegion(table: "bar", columns: ["fooId"])) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "bar(fooId),foo(id,name)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM foo") if sqlite3_libversion_number() < 3019000 { let expectedRegion = DatabaseRegion.fullDatabase - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "full database") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "full database") } else { let expectedRegion = DatabaseRegion(table: "foo") - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(*)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } } } @@ -295,117 +295,117 @@ class DatabaseRegionTests : GRDBTestCase { do { let request = Record.all() - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("a") == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("id") >= 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter((Column("id") == 1) || (Column("a") == "foo")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } // No rowId do { let request = Record.filter(Column("id") == nil) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(Column("id") === nil) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil == Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil === Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter((Column("id") == 1) && (Column("id") == 2)) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(key: 1).filter(key: 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "empty") + try XCTAssertEqual(request.databaseRegion(db).description, "empty") } // Single rowId do { let request = Record.filter(Column("id") == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") === 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") == 1 && Column("a") == "foo") - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column.rowID == 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 == Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column("id")) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column.rowID) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(key: 1) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(Column("a") == "foo") - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } // Multiple rowIds do { let request = Record.filter(Column("id") == 1 || Column.rowID == 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter((Column("id") == 1 && Column("a") == "foo") || Column.rowID == 2) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter([1, 2, 3].contains(Column("id"))) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter([1, 2, 3].contains(Column.rowID)) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter(keys: [1, 2, 3]) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } } } @@ -433,14 +433,14 @@ class DatabaseRegionTests : GRDBTestCase { .including(optional: A.b.filter(key: 2)) .including(optional: A.c.filter(keys: [1, 2, 3])) // This test will fail when we are able to improve regions of joined requestt - try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)") + try XCTAssertEqual(request.databaseRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)") } do { let request = B.filter(key: 1) .including(optional: B.a.filter(key: 2) .including(optional: A.c.filter(keys: [1, 2, 3]))) // This test will fail when we are able to improve regions of joined requestt - try XCTAssertEqual(request.fetchedRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") + try XCTAssertEqual(request.databaseRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") } } } @@ -454,20 +454,20 @@ class DatabaseRegionTests : GRDBTestCase { } let request = Record.filter(keys: [1, 2, 3]) - try XCTAssertEqual(request.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") do { let derivedRequest: AnyFetchRequest = AnyFetchRequest(request) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let derivedRequest: AdaptedFetchRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)[1,2,3]") + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { // SQL request loses region info let derivedRequest = try SQLRequest(db, request: request) - try XCTAssertEqual(derivedRequest.fetchedRegion(db).description, "foo(a,id)") + try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)") } } } @@ -506,20 +506,20 @@ class DatabaseRegionTests : GRDBTestCase { do { let statement = try db.makeSelectStatement("SELECT rowid FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeSelectStatement("SELECT _ROWID_ FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeSelectStatement("SELECT oID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) - XCTAssertEqual(statement.fetchedRegion, expectedRegion) - XCTAssertEqual(statement.fetchedRegion.description, "foo(ROWID)") + XCTAssertEqual(statement.databaseRegion, expectedRegion) + XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } } } diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index d48eecad1..66b6cc1ba 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -196,7 +196,7 @@ class SelectStatementTests : GRDBTestCase { let doubtfulCountFunction = (sqlite3_libversion_number() < 3019000) - let observers = statements.map { Observer(region: $0.fetchedRegion) } + let observers = statements.map { Observer(region: $0.databaseRegion) } if doubtfulCountFunction { XCTAssertEqual(observers.map { $0.region.description }, ["table1(a,b,id,id3,id4)","table1(a,id,id3)", "table1(a,id),table2(a,id)", "full database"]) } else { From dc7bdfed50e537202a02a9e7bf11271446919845 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 5 May 2018 12:02:50 +0200 Subject: [PATCH 238/348] More fixits for DatabaseRegion --- GRDB/Legacy/Fixits-3.0.swift | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/GRDB/Legacy/Fixits-3.0.swift b/GRDB/Legacy/Fixits-3.0.swift index c4c25bc68..6ec160f41 100644 --- a/GRDB/Legacy/Fixits-3.0.swift +++ b/GRDB/Legacy/Fixits-3.0.swift @@ -36,6 +36,10 @@ extension SelectStatement { /// :nodoc: @available(*, unavailable, renamed:"databaseRegion") public var selectionInfo: DatabaseRegion { preconditionFailure() } + + /// :nodoc: + @available(*, unavailable, renamed:"databaseRegion") + public var fetchedRegion: DatabaseRegion { preconditionFailure() } } extension DatabaseEventKind { @@ -72,3 +76,10 @@ extension Row { @available(*, unavailable, message: "Use row.scopes[name] instead") public func scoped(on name: String) -> Row? { preconditionFailure() } } + +extension FetchRequest { + + /// :nodoc: + @available(*, unavailable, renamed:"databaseRegion(_:)") + public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { preconditionFailure() } +} From 214748fe5acf7e4db23cae4caec5763d8432103d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 09:11:00 +0200 Subject: [PATCH 239/348] DatabaseRegion.fullDatabase is public --- GRDB/Core/DatabaseRegion.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index ebb9fbbca..9758b1b41 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -51,8 +51,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable { return tableRegions.isEmpty } - /// The full database: (All columns in all tables) × (all rows) - static let fullDatabase = DatabaseRegion(tableRegions: nil) + /// The region that covers the full database: all columns and all rows + /// from all tables. + public static let fullDatabase = DatabaseRegion(tableRegions: nil) /// The empty database region public init() { From cce0e332e02815a2e5106a0cd009eeeb62ea84ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 10:01:10 +0200 Subject: [PATCH 240/348] Update documentation of FetchRequest protocol --- README.md | 94 +++++++++++++------------------------------------------ 1 file changed, 21 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index 84a2223c5..6d593e929 100644 --- a/README.md +++ b/README.md @@ -4105,94 +4105,42 @@ Player.customRequest(...).rx }) ``` -- [DatabaseRequest Protocol](#databaserequest-protocol) -- [SelectStatementRequest Protocol](#selectstatementrequest-protocol) - [FetchRequest Protocol](#fetchrequest-protocol) - [Building Custom Requests](#building-custom-requests) - [Fetching From Custom Requests](#fetching-from-custom-requests) -### DatabaseRequest Protocol - -**DatabaseRequest** is the highest-level protocol for all types that request database values. It does not tell how values are fetched, but it allows database observation tools ([transaction observers](#transactionobserver-protocol) and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB)) the ability to notify changes in the request content. - -```swift -protocol DatabaseRequest { - func fetchedRegion(_ db: Database) throws -> DatabaseRegion -} -``` - -**You'll use DatabaseRequest when you want to encapsulate your most complex fetching strategies.** - -For example: - -```swift -struct LibraryRequest: DatabaseRequest { - func fetchAll(_ db: Database) throws -> [(Author, [Books])] { - let authors = try Author.fetchAll(db) - let books = try Dictionary( - grouping: Book.fetchAll(db), - by: { book in book.authorId }) - return authors.map { author in (author, books[author.id]!) } - } - - func fetchedRegion(_ db: Database) throws -> DatabaseRegion { - let authorsRegion = try Author.all().fetchedRegion(db) - let booksRegion = try Book.all().fetchedRegion(db) - return authorsRegion.union(booksRegion) - } -} - -// Track library content with RxGRDB -let request = LibraryRequest() -dbQueue.rx - .fetchTokens(in: [request]) - .mapFetch { db in try request.fetchAll(db) } - .subscribe(onNext: { library: [(Author, [Books])] in - print("Library has changed.") - }) -``` - -See [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/2.10/Structs/DatabaseRegion.html) reference for more information. - - -### SelectStatementRequest Protocol - -**SelectStatementRequest** is the protocol for all requests that run a single select statement: - -```swift -protocol SelectStatementRequest: DatabaseRequest { - /// A tuple that contains a prepared statement, and an eventual row adapter. - func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) - - /// The number of rows fetched by the request. - func fetchCount(_ db: Database) throws -> Int -} -``` - -The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). - -The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. - -The `fetchedRegion` method inherited from [DatabaseRequest](#databaserequest-protocol) is also given a default implementation, based on the statement returned by `prepare`. - -There are few use cases for SelectStatementRequest. Usually, your custom requests will adopt its derivative [FetchRequest](#fetchrequest-protocol), introduced below: - - ### FetchRequest Protocol **FetchRequest** is the protocol for all requests that run from a single select statement, and know how fetched rows should be interpreted: ```swift -protocol FetchRequest: SelectStatementRequest { +protocol FetchRequest { /// The type that tells how fetched rows should be decoded associatedtype RowDecoder + + /// A tuple that contains a prepared statement, and an eventual row adapter. + func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) + + /// The number of rows fetched by the request. + func fetchCount(_ db: Database) throws -> Int + + /// Returns the database region that the request looks into. + /// + /// - parameter db: A database connection. + func databaseRegion(_ db: Database) throws -> DatabaseRegion } ``` -The `RowDecoder` associated type can be any type. Yet, not all types have built-in support: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. +When the `RowDecoder` associated type is [Row](#fetching-rows), or a [value](#value-queries), or a type that conforms to [FetchableRecord], the request can fetch: see [Fetching From Custom Requests](#fetching-from-custom-requests) below. -FetchRequest is adopted, for example, by [query interface requests](#requests): +The `prepare` method returns a prepared statement and an optional row adapter. The [prepared statement](#prepared-statements) tells which SQL query should be executed. The row adapter helps presenting the fetched rows in the way expected by the row decoders (see [row adapter](#row-adapters)). + +The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. + +The `databaseRegion` method is involved in [database observation](#database-changes-observation). It is given a default implementation, based on the statement returned by `prepare`. For more information, see [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/2.10/Structs/DatabaseRegion.html), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). + +The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): ```swift // A FetchRequest whose RowDecoder associated type is Player: @@ -4202,7 +4150,7 @@ let request = Player.all() ### Building Custom Requests -**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts one of the request protocols described above ([FetchRequest](#fetchrequest-protocol), [SelectStatementRequest](#selectstatementrequest-protocol), or [DatabaseRequest](#databaserequest-protocol)). +**To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. - [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: From 175c96cd38b061d72df6b2a96cf0a55e43e7d6f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 10:03:07 +0200 Subject: [PATCH 241/348] Update documentation of FetchRequest protocol --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 6d593e929..24ee271ae 100644 --- a/README.md +++ b/README.md @@ -4125,9 +4125,7 @@ protocol FetchRequest { /// The number of rows fetched by the request. func fetchCount(_ db: Database) throws -> Int - /// Returns the database region that the request looks into. - /// - /// - parameter db: A database connection. + /// The database region that the request looks into. func databaseRegion(_ db: Database) throws -> DatabaseRegion } ``` From cc7cf597f31110485a0526e53e89f33a550d7207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 10:50:14 +0200 Subject: [PATCH 242/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 53 ++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a9f97e30a..0640b817c 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -323,6 +323,58 @@ For other incompatible changes, let the compiler fixits guide you. ## If You Use RxGRDB +Not only was RxGRDB upgraded for GRDB3, but some APIs have slighly changed. + +Did you track multiple requests at the same time with "fetch tokens"? + +```swift +// GRDB2 +dbQueue.rx + .fetchTokens(in: [...]) + .mapFetch { db in ... } + .subscribe(...) +``` + +Now you'll write instead: + +```swift +// GRDB3 +dbQueue.rx + .fetch(from: [...]) { db in ... } + .subscribe(...) +``` + +It's just a syntactic change, without any impact on the runtime. + +RxGRDB from GRDB3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition: + +```swift +// GRDB2: Track a team and its players +let teamId = 1 +let teamRequest = Team.filter(key: teamId) +let playersRequest = Player.filter(teamId: teamId) +dbQueue.rx + .fetchTokens(in: [teamRequest, playersRequest]) + .mapFetch { db -> TeamInfo? in + guard let team = try teamRequest.fetchOne(db) else { + return nil + } + let players = try playersRequest.fetchAll(db) + return TeamInfo(team: team, players: players) + } + .subscribe(onNext: { teamInfo: TeamInfo? in + ... + }) + +// GRDB3: Track a team and its players +let request = TeamInfoRequest(teamId: 1) +dbQueue.rx + .fetch(from: [request]) { try request.fetchOne($0) } + .subscribe(onNext: { teamInfo: TeamInfo? in + ... + }) +``` + [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations @@ -347,3 +399,4 @@ For other incompatible changes, let the compiler fixits guide you. [record protocols]: ../README.md#record-protocols-overview [Custom requests]: ../README.md#custom-requests [query interface]: ../README.md#the-query-interface +[DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/GRDB3/README.md#databaseregionconvertible-protocol From 7a520f32698505a9d5b3a0ed36b363f32ac316e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 10:55:39 +0200 Subject: [PATCH 243/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 0640b817c..9e427dc9f 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -29,7 +29,6 @@ Update your Podfile: ```ruby pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift', branch: 'GRDB3' -# pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' ``` ### Swift Package Manager @@ -323,9 +322,13 @@ For other incompatible changes, let the compiler fixits guide you. ## If You Use RxGRDB -Not only was RxGRDB upgraded for GRDB3, but some APIs have slighly changed. +To install the GRDB3 flavor of RxGRDB, update your Podfile: -Did you track multiple requests at the same time with "fetch tokens"? +```ruby +pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' +``` + +Some APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"? ```swift // GRDB2 @@ -346,7 +349,9 @@ dbQueue.rx It's just a syntactic change, without any impact on the runtime. -RxGRDB from GRDB3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition: +RxGRDB from GRDB3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition. + +For example: ```swift // GRDB2: Track a team and its players From 6434f0cdb1ecc5e8a446bc424da6e7c8cdfd0d03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 11:09:44 +0200 Subject: [PATCH 244/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 9e427dc9f..74654f8a9 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -6,6 +6,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up **For all users** - [How To Upgrade] +- [Swift 4.1 Required] - [iOS 8 Sunsetting] - [Database Schema Recommendations] - [Record Protocols Renaming] @@ -52,10 +53,14 @@ git checkout GRDB3 git pull ``` +## Swift 4.1 Required + +GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+. + ## iOS 8 Sunsetting -GRDB 3 is only tested on iOS 9+. Code that targets older versions of SQLite and iOS is still there, but is not supported. +GRDB 3 is only tested on iOS 9+, due to a limitation in XCode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. ## Database Schema Recommendations @@ -68,7 +73,7 @@ GRDB 3 still accepts any database, but brings two schema recommendations: When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not. - GRDB3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: + GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key: ```diff try db.create(table: "author") { t in @@ -322,7 +327,7 @@ For other incompatible changes, let the compiler fixits guide you. ## If You Use RxGRDB -To install the GRDB3 flavor of RxGRDB, update your Podfile: +To install the GRDB 3 flavor of RxGRDB, update your Podfile: ```ruby pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' @@ -331,7 +336,7 @@ pod 'RxGRDB', git: 'https://github.com/groue/RxGRDB', branch: 'GRDB3' Some APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"? ```swift -// GRDB2 +// GRDB 2 dbQueue.rx .fetchTokens(in: [...]) .mapFetch { db in ... } @@ -341,7 +346,7 @@ dbQueue.rx Now you'll write instead: ```swift -// GRDB3 +// GRDB 3 dbQueue.rx .fetch(from: [...]) { db in ... } .subscribe(...) @@ -349,12 +354,12 @@ dbQueue.rx It's just a syntactic change, without any impact on the runtime. -RxGRDB from GRDB3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition. +RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition. For example: ```swift -// GRDB2: Track a team and its players +// GRDB 2: Track a team and its players let teamId = 1 let teamRequest = Team.filter(key: teamId) let playersRequest = Player.filter(teamId: teamId) @@ -371,7 +376,7 @@ dbQueue.rx ... }) -// GRDB3: Track a team and its players +// GRDB 3: Track a team and its players let request = TeamInfoRequest(teamId: 1) dbQueue.rx .fetch(from: [request]) { try request.fetchOne($0) } @@ -405,3 +410,4 @@ dbQueue.rx [Custom requests]: ../README.md#custom-requests [query interface]: ../README.md#the-query-interface [DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/GRDB3/README.md#databaseregionconvertible-protocol +[conditional conformance]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md From 9c9217727c143e3eb09df61884c5acaf9b1332e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 11:10:42 +0200 Subject: [PATCH 245/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 74654f8a9..7b28766f7 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -389,7 +389,8 @@ dbQueue.rx [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations [Record Protocols Renaming]: #record-protocols-renaming -[iOS 8 Sunsetting]: @ios-8-sunsetting +[Swift 4.1 Required]: #swift-41-required +[iOS 8 Sunsetting]: #ios-8-sunsetting [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools [If You Use Database Snapshots]: #if-you-use-database-snapshots From 15299eaac0cff4d9b85b3108298da2964ccbf8e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 11:53:19 +0200 Subject: [PATCH 246/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 79 +++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 2 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 7b28766f7..a60ff0af2 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -10,6 +10,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [iOS 8 Sunsetting] - [Database Schema Recommendations] - [Record Protocols Renaming] +- [Columns Definition] **By topic** @@ -18,6 +19,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [If You Use Database Snapshots] - [If You Use Custom Requests] - [If You Use RxGRDB] +- [Notable Documentation Updates] ## How to Upgrade @@ -145,6 +147,64 @@ GRDB 3 has renamed the [record protocols]: After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits. +## Columns Definition + +GRDB 2 has you define columns of the query interface with the Column type: + +```swift +// GRDB 2 +let nameColumn = Column("name") +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +``` + +A recommended practice was to define an enum namespace in the Record type: + +```swift +// GRDB 2 +struct Player: RowConvertible, TableMapping { + enum Columns { + static let id = Column("id") + static let name = Column("name") + static let score = Column("score") + } + + init(row: Row) { + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } +} +``` + +In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums: + +```swift +// GRDB 3 +struct Player: RowConvertible, TableMapping { + enum Columns: String, ColumnExpression { + case id, name, score + } + + init(row: Row) { + id = row[Columns.id] + name = row[Columns.name] + score = row[Columns.score] + } +} +``` + +GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type: + +```swift +struct TypedColumn: ColumnExpression { + var name: String + var sqlType: String +} +let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR") +let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +``` + + ## If You Use Database Queues With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods: @@ -322,7 +382,7 @@ extension Player { let players = try Player.filter(color: .red).fetchAll(db) ``` -For other incompatible changes, let the compiler fixits guide you. +See the updated [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests) chapter for more information. ## If You Use RxGRDB @@ -386,9 +446,23 @@ dbQueue.rx ``` +## Notable Documentation Updates + +If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter: + +- [Database Queues](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-queues): focus on the new `read` and `write` methods. +- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as an advanced and potentially dangerous feature. +- [ScopeAdapter](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#scopeadapter): do you use row adapters? If so, have a look. +- [Examples of Record Definitions](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Migrations](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). + + [How To Upgrade]: #how-to-upgrade [Database Schema Recommendations]: #database-schema-recommendations [Record Protocols Renaming]: #record-protocols-renaming +[Columns Definition]: #columns-definition [Swift 4.1 Required]: #swift-41-required [iOS 8 Sunsetting]: #ios-8-sunsetting [If You Use Database Queues]: #if-you-use-database-queues @@ -396,6 +470,7 @@ dbQueue.rx [If You Use Database Snapshots]: #if-you-use-database-snapshots [If You Use Custom Requests]: #if-you-use-custom-requests [If You Use RxGRDB]: #if-you-use-rxgrdb +[Notable Documentation Updates]: #notable-documentation-updates [FetchedRecordsController]: ../README.md#fetchedrecordscontroller [RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB [Associations]: AssociationsBasics.md @@ -411,4 +486,4 @@ dbQueue.rx [Custom requests]: ../README.md#custom-requests [query interface]: ../README.md#the-query-interface [DatabaseRegionConvertible]: https://github.com/groue/RxGRDB/blob/GRDB3/README.md#databaseregionconvertible-protocol -[conditional conformance]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md +[conditional conformances]: https://github.com/apple/swift-evolution/blob/master/proposals/0143-conditional-conformances.md From 26607ba1937bdb81781347e6ef09185cdfde3f34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 11:56:02 +0200 Subject: [PATCH 247/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index a60ff0af2..b06ca7fac 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -157,7 +157,7 @@ let nameColumn = Column("name") let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) ``` -A recommended practice was to define an enum namespace in the Record type: +A recommended practice was to define enum namespaces in record types: ```swift // GRDB 2 @@ -437,6 +437,7 @@ dbQueue.rx }) // GRDB 3: Track a team and its players +struct TeamInfoRequest: DatabaseRegionConvertible { ... } let request = TeamInfoRequest(teamId: 1) dbQueue.rx .fetch(from: [request]) { try request.fetchOne($0) } From 6db0831bfd503e7bf44fcb59da9c3b652987917c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 12:12:11 +0200 Subject: [PATCH 248/348] fix links --- Documentation/AssociationsBasics.md | 44 ++++++++++++++--------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 1a27d2d08..6bcb6441a 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -151,7 +151,7 @@ struct Author: TableRecord { The **BelongsTo** association between a book and its author needs that the database table for books has a column that points to the table for authors: -![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/BelongsToSchema.svg) See [Convention for the BelongsTo Association] for some sample code that defines the database schema for such an association. @@ -175,7 +175,7 @@ struct Demographics: TableRecord { The **HasOne** association between a country and its demographics needs that the database table for demographics has a column that points to the table for countries: -![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasOneSchema.svg) See [Convention for the HasOne Association] for some sample code that defines the database schema for such an association. @@ -198,7 +198,7 @@ struct Book: TableRecord { The **HasMany** association between an author and its books needs that the database table for books has a column that points to the table for authors: -![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasManySchema.svg) See [Convention for the HasMany Association] for some sample code that defines the database schema for such an association. @@ -211,7 +211,7 @@ The distinction is in where you place the database foreign key. The record that A country **has one** demographic profile, a demographic profile **belongs to** a country: -![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasOneSchema.svg) ```swift struct Country: TableRecord, FetchableRecord { @@ -236,7 +236,7 @@ struct Employee { } ``` -![RecursiveSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/RecursiveSchema.svg) +![RecursiveSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/RecursiveSchema.svg) The matching [migration] would look like: @@ -322,7 +322,7 @@ See [The Structure of a Joined Request] for more information. Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. -![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/BelongsToSchema.svg) The matching [migration] could look like: @@ -381,7 +381,7 @@ See [Foreign Keys] for more information. Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. -![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasOneSchema.svg) +![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasOneSchema.svg) The matching [migration] could look like: @@ -441,7 +441,7 @@ See [Foreign Keys] for more information. Foreign keys are the recommended way to declare relationships between database tables. Not only will SQLite guarantee the integrity of your data, but GRDB will be able to use those foreign keys to automatically configure your associations. -![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/HasManySchema.svg) +![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasManySchema.svg) The matching [migration] could look like: @@ -500,7 +500,7 @@ See [Foreign Keys] for more information. In the example below, the `book.authorId` column is automatically used to link a book to its author: -![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/BelongsToSchema.svg) +![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/BelongsToSchema.svg) ```swift struct Book: TableRecord { @@ -516,7 +516,7 @@ But this requires the database schema to define a foreign key between the book a Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another. -![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) +![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to author", or "Could not infer foreign key from book to author". @@ -777,7 +777,7 @@ The request above fetches all books, along with their author's country. **You can filter associated records.** -The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can filter associated records as well: +The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#requests), can filter associated records as well: ```swift // SELECT book.* @@ -802,7 +802,7 @@ Those extra filtering options require **[Table Aliases]**, introduced below. **You can sort fetched results according to associated records.** -The `order()` method, that you already know for [sorting simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#requests), can sort associated records as well: +The `order()` method, that you already know for [sorting simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#requests), can sort associated records as well: ```swift // SELECT book.*, person.* @@ -891,7 +891,7 @@ Modifying `databaseSelection` not only affects joined requests, but all requests let request = RestrictedAuthor.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#columns-selected-by-a-request) for further information. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#columns-selected-by-a-request) for further information. ## Table Aliases @@ -1032,13 +1032,13 @@ let request = Book This request builds the following **tree of association keys**: -![TreeOfAssociationKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeys.svg) +![TreeOfAssociationKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/TreeOfAssociationKeys.svg) **Association keys** are strings. They are the names of the database tables of associated records (unless you specify otherwise, as we'll see below). Those keys are associated with slices in the fetched rows: -![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) We'll see below how this tree of association keys and row slices can feed a Decodable record type. We'll then add some details by using FetchableRecord without Decodable support. @@ -1066,7 +1066,7 @@ This deserves a little explanation: You known that the Decodable protocol feeds a value's properties by looking for **coding keys**. For example, the standard built-in JSONDecoder matches those coding keys with dictionary keys in a JSON object. The GRDB record decoder also matches coding keys, but with association keys: -![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3-Associations/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) +![TreeOfAssociationKeysMapping](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/TreeOfAssociationKeysMapping.svg) Practically speaking, the BookInfo initializer first looks for the "book" coding key. This key is not found anywhere in the tree of association keys, so the book property is initialized from the row slice associated with the root of the tree, which contains book columns. @@ -1228,7 +1228,7 @@ struct BookInfo: FetchableRecord { let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] ``` -You are already familiar with row subscripts to decode [database values](https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#column-values): +You are already familiar with row subscripts to decode [database values](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#column-values): ```swift let name: String = row["name"] @@ -1346,9 +1346,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Self Joins]: #self-joins [The Types of Associations]: #the-types-of-associations [Codable]: https://developer.apple.com/documentation/swift/codable -[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#fetchablerecord-protocols -[migration]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#migrations -[Record]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#records +[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#fetchablerecord-protocols +[migration]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations +[Record]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#records [Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions [Associations and the Database Schema]: #associations-and-the-database-schema [Convention for Database Table Names]: #convention-for-database-table-names @@ -1369,7 +1369,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Decoding a Joined Request with a Decodable Record]: #decoding-a-joined-request-with-a-decodable-record [Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record [Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord -[Custom Requests]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#custom-requests +[Custom Requests]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests [Known Issues]: #known-issues [Future Directions]: #future-directions -[Row Adapters]: https://github.com/groue/GRDB.swift/blob/GRDB3-Associations/README.md#row-adapters \ No newline at end of file +[Row Adapters]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#row-adapters \ No newline at end of file From de6667a2362fd5efea30893050cfeb06ab3a345b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 12:44:06 +0200 Subject: [PATCH 249/348] WIP: GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index b06ca7fac..e768fd15d 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -452,7 +452,7 @@ dbQueue.rx If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter: - [Database Queues](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-queues): focus on the new `read` and `write` methods. -- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as an advanced and potentially dangerous feature. +- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. - [ScopeAdapter](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#scopeadapter): do you use row adapters? If so, have a look. - [Examples of Record Definitions](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). - [SQL Operators](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. From a360976e23b0caec66b6cf2edb4725027fafe2da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 14:15:12 +0200 Subject: [PATCH 250/348] ForeignKey initializer accepts ColumnExpression --- GRDB/QueryInterface/Association/ForeignKey.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift index c509202b7..032694e69 100644 --- a/GRDB/QueryInterface/Association/ForeignKey.swift +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -10,7 +10,7 @@ public struct ForeignKey { } /// TODO - public init(_ originColumns: [Column], to destinationColumns: [Column]? = nil) { + public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) { self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name }) } } From 402f9d3ba9fa7a0a8b782e3e39286fe614bd27d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 14:43:44 +0200 Subject: [PATCH 251/348] Tweaks in AssociationBasics.md --- Documentation/AssociationsBasics.md | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 6bcb6441a..653a0bd26 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -547,11 +547,12 @@ Foreign keys can also be defined from `Column`: ```swift struct Book: TableRecord { - static let authorId = Column("authorId") - static let translatorId = Column("translatorId") + enum Columns: String, ColumnExpression { + case id, title, authorId, translatorId + } - static let authorForeignKey = ForeignKey([authorId])) - static let translatorForeignKey = ForeignKey([translatorId])) + static let authorForeignKey = ForeignKey([Columns.authorId])) + static let translatorForeignKey = ForeignKey([Columns.translatorId])) } ``` @@ -777,7 +778,7 @@ The request above fetches all books, along with their author's country. **You can filter associated records.** -The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#requests), can filter associated records as well: +The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well: ```swift // SELECT book.* @@ -802,7 +803,7 @@ Those extra filtering options require **[Table Aliases]**, introduced below. **You can sort fetched results according to associated records.** -The `order()` method, that you already know for [sorting simple requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#requests), can sort associated records as well: +The `order()` method, that you already know for [sorting simple requests](../README.md#requests), can sort associated records as well: ```swift // SELECT book.*, person.* @@ -891,7 +892,7 @@ Modifying `databaseSelection` not only affects joined requests, but all requests let request = RestrictedAuthor.all() ``` -> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#columns-selected-by-a-request) for further information. +> :point_up: **Note**: make sure the `databaseSelection` property is explicitely declared as `[SQLSelectable]`. If it is not, the Swift compiler may infer a type which may silently miss the protocol requirement, resulting in sticky SELECT * requests. See [Columns Selected by a Request](../README.md#columns-selected-by-a-request) for further information. ## Table Aliases @@ -1228,7 +1229,7 @@ struct BookInfo: FetchableRecord { let bookInfos = try BookInfo.fetchAll(db, request) // [BookInfo] ``` -You are already familiar with row subscripts to decode [database values](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#column-values): +You are already familiar with row subscripts to decode [database values](../README.md#column-values): ```swift let name: String = row["name"] @@ -1346,9 +1347,9 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Self Joins]: #self-joins [The Types of Associations]: #the-types-of-associations [Codable]: https://developer.apple.com/documentation/swift/codable -[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#fetchablerecord-protocols -[migration]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations -[Record]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#records +[FetchableRecord]: ../README.md#fetchablerecord-protocols +[migration]: ../README.md#migrations +[Record]: ../README.md#records [Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions [Associations and the Database Schema]: #associations-and-the-database-schema [Convention for Database Table Names]: #convention-for-database-table-names @@ -1369,7 +1370,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Decoding a Joined Request with a Decodable Record]: #decoding-a-joined-request-with-a-decodable-record [Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record [Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord -[Custom Requests]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests +[Custom Requests]: ../README.md#custom-requests [Known Issues]: #known-issues [Future Directions]: #future-directions -[Row Adapters]: https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#row-adapters \ No newline at end of file +[Row Adapters]: ../README.md#row-adapters \ No newline at end of file From a12bc2e90e52d14adde282bc98d440a913f7945d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 14:44:32 +0200 Subject: [PATCH 252/348] Tweaks in GRDB2MigrationGuide.md --- Documentation/GRDB2MigrationGuide.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index e768fd15d..f99d0bf22 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -62,7 +62,7 @@ GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be ## iOS 8 Sunsetting -GRDB 3 is only tested on iOS 9+, due to a limitation in XCode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. +GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. ## Database Schema Recommendations @@ -382,7 +382,7 @@ extension Player { let players = try Player.filter(color: .red).fetchAll(db) ``` -See the updated [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests) chapter for more information. +See the updated [Custom Requests](../README.md#custom-requests) chapter for more information. ## If You Use RxGRDB @@ -451,13 +451,13 @@ dbQueue.rx If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter: -- [Database Queues](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-queues): focus on the new `read` and `write` methods. -- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. -- [ScopeAdapter](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#scopeadapter): do you use row adapters? If so, have a look. -- [Examples of Record Definitions](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). -- [SQL Operators](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. -- [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. -- [Migrations](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). +- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods. +- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. +- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look. +- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). [How To Upgrade]: #how-to-upgrade From 62f985469c6bd2da3c87e61c25e8da29cc56239a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 14:53:49 +0200 Subject: [PATCH 253/348] Update WhyAdoptGRDB.md for GRDB3 --- Documentation/WhyAdoptGRDB.md | 89 +++++++++++++++++++++-------------- 1 file changed, 53 insertions(+), 36 deletions(-) diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 8a56e72d0..6bf9019c7 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -10,7 +10,7 @@ We'll start with a few [core principles](#core-principles), so that you see wher ### It is generally easier to access a database through "record types". -This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow[nameColumn]`, doesn't it? +This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it? The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause. @@ -39,7 +39,7 @@ This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams... -Some will call GRDB "opinionated", or "bloated". Well, the bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. +The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face. Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries. @@ -51,7 +51,7 @@ What is the purpose of the above principles, if not providing solutions to diffi ### Allow any Swift struct or class to become a database record -Most libraries that provide record types want you to subclass a root class: NSManagedObject, Realm.Object, FCModel. +Most libraries that provide record types want you to subclass a root class: [NSManagedObject](https://developer.apple.com/documentation/coredata/nsmanagedobject), [Realm.Object](https://www.realm.io/docs/swift/latest), [FCModel](https://github.com/marcoarment/FCModel). The main problem with those root classes is that they are classes. You can't define records from plain Swift structs, and leverage all advantages of Swift value types: immutability, multi-threading safety, etc. @@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques ```swift extension Place: FetchableRecord { ... } -let places = try Place.fetchAll(db, "SELECT * FROM places") // [Place] +let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place] ``` Add the [TableRecord] protocol, and SQL requests are generated for you: @@ -86,7 +86,7 @@ extension Place: PersistableRecord { ... } try place.delete(db) ``` -Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with database change notifications, with many advantages. +Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages. ### Allow database records to cross threads @@ -129,16 +129,16 @@ First, notifications only come from database changes safely saved on disk. This Next, you choose the dispatch queue on which notifications happen. It can be on the special "writer queue", which allows you to process changes before any other thread has any opportunity to perform further database modifications. But notifications can also happen on the queue of your choice (generally the main queue, by default, as in the example above). Of course, GRDB makes sure notifications happen in the same order as database transactions. -Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. +Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, and even SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported. ### Non-blocking database reads -GRDB ships with two ways to access databases, [database queues](https://github.com/groue/GRDB.swift/blob/master/README.md#database-queues) and [pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools). +GRDB ships with two ways to access databases, [database queues](../README.md#database-queues) and [pools](../README.md#database-pools). Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen. -[Database pools](https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). +[Database pools](../README.md#database-pools) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). ### Strong and clear multi-threading guarantees @@ -162,9 +162,9 @@ The more threats are handled by the application, the more skilled and careful a | GRDB's DatabaseQueue | :white_check_mark: | :white_check_mark: | Handled by the application | UI is blocked | | GRDB's DatabasePool | :white_check_mark: | :white_check_mark: | Handled by the application | :white_check_mark: (as long as the maximum number of readers has not been reached) | -I had to omit Realm and FCModel from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. +I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue. -We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to use or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. A weaker way to say this is that conflict handling at the library level can wait :sweat_smile:. +We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way. Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly. @@ -175,47 +175,62 @@ For further information about GRDB concurrency, check its detailed [Concurrency SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful. -GRDB records can generate SQL for you: +GRDB [query interface] and [associations] can generate SQL for you: ```swift -// SELECT * FROM players ORDER BY score DESC LIMIT 10 +// SELECT * FROM player ORDER BY score DESC LIMIT 10 let bestPlayers: [Player] = try Player .order(scoreColumn.desc) .limit(10) .fetchAll(db) -// SELECT MAX(score) FROM players +// SELECT MAX(score) FROM player let maximumScore: Int? = try Player .select(max(scoreColumn)) .asRequestOf(Int.self) .fetchOne(db) - -// SELECT COUNT(*) FROM players WHERE score = ? -let exAequoCount: Int = try Player - .filter(scoreColumn == maximumScore) - .fetchCount(db) + +// SELECT book.*, author.* +// FROM book +// LEFT JOIN author ON author.id = book.authorId +let request = Book.including(optional: Book.author) +let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request) ``` But you can always switch to SQL when you want to: ```swift let bestPlayers: [Player] = try Player.fetchAll(db, """ - SELECT * FROM players ORDER BY score DESC LIMIT 10 + SELECT * FROM player ORDER BY score DESC LIMIT 10 """) let maximumScore: Int? = try Int.fetchOne(db, """ - SELECT MAX(score) FROM players + SELECT MAX(score) FROM player """) - -let exAequoCount: Int? = try Int.fetchOne(db, """ - SELECT COUNT(*) FROM players WHERE score = ? - """, arguments: [maximumScore]) ``` -In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](https://github.com/groue/GRDB.swift/blob/master/README.md#cursors) instead of arrays: +Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)): ```swift -let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM players") +let bookInfos: [BookInfo] = SQLRequest(""" + SELECT book.*, author.* + FROM book + LEFT JOIN author ON author.id = book.authorId + """) + .adapted { db in + let adapters = try splittingRowAdapters(columnCounts: [ + db.columns(in: "book").count, + db.columns(in: "author").count]) + return ScopeAdapter([ + "book": adapters[0], + "author": adapters[1]]) + } +``` + +In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays: + +```swift +let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player") while let row = try rows.next() { let id: Int64 = row[0] let name: String = row[1] @@ -223,7 +238,7 @@ while let row = try rows.next() { } ``` -When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](https://github.com/groue/GRDB.swift/blob/master/README.md#custom-requests): +When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests): ```swift extension Player { @@ -238,8 +253,8 @@ let players = try Player.customRequest(...).fetchAll(db) Those custom requests are welcome in database observation tools like [FetchedRecordsController] and [RxGRDB]: ```swift -Player.customRequest(...) - .rx.fetchAll(in: dbQueue) +Player.customRequest(...).rx + .fetchAll(in: dbQueue) .subscribe(onNext: { players: [Player] in print("Players have changed") }) @@ -253,23 +268,25 @@ And if you happen to maintain an Objective-C application that uses FMDB, checkou Happy GRDB! :gift: -[Concurrency Guide]: https://github.com/groue/GRDB.swift/blob/master/README.md#concurrency +[Concurrency Guide]: ../README.md#concurrency [Core Data]: https://developer.apple.com/documentation/coredata -[DatabasePool]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-pools +[DatabasePool]: ../README.md#database-pools [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel -[FetchedRecordsController]: https://github.com/groue/GRDB.swift/blob/master/README.md#fetchedrecordscontroller +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller [Fluent]: https://github.com/vapor/fluent [FMDB]: http://github.com/ccgus/fmdb [GRDB]: http://github.com/groue/GRDB.swift [GRDBObjc]: http://github.com/groue/GRDBObjc -[PersistableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[PersistableRecord]: ../README.md#records [Realm]: http://realm.io -[FetchableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records +[FetchableRecord]: ../README.md#records [RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB [RxSwift]: https://github.com/ReactiveX/RxSwift [SQLite.swift]: http://github.com/stephencelis/SQLite.swift [StORM]: https://www.perfect.org/docs/StORM.html [Swift-Kuery]: http://github.com/IBM-Swift/Swift-Kuery -[TableRecord]: https://github.com/groue/GRDB.swift/blob/master/README.md#records -[TransactionObserver]: https://github.com/groue/GRDB.swift/blob/master/README.md#transactionobserver-protocol +[TableRecord]: ../README.md#records +[TransactionObserver]: ../README.md#transactionobserver-protocol +[query interface]: ../README.md#the-query-interface +[associations]: AssociationsBasics.md From 56ae745851aa039deecba483385c1b98336e5c6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 14:55:39 +0200 Subject: [PATCH 254/348] Prepare v3.0.0-beta.1 release --- CHANGELOG.md | 187 ++++++---------------------- Documentation/CustomSQLiteBuilds.md | 4 +- Documentation/README.md | 2 +- README.md | 56 ++++----- 4 files changed, 68 insertions(+), 181 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3cdd1b3ca..82c337c18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,166 +3,53 @@ Release Notes ## Next Version +GRDB 3.0.0-beta.1 is a release focused on **modernization**, **safety**, and **associations between record types**. + +It comes with new features, but also a few breaking changes, and a set of updated good practices. The [GRDB 2 Migration Guide](Documentation/GRDB2MigrationGuide.md) will help you upgrading your applications. + + ### New -- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table. -- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table. -- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database. +- Associations and Joins ([#319](https://github.com/groue/GRDB.swift/pull/319)). +- Enhancements to logical operators ([#336](https://github.com/groue/GRDB.swift/pull/336)). +- Foster auto-incremented primary keys ([#337](https://github.com/groue/GRDB.swift/pull/337)). +- ColumnExpression Protocol ([#340](https://github.com/groue/GRDB.swift/pull/340)). +- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909). +- Common API for requests and associations derivation ([#347](https://github.com/groue/GRDB.swift/pull/347)). +- `DatabaseMigrator.appliedMigrations(in:)` returns the set of applied migrations identifiers in a database ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- `Database.isSQLiteInternalTable(_:)` returns whether a table name is an internal SQLite table ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- `Database.isGRDBInternalTable(_:)` returns whether a table name is an internal GRDB table ([#321](https://github.com/groue/GRDB.swift/pull/321)). +- Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)). +- Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)). +- Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)). + ### Breaking Changes -- The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord`. -- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([311](https://github.com/groue/GRDB.swift/pull/311)). -- The `IteratorCursor` type has been removed. Use `AnyCursor` instead. +- Swift 4.1 is now required. +- iOS 8 sunsetting: GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported. +- The Record protocols have been renamed: `RowConvertible` to `FetchableRecord`, `Persistable` to `PersistableRecord`, and `TableMapping` to `TableRecord` ([#314](https://github.com/groue/GRDB.swift/pull/314)). +- Implicit transaction in DatabasePool.write and DatabaseQueue.write ([#332](https://github.com/groue/GRDB.swift/pull/332)). +- `Request` and `TypedRequest` protocols have been merged into `FetchRequest` ([#311](https://github.com/groue/GRDB.swift/pull/311), [#328](https://github.com/groue/GRDB.swift/pull/328), [#348](https://github.com/groue/GRDB.swift/pull/348)). +- Reversing unordered requests has no effect ([#342](https://github.com/groue/GRDB.swift/pull/342)). +- The `IteratorCursor` type has been removed. Use `AnyCursor` instead ([#312](https://github.com/groue/GRDB.swift/pull/312)). +- Row scopes collection, breadth-first scope search ([#335](https://github.com/groue/GRDB.swift/pull/335)). +- Expressions are no longer PATs ([#330](https://github.com/groue/GRDB.swift/pull/330)). - Deprecated APIs have been removed. -### API diff +### Documentation Diff -**Record protocols** +- [Associations](Documentation/AssociationsBasics.md): Discover the major GRDB 3 feature +- [Database Queues](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-queues): focus on the `read` and `write` methods. +- [Database Pools](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-pools): focus on the `read` and `write` methods. +- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. +- [ScopeAdapter](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#scopeadapter): do you use row adapters? If so, have a look. +- [Examples of Record Definitions](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Migrations](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). -```diff --protocol RowConvertible { -+protocol FetchableRecord { - } - --protocol TableMapping { -+protocol TableRecord { - } - --protocol MutablePersistable: TableMapping { -+protocol MutablePersistableRecord: TableRecord { - } - --protocol Persistable: MutablePersistable { -+protocol PersistableRecord: MutablePersistableRecord { - } -``` - -**FetchRequest** - -```diff -+protocol FetchRequest { -+ associatedtype RowDecoder -+ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) -+ func fetchCount(_ db: Database) throws -> Int -+ func databaseRegion(_ db: Database) throws -> DatabaseRegion -+} -+extension FetchRequest { -+ func fetchCount(_ db: Database) throws -> Int -+ func databaseRegion(_ db: Database) throws -> DatabaseRegion -+ func asRequest(of type: T.Type) -> AnyFetchRequest -+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest -+} -+struct AdaptedFetchRequest : FetchRequest { -+ typealias RowDecoder = Base.RowDecoder -+} -+struct AnyFetchRequest : FetchRequest { -+ typealias RowDecoder = T -+ init(_ request: Request) -+ init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) -+} -+struct SQLRequest : FetchRequest { -+ typealias RowDecoder = T -+ let sql: String -+ let arguments: StatementArguments? -+ let adapter: RowAdapter? -+ init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) -+ init(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder -+} - -+extension FetchRequest where RowDecoder: DatabaseValueConvertible { -+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor -+ func fetchAll(_ db: Database) throws -> [RowDecoder] -+ func fetchOne(_ db: Database) throws -> RowDecoder? -+ -} -+extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible -+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor -+ func fetchAll(_ db: Database) throws -> [RowDecoder._Wrapped?] -+} - -+extension FetchRequest where RowDecoder: Row { -+ func fetchCursor(_ db: Database) throws -> RowCursor -+ func fetchAll(_ db: Database) throws -> [Row] -+ func fetchOne(_ db: Database) throws -> Row? -+} - -+extension FetchRequest where RowDecoder: FetchableRecord { -+ func fetchCursor(_ db: Database) throws -> RecordCursor -+ func fetchAll(_ db: Database) throws -> [RowDecoder] -+ func fetchOne(_ db: Database) throws -> RowDecoder? -+} - --protocol Request { } --struct AdaptedRequest : Request { } --struct AnyRequest : Request { } --struct SQLRequest : Request { } --protocol TypedRequest : Request { } --struct AdaptedTypedRequest : TypedRequest { } --struct AnyTypedRequest : TypedRequest { } - --extension DatabaseValueConvertible { -- static func fetchCursor(_ db: Database, _ request: Request) throws -> DatabaseValueCursor -- static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] -- static func fetchOne(_ db: Database, _ request: Request) throws -> Self? --} - --extension Optional where Wrapped: DatabaseValueConvertible { -- static func fetchCursor(_ db: Database, _ request: Request) throws -> NullableDatabaseValueCursor -- static func fetchAll(_ db: Database, _ request: Request) throws -> [Wrapped?] --} - --extension Row { -- static func fetchCursor(_ db: Database, _ request: Request) throws -> RowCursor -- static func fetchAll(_ db: Database, _ request: Request) throws -> [Row] -- static func fetchOne(_ db: Database, _ request: Request) throws -> Row? --} - --extension RowConvertible { -- static func fetchCursor(_ db: Database, _ request: Request) throws -> RecordCursor -- static func fetchAll(_ db: Database, _ request: Request) throws -> [Self] -- static func fetchOne(_ db: Database, _ request: Request) throws -> Self? --} - --extension QueryInterfaceRequest : TypedRequest { } -+extension QueryInterfaceRequest : FetchRequest { } -``` - -**Cursor** - -```diff - final class AnyCursor : Cursor { -+ convenience init(iterator: I) where I.Element == Element -+ convenience init(_ s: S) where S.Element == Element - } --final class IteratorCursor : Cursor { } -``` - -**Removed Deprecated APIs** - -```diff - final class Database { -- func columnCount(in tableName: String) throws -> Int - } - final class SelectStatement : Statement { -- typealias SelectionInfo = DatabaseRegion -- var selectionInfo: DatabaseRegion - } - enum DatabaseEventKind { -- func impacts(_ region: DatabaseRegion) -> Bool - } - open class Record: FetchableRecord, TableRecord, PersistableRecord { -- var hasPersistentChangedValues: Bool -- var persistentChangedValues: [String: DatabaseValue?] - } --final class RecordBox: Record { } -``` - - -## Next Version - -- Improved parsing of dates and date components ([#334](https://github.com/groue/GRDB.swift/pull/334) by @sobri909) ## 2.10.0 diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index c9f525457..144a2923b 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -3,7 +3,7 @@ Custom SQLite Builds By default, GRDB uses the version of SQLite that ships with the target operating system. -**You can build GRDB with a custom build of [SQLite 3.22.0](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.23.0](https://www.sqlite.org/changes.html).** A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks). @@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal ```sh cd [GRDB directory] - git checkout v2.10.0 + git checkout v3.0.0-beta.1 git submodule update --init SQLiteCustom/src ```` diff --git a/Documentation/README.md b/Documentation/README.md index dff0e9633..b29c23d5f 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -1 +1 @@ -The main documentation is available in [README.md](../../../#documentation). +The main documentation is available in [README.md](../README.md#documentation). diff --git a/README.md b/README.md index 24ee271ae..4ff47bd1d 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ GRDB 3 [![Swift](https://img.shields.io/badge/swift-4.1-orange.svg?style=flat)]( ### A toolkit for SQLite databases, with a focus on application development -**Latest release**: March 30, 2018 • version 2.10.0 • [CHANGELOG](CHANGELOG.md) +**Latest release**: March 30, 2018 • version 3.0.0-beta.1 • [CHANGELOG](CHANGELOG.md) **Requirements**: iOS 8.0+ / OSX 10.9+ / watchOS 2.0+ • Swift 4.1+ / Xcode 9.3+ | Swift version | GRDB version | | ------------- | ----------------------------------------------------------- | -| **Swift 4.1** | **v3.0.0** | +| **Swift 4.1** | **v3.0.0-beta.1** | | Swift 4 | [v2.10.0](https://github.com/groue/GRDB.swift/tree/v2.10.0) | | Swift 3.2 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | | Swift 3.1 | [v1.3.0](https://github.com/groue/GRDB.swift/tree/v1.3.0) | @@ -251,7 +251,7 @@ Documentation **Reference** -- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/2.10/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) +- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) **Getting Started** @@ -319,7 +319,7 @@ The [Swift Package Manager](https://swift.org/package-manager/) automates the di ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", from: "2.10.0") + .package(url: "https://github.com/groue/GRDB.swift.git", from: "3.0.0-beta.1") ] ) ``` @@ -336,7 +336,7 @@ If you decide to use Carthage despite this warning, and get any Carthage-related ## Manually -1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v2.10.0) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v2.10.0` command. +1. [Download](https://github.com/groue/GRDB.swift/releases/tag/v3.0.0-beta.1) a copy of GRDB, or clone its repository and make sure you use the latest tagged version with the `git checkout v3.0.0-beta.1` command. 2. Embed the `GRDB.xcodeproj` project in your own project. @@ -439,7 +439,7 @@ let dbQueue = try DatabaseQueue( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) for more details. ## Database Pools @@ -524,7 +524,7 @@ let dbPool = try DatabasePool( configuration: config) ``` -See [Configuration](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) for more details. +See [Configuration](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) for more details. Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information. @@ -739,7 +739,7 @@ Both arrays and cursors can iterate over database results. How do you choose one If you don't see, or don't care about the difference, use arrays. If you care about memory and performance, use cursors when appropriate. -**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: +**All GRDB cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // All URL hosts @@ -812,7 +812,7 @@ let rows = try Row.fetchAll(db, arguments: ["name": "Arthur"]) ``` -See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. +See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments. Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care: @@ -1083,7 +1083,7 @@ GRDB ships with built-in support for the following value types: - Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol. -Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift let url: URL = ... @@ -1439,7 +1439,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction } ``` -Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) configuration flag: +Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) configuration flag: ```swift // fatal error: A transaction has been left opened at the end of a database access @@ -1574,7 +1574,7 @@ try dbQueue.write { db in } ``` -The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). +The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols). ```swift updateStatement.arguments = ["name": "Arthur", "score": 1000] @@ -1832,7 +1832,7 @@ row["consumed"] // "Hello" row["produced"] // nil ``` -Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. +Row adapters are values that adopt the [RowAdapter](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/RowAdapter.html) protocol. You can implement your own custom adapters ([**:fire: EXPERIMENTAL**](#what-are-experimental-features)), or use one of the four built-in adapters, described below. To see how row adapters can be used, see [Joined Queries Support](#joined-queries-support). @@ -1975,8 +1975,8 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_aggregate_context`, `sqlite3_create_function_v2`, `sqlite3_result_blob`, `sqlite3_result_double`, `sqlite3_result_error`, `sqlite3_result_error_code`, `sqlite3_result_int64`, `sqlite3_result_null`, `sqlite3_result_text`, `sqlite3_user_data`, `sqlite3_value_blob`, `sqlite3_value_bytes`, `sqlite3_value_double`, `sqlite3_value_int64`, `sqlite3_value_text`, `sqlite3_value_type`: see [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - `sqlite3_backup_finish`, `sqlite3_backup_init`, `sqlite3_backup_step`: see [Backup](#backup) - `sqlite3_bind_blob`, `sqlite3_bind_double`, `sqlite3_bind_int64`, `sqlite3_bind_null`, `sqlite3_bind_parameter_count`, `sqlite3_bind_parameter_name`, `sqlite3_bind_text`, `sqlite3_clear_bindings`, `sqlite3_column_blob`, `sqlite3_column_bytes`, `sqlite3_column_count`, `sqlite3_column_double`, `sqlite3_column_int64`, `sqlite3_column_name`, `sqlite3_column_text`, `sqlite3_column_type`, `sqlite3_exec`, `sqlite3_finalize`, `sqlite3_prepare_v2`, `sqlite3_reset`, `sqlite3_step`: see [Executing Updates](#executing-updates), [Fetch Queries](#fetch-queries), [Prepared Statements](#prepared-statements), [Values](#values) -- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) -- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/2.10/Classes/Database.html) +- `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) +- `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) - `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [FetchedRecordsController](#fetchedrecordscontroller) - `sqlite3_config`: see [Error Log](#error-log) @@ -1987,9 +1987,9 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_last_insert_rowid`: see [Executing Updates](#executing-updates) - `sqlite3_preupdate_count`, `sqlite3_preupdate_depth`, `sqlite3_preupdate_hook`, `sqlite3_preupdate_new`, `sqlite3_preupdate_old`: see [Support for SQLite Pre-Update Hooks](#support-for-sqlite-pre-update-hooks) - `sqlite3_set_authorizer`: **reserved by GRDB** -- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/2.10/Classes/Statement.html) -- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) -- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/2.10/Classes/DatabasePool.html) +- `sqlite3_sql`: see [Statement.sql](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/Statement.html) +- `sqlite3_trace`: see [Configuration.trace](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) +- `sqlite3_wal_checkpoint_v2`: see [DatabasePool.checkpoint](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Classes/DatabasePool.html) Records @@ -2276,7 +2276,7 @@ try Place.fetchAll(db, "SELECT ...", arguments:...) // [Place] try Place.fetchOne(db, "SELECT ...", arguments:...) // Place? ``` -See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html) for more information about the query arguments. +See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html) for more information about the query arguments. ## TableRecord Protocol @@ -3615,7 +3615,7 @@ Player // SELECT * FROM player ``` -Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift // SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate) @@ -4136,7 +4136,7 @@ The `prepare` method returns a prepared statement and an optional row adapter. T The `fetchCount` method has a default implementation that builds a correct but naive SQL query from the statement returned by `prepare`: `SELECT COUNT(*) FROM (...)`. Adopting types can refine the counting SQL by customizing their `fetchCount` implementation. -The `databaseRegion` method is involved in [database observation](#database-changes-observation). It is given a default implementation, based on the statement returned by `prepare`. For more information, see [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/2.10/Structs/DatabaseRegion.html), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). +The `databaseRegion` method is involved in [database observation](#database-changes-observation). It is given a default implementation, based on the statement returned by `prepare`. For more information, see [DatabaseRegion](https://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/DatabaseRegion.html), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB). The FetchRequest protocol is adopted, for example, by [query interface requests](#requests): @@ -4150,7 +4150,7 @@ let request = Player.all() **To build custom requests**, you can use one of the built-in requests, derive requests from other requests, or create your own request type that adopts the [FetchRequest](#fetchrequest-protocol) protocol. -- [SQLRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: +- [SQLRequest](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/SQLRequest.html) is a fetch request built from raw SQL. For example: ```swift extension Player { @@ -4176,7 +4176,7 @@ let request = Player.all() - The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method. -- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/2.10/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. +- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/AnyFetchRequest.html): a [type-erased](http://chris.eidhof.nl/post/type-erasers-in-swift/) request. ### Fetching From Custom Requests @@ -4590,7 +4590,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +FTS3Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -4805,7 +4805,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/2.10/Structs/StatementArguments.html): +FTS5Pattern are regular [values](#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html): ```swift let documents = try Document.fetchAll(db, @@ -6062,7 +6062,7 @@ Alternatively, perform a manual installation of GRDB and SQLCipher: ```sh cd [GRDB directory] - git checkout v2.10.0 + git checkout v3.0.0-beta.1 git submodule update --init SQLCipher/src ``` @@ -6857,7 +6857,7 @@ try snapshot2.read { db in ### DatabaseWriter and DatabaseReader Protocols -Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/2.10/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. +Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only. These protocols provide a unified API that lets you write safe concurrent code that targets all three concurrency modes. @@ -6951,7 +6951,7 @@ If you absolutely need multiple connections, then: - Read about [isolation in SQLite](https://www.sqlite.org/isolation.html) - Learn about [locks and transactions](https://www.sqlite.org/lang_transaction.html) - Become a master of the [WAL mode](https://www.sqlite.org/wal.html) -- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/2.10/Structs/Configuration.html) +- Prepare to setup a [busy handler](https://www.sqlite.org/c3ref/busy_handler.html) with [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/Configuration.html) - [Ask questions](https://github.com/groue/GRDB.swift/issues) From 69cf95e8289fcf54c83ce55d31e1a2fba0dbd4b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 6 May 2018 20:03:28 +0200 Subject: [PATCH 255/348] Typo --- Documentation/AssociationsBasics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 653a0bd26..18c4c0c0a 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -109,7 +109,7 @@ let request = Book.including(optional: Book.author) let bookInfos = BookInfo.fetchAll(db, request) ``` -Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because Your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter. +Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome: see the [Joined Queries Support](../README.md#joined-queries-support) chapter. The Types of Associations From 56a0dab4433afe3d8dee2f1110b795e02c408fa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 09:10:50 +0200 Subject: [PATCH 256/348] Typo --- Documentation/GRDB2MigrationGuide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index f99d0bf22..7791dd2df 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -180,7 +180,7 @@ In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has be ```swift // GRDB 3 -struct Player: RowConvertible, TableMapping { +struct Player: FetchableRecord, TableRecord { enum Columns: String, ColumnExpression { case id, name, score } From a35f01228635e524d8d6c13d284857f1797c3121 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 17:50:27 +0200 Subject: [PATCH 257/348] Cleanup --- .../Association/Association.swift | 31 +++- .../AssociationBelongsToSQLTests.swift | 147 +++++++++++++++--- 2 files changed, 151 insertions(+), 27 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 4fc93f130..53fa919b9 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -281,18 +281,37 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { /// let team: Team = ... /// let players = try team.players.fetchAll(db) // [Player] func request(from record: OriginRowDecoder) -> QueryInterfaceRequest { - // Turn `JOIN associated ON associated.recordId = record.id` - // into `FROM associated WHERE associated.recordId = 1` + // Goal: turn `JOIN association ON association.recordId = record.id` + // into a regular request `SELECT * FROM association WHERE association.recordId = 123` + + // We need table aliases to build the joining condition let associationAlias = TableAlias() - let recordAlias = TableAlias(tableName: OriginRowDecoder.databaseTableName) + let recordAlias = TableAlias() + + // Turn JOIN into SELECT FROM return QueryInterfaceRequest(request) - .aliased(associationAlias) + + // Turn the JOIN condition into a regular WHERE condition .filter { db in + // Build a join condition: `association.recordId = record.id` + // We still need to replace `record.id` with the actual record id. guard let joinCondition = try self.joinCondition(db)(recordAlias, associationAlias) else { fatalError("Can't request from record without join condition") } - let container = PersistenceContainer(record) // support for record classes: late construction of container + + // Serialize record: ["id": 123, ...] + // We do it as late as possible, when request is about to be + // executed, in order to support long-lived reference types. + let container = PersistenceContainer(record) + + // Replace `record.id` with 123 return joinCondition.resolvedExpression(inContext: [recordAlias: container]) - } + } + + // We just added a condition qualified with associationAlias. Don't + // risk introducing conflicting aliases that would prevent the user + // from setting a custom alias name: force the same alias for the + // whole request. + .aliased(associationAlias) } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 3e781f56c..3f619c67b 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -55,7 +55,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."rowid" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"rowid\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"rowid\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"rowid\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) @@ -79,7 +84,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } } } @@ -129,7 +139,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) @@ -153,7 +168,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } } } @@ -203,7 +223,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")])) @@ -227,7 +252,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentId")], to: [Column("id")])) @@ -251,7 +281,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parentId") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } } } @@ -303,7 +338,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1Id")], to: [Column("id")])) @@ -327,7 +367,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent1Id") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 1)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 1) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 1) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")])) @@ -351,7 +396,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 2) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 2) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2Id")], to: [Column("id")])) @@ -375,7 +425,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON ("parents"."id" = "children"."parent2Id") """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE (\"id\" = 2)") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE (\"id\" = 2) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE (\"custom\".\"id\" = 2) + """) } } } @@ -428,7 +483,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } } } @@ -482,7 +542,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children\".\"parentB\")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) @@ -506,7 +571,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } } } @@ -561,7 +631,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")])) @@ -585,7 +660,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parentA"), Column("parentB")], to: [Column("a"), Column("b")])) @@ -609,7 +689,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } } } @@ -669,7 +754,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent1A"), Column("parent1B")], to: [Column("a"), Column("b")])) @@ -693,7 +783,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 1) AND (\"b\" = 2)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 1) AND (\"custom\".\"b\" = 2)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")])) @@ -717,7 +812,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 3) AND (\"custom\".\"b\" = 4)) + """) } do { let association = Child.belongsTo(Parent.self, using: ForeignKey([Column("parent2A"), Column("parent2B")], to: [Column("a"), Column("b")])) @@ -741,7 +841,12 @@ class AssociationBelongsToSQLTests: GRDBTestCase { FROM "children" \ LEFT JOIN "parents" ON (("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")) """) - try assertEqualSQL(db, Child().request(for: association), "SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4))") + try assertEqualSQL(db, Child().request(for: association), """ + SELECT * FROM \"parents\" WHERE ((\"a\" = 3) AND (\"b\" = 4)) + """) + try assertEqualSQL(db, Child().request(for: association).aliased(TableAlias(name: "custom")), """ + SELECT \"custom\".* FROM \"parents\" \"custom\" WHERE ((\"custom\".\"a\" = 3) AND (\"custom\".\"b\" = 4)) + """) } } } From 91ad986d0b0a3a0dde47e5f248785f49eaac9855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 19:17:19 +0200 Subject: [PATCH 258/348] Cleanup and add internal documentation for the non-trivial TableAlias --- GRDB/QueryInterface/Column.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 2 +- .../QueryInterface/SQLGenerationContext.swift | 83 +++++++++++++------ 3 files changed, 58 insertions(+), 29 deletions(-) diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index 5cfb79769..bcdc7fe86 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -89,7 +89,7 @@ struct QualifiedColumn: ColumnExpression { func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression { guard - let container = context[alias.root], + let container = context[alias], let value = container.value(forCaseInsensitiveColumn: name) else { return self diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index f63053f91..2e3eba87a 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -633,7 +633,7 @@ enum SQLSource { switch self { case .table(let tableName, let sourceAlias): if let sourceAlias = sourceAlias { - alias.rebase(on: sourceAlias) + alias.becomeProxy(of: sourceAlias) return self } else { alias.setTableName(tableName) diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index 9e8590fa9..b8aaf89c4 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -57,7 +57,7 @@ public struct SQLGenerationContext { /// WHERE MATCH pattern func resolvedName(for alias: TableAlias) -> String { - return resolvedNames[alias.root] ?? alias.identityName + return resolvedNames[alias] ?? alias.identityName } /// FROM tableName @@ -73,30 +73,60 @@ public struct SQLGenerationContext { // MARK: - TableAlias /// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// +/// A TableAlias identifies a table in a request. public class TableAlias: Hashable { + private var impl: Impl private enum Impl { /// A TableAlias is undefined when it is created by the GRDB user: /// /// let alias = TableAlias() - /// let alias = TableAlias(name: "player") + /// let alias = TableAlias(name: "custom") case undefined(userName: String?) /// A TableAlias is a table when explicitly specified: /// /// let alias = TableAlias(tableName: "player") /// - /// Or when it has been qualified by a request: + /// Or when it qualifies a request that wasn't qualified yet (in which + /// case it turns from undefined to a table): /// - /// let alias = TableAlias() + /// // SELECT custom.* FROM player custom + /// let alias = TableAlias(name: "custom") /// let request = Player.all().aliased(alias) case table(tableName: String, userName: String?) - case derived(TableAlias) + + /// A TableAlias can be a proxy for another table alias. Two different + /// instances for the same table identifier: + /// + /// // Pointless example: make alias2 a proxy for alias1 + /// let alias1 = TableAlias() + /// let alias2 = TableAlias() + /// Player.all() + /// .aliased(alias1) + /// .aliased(alias2) + /// + /// Proxies are useful because queries get implicit aliases as soon + /// as they are joined with associations. In the example below, + /// customAlias becomes a proxy for the request's implicit alias, which + /// gets a custom name. This allows implicit and user aliases to merge + /// into a single "table identifier" that matches the user's expectations: + /// + /// // SELECT custom.*, team.* + /// // FROM player custom + /// // JOIN team ON taem.id = custom.teamId + /// // WHERE custom.name = 'Arthur' + /// let customAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team) + /// .filter(sql: "custom.name = 'Arthur'") + /// .aliased(customAlias) + case proxy(TableAlias) } - private var impl: Impl - // exposed for SQLGenerationContext and expression.resolvedExpression - var root: TableAlias { - if case .derived(let base) = impl { + /// Resolve all proxies + private var root: TableAlias { + if case .proxy(let base) = impl { return base.root } else { return self @@ -116,10 +146,11 @@ public class TableAlias: Hashable { var tableName: String { switch impl { case .undefined: + // Likely a GRDB bug fatalError("Undefined alias has no table name") case .table(tableName: let tableName, userName: _): return tableName - case .derived(let base): + case .proxy(let base): return base.tableName } } @@ -130,7 +161,7 @@ public class TableAlias: Hashable { return userName case .table(tableName: _, userName: let userName): return userName - case .derived(let base): + case .proxy(let base): return base.userName } } @@ -143,26 +174,27 @@ public class TableAlias: Hashable { self.impl = .table(tableName: tableName, userName: userName) } - func rebase(on base: TableAlias) { + func becomeProxy(of base: TableAlias) { switch impl { case .undefined(let userName): if let userName = userName { // rename base.setUserName(userName) } - self.impl = .derived(base) + self.impl = .proxy(base) default: + // Likely a GRDB bug fatalError("Not implemented") } } - func setUserName(_ userName: String) { + private func setUserName(_ userName: String) { switch impl { case .undefined: self.impl = .undefined(userName: userName) case .table(tableName: let tableName, userName: _): self.impl = .table(tableName: tableName, userName: userName) - case .derived(let base): + case .proxy(let base): base.setUserName(userName) } } @@ -172,8 +204,11 @@ public class TableAlias: Hashable { case .undefined(let userName): self.impl = .table(tableName: tableName, userName: userName) case .table(tableName: let initialTableName, userName: _): - GRDBPrecondition(tableName.lowercased() == initialTableName.lowercased(), "Can't change table name of a table alias") - case .derived(let base): + GRDBPrecondition( + tableName.lowercased() == initialTableName.lowercased(), + // Likely a GRDB bug + "Can't change table name of a table alias") + case .proxy(let base): base.setTableName(tableName) } } @@ -192,11 +227,7 @@ public class TableAlias: Hashable { /// :nodoc: public var hashValue: Int { - if case .derived(let base) = impl { - return base.hashValue - } else { - return ObjectIdentifier(self).hashValue - } + return ObjectIdentifier(root).hashValue } /// :nodoc: @@ -208,13 +239,11 @@ public class TableAlias: Hashable { extension Array where Element == TableAlias { /// Resolve ambiguities in aliases' names. fileprivate var resolvedNames: [TableAlias: String] { - let aliases = map { $0.root } - - // It is a programmer error to reuse the same (===) TableAlias for + // It is a programmer error to reuse the same TableAlias for // multiple tables. - GRDBPrecondition(aliases.count == Set(aliases).count, "A TableAlias most not be used to refer to multiple tables") + GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") - let groups = Dictionary.init(grouping: aliases) { + let groups = Dictionary.init(grouping: self) { $0.identityName.lowercased() } From c1c3233ba2f5b8cc2edfc6a7ad37e11467b19b7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 19:23:33 +0200 Subject: [PATCH 259/348] Remove two useless .init (thank you Xcode autocomplete) --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 2 +- GRDB/QueryInterface/SQLGenerationContext.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 8ac84c250..06813ca5b 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -11,7 +11,7 @@ class SQLiteDateParser { var hour: Int32 = 0 var minute: Int32 = 0 var second: Int32 = 0 - var nanosecond = ContiguousArray.init(repeating: 0, count: 10) // 9 digits, and trailing \0 + var nanosecond = ContiguousArray(repeating: 0, count: 10) // 9 digits, and trailing \0 } func components(from dateString: String) -> DatabaseDateComponents? { diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index b8aaf89c4..1fd7830bf 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -243,7 +243,7 @@ extension Array where Element == TableAlias { // multiple tables. GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") - let groups = Dictionary.init(grouping: self) { + let groups = Dictionary(grouping: self) { $0.identityName.lowercased() } From 756863152c9b0c5bc435de5c625f30fe613a7d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 19:33:07 +0200 Subject: [PATCH 260/348] Fix documentation typos --- GRDB/QueryInterface/Association/Association.swift | 2 +- GRDB/QueryInterface/QueryInterfaceRequest.swift | 2 +- GRDB/QueryInterface/RequestProtocols.swift | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 53fa919b9..2c034f97b 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -61,7 +61,7 @@ public protocol Association: DerivableRequest { } extension Association { - /// Creates an association with a new net of selected columns. + /// Creates an association with a new set of selected columns. /// /// struct Player: TableRecord { /// static let team = belongsTo(Team.self) diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index a7ab4b20d..f6b62bcda 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -47,7 +47,7 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { // MARK: Request Derivation - /// Creates a request with a new net of selected columns. + /// Creates a request with a new set of selected columns. /// /// // SELECT id, email FROM player /// var request = Player.all() diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 3588a77d3..6d87d39c1 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -2,7 +2,7 @@ /// The protocol for all requests that can refine their selection. public protocol SelectionRequest { - /// Creates a request with a new net of selected columns. + /// Creates a request with a new set of selected columns. /// /// // SELECT id, email FROM player /// var request = Player.all() @@ -18,7 +18,7 @@ public protocol SelectionRequest { } extension SelectionRequest { - /// Creates a request with a new net of selected columns. + /// Creates a request with a new set of selected columns. /// /// // SELECT id, email FROM player /// var request = Player.all() @@ -34,7 +34,7 @@ extension SelectionRequest { return select(selection) } - /// Creates a request with a new net of selected columns. + /// Creates a request with a new set of selected columns. /// /// // SELECT id, email FROM player /// var request = Player.all() From aead6eec4acba1ca634182284d40063e86b0d551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 7 May 2018 19:39:13 +0200 Subject: [PATCH 261/348] Sometimes you don't understand what you read because information is not given at the right time --- GRDB/QueryInterface/RequestProtocols.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index 6d87d39c1..a47975774 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -182,16 +182,16 @@ extension TableRequest where Self: FilteredRequest { // Prevent filter(keys: [["foo": 1, "bar": 2]]) where // ("foo", "bar") is not a unique key (primary key or columns of a // unique index) - guard let orderedColumns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { + guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else { fatalError("table \(databaseTableName) has no unique index on column(s) \(key.keys.sorted().joined(separator: ", "))") } - let lowercaseOrderedColumns = orderedColumns.map { $0.lowercased() } + let lowercaseColumns = columns.map { $0.lowercased() } return key - // Sort key columns in the same order as the unique index + // Preserve ordering of columns in the unique index .sorted { (kv1, kv2) in - let index1 = lowercaseOrderedColumns.index(of: kv1.key.lowercased())! - let index2 = lowercaseOrderedColumns.index(of: kv2.key.lowercased())! + let index1 = lowercaseColumns.index(of: kv1.key.lowercased())! + let index2 = lowercaseColumns.index(of: kv2.key.lowercased())! return index1 < index2 } .map { (column, value) in Column(column) == value } From 2de040a6f1dcad45108f246305bc6f65f693ae00 Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sat, 12 May 2018 15:39:59 +0200 Subject: [PATCH 262/348] Use `String(format: ...)` ... instead of `NSString(format: ...) as String` --- GRDB/Core/Support/Foundation/DatabaseDateComponents.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 4ca356877..518aaf024 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -94,7 +94,7 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn let year = dateComponents.year ?? 0 let month = dateComponents.month ?? 1 let day = dateComponents.day ?? 1 - dateString = NSString(format: "%04d-%02d-%02d", year, month, day) as String + dateString = String(format: "%04d-%02d-%02d", year, month, day) default: dateString = nil } @@ -104,18 +104,18 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn case .YMD_HM, .HM: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 - timeString = NSString(format: "%02d:%02d", hour, minute) as String + timeString = String(format: "%02d:%02d", hour, minute) case .YMD_HMS, .HMS: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 - timeString = NSString(format: "%02d:%02d:%02d", hour, minute, second) as String + timeString = String(format: "%02d:%02d:%02d", hour, minute, second) case .YMD_HMSS, .HMSS: let hour = dateComponents.hour ?? 0 let minute = dateComponents.minute ?? 0 let second = dateComponents.second ?? 0 let nanosecond = dateComponents.nanosecond ?? 0 - timeString = NSString(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) as String + timeString = String(format: "%02d:%02d:%02d.%03d", hour, minute, second, Int(round(Double(nanosecond) / 1_000_000.0))) default: timeString = nil } From 857798b9399c2983f9cef656591581ea9a8469fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 15 May 2018 13:35:36 +0200 Subject: [PATCH 263/348] Extend the "thank you" notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4ff47bd1d..9f51449ee 100644 --- a/README.md +++ b/README.md @@ -7358,7 +7358,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From 5136142d83a94c4b5df45919910910087a94fd7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 May 2018 08:49:47 +0200 Subject: [PATCH 264/348] Playgrounds documentation --- .../Contents.swift | 22 ++++++++++++------- .../contents.xcplayground | 2 +- Playgrounds/Record.playground/Contents.swift | 8 ++++++- .../Record.playground/contents.xcplayground | 2 +- Playgrounds/Tour.playground/Contents.swift | 8 ++++++- .../Tour.playground/contents.xcplayground | 2 +- .../Contents.swift | 15 ++++++++----- .../contents.xcplayground | 2 +- 8 files changed, 42 insertions(+), 19 deletions(-) diff --git a/Playgrounds/JSONSynchronization.playground/Contents.swift b/Playgrounds/JSONSynchronization.playground/Contents.swift index 039c1ad3a..0a3184746 100644 --- a/Playgrounds/JSONSynchronization.playground/Contents.swift +++ b/Playgrounds/JSONSynchronization.playground/Contents.swift @@ -1,11 +1,17 @@ -// To run this playground, select and build the GRDBOSX scheme. -// -// This sample code shows how to use GRDB to synchronize a database table -// with a JSON payload. We use as few SQL queries as possible: -// -// - Only one SELECT query. -// - One query per insert, delete, and update. -// - Useless UPDATE statements are avoided. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground +//: +//: This sample code shows how to use GRDB to synchronize a database table +//: with a JSON payload. We use as few SQL queries as possible: +//: +//: - Only one SELECT query. +//: - One query per insert, delete, and update. +//: - Useless UPDATE statements are avoided. import Foundation import GRDB diff --git a/Playgrounds/JSONSynchronization.playground/contents.xcplayground b/Playgrounds/JSONSynchronization.playground/contents.xcplayground index 16f9952aa..dd3ff35de 100644 --- a/Playgrounds/JSONSynchronization.playground/contents.xcplayground +++ b/Playgrounds/JSONSynchronization.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/Record.playground/Contents.swift b/Playgrounds/Record.playground/Contents.swift index 258191d82..bb8ad7265 100644 --- a/Playgrounds/Record.playground/Contents.swift +++ b/Playgrounds/Record.playground/Contents.swift @@ -1,4 +1,10 @@ -//: To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground //: //: Record //: ====== diff --git a/Playgrounds/Record.playground/contents.xcplayground b/Playgrounds/Record.playground/contents.xcplayground index 3de2b51ba..fd676d5b4 100644 --- a/Playgrounds/Record.playground/contents.xcplayground +++ b/Playgrounds/Record.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/Tour.playground/Contents.swift b/Playgrounds/Tour.playground/Contents.swift index af215f9d5..a87fe0aff 100644 --- a/Playgrounds/Tour.playground/Contents.swift +++ b/Playgrounds/Tour.playground/Contents.swift @@ -1,4 +1,10 @@ -//: To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground //: //: Tour //: ====== diff --git a/Playgrounds/Tour.playground/contents.xcplayground b/Playgrounds/Tour.playground/contents.xcplayground index 3de2b51ba..fd676d5b4 100644 --- a/Playgrounds/Tour.playground/contents.xcplayground +++ b/Playgrounds/Tour.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/Playgrounds/TransactionObserver.playground/Contents.swift b/Playgrounds/TransactionObserver.playground/Contents.swift index 9a151b925..05553a55e 100644 --- a/Playgrounds/TransactionObserver.playground/Contents.swift +++ b/Playgrounds/TransactionObserver.playground/Contents.swift @@ -1,13 +1,17 @@ -// To run this playground, select and build the GRDBOSX scheme. +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground import GRDB // Create the databsae -var configuration = Configuration() -configuration.trace = { print($0) } -let dbQueue = DatabaseQueue(configuration: configuration) // Memory database +let dbQueue = DatabaseQueue() // Memory database var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in try db.execute( @@ -80,6 +84,7 @@ try dbQueue.inTransaction { db in print("-- Changes 3") -try dbQueue.inDatabase { db in +try dbQueue.write { db in try db.execute("DELETE FROM persons") + try db.execute("DELETE FROM pets") } diff --git a/Playgrounds/TransactionObserver.playground/contents.xcplayground b/Playgrounds/TransactionObserver.playground/contents.xcplayground index 06828af92..3de2b51ba 100644 --- a/Playgrounds/TransactionObserver.playground/contents.xcplayground +++ b/Playgrounds/TransactionObserver.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file From eddc078c2dfcced7bbc160ebda4e304a34cc8334 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 May 2018 14:29:03 +0200 Subject: [PATCH 265/348] Prepare AlternateRowDecoder playground --- GRDB.xcworkspace/contents.xcworkspacedata | 3 + .../Contents.swift | 188 ++++++++++++++++++ .../contents.xcplayground | 4 + 3 files changed, 195 insertions(+) create mode 100644 Playgrounds/AlternateRowDecoder.playground/Contents.swift create mode 100644 Playgrounds/AlternateRowDecoder.playground/contents.xcplayground diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index d547997e4..5856985d6 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -19,6 +19,9 @@ + + diff --git a/Playgrounds/AlternateRowDecoder.playground/Contents.swift b/Playgrounds/AlternateRowDecoder.playground/Contents.swift new file mode 100644 index 000000000..31f6de510 --- /dev/null +++ b/Playgrounds/AlternateRowDecoder.playground/Contents.swift @@ -0,0 +1,188 @@ +import GRDB + +protocol DatabaseDecoder { + associatedtype DecodedType + static func decode(row: Row) -> DecodedType +} + +// MARK: Fetching From SelectStatement + +/// Fetch from prepared statement: +/// +/// struct Decoder: DatabaseDecoder { ... } +/// try dbQueue.read { db in +/// let statement = try db.makeSelectStatement("SELECT ...") +/// let values = try Decoder.fetchAll(statement) +/// } +extension DatabaseDecoder { + static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + self.decode(row: $0) + } + } + + static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) + } + + static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() + } +} + +// MARK: Fetching From FetchRequest + +/// Fetch from request: +/// +/// struct Decoder: DatabaseDecoder { ... } +/// try dbQueue.read { db in +/// let request = SQLRequest("SELECT ...") +/// let values = try Decoder.fetchAll(db, request) +/// } +extension DatabaseDecoder { + static func fetchCursor(_ db: Database, _ request: R) throws -> MapCursor { + let (statement, adapter) = try request.prepare(db) + return try fetchCursor(statement, adapter: adapter) + } + + static func fetchAll(_ db: Database, _ request: R) throws -> [DecodedType] { + let (statement, adapter) = try request.prepare(db) + return try fetchAll(statement, adapter: adapter) + } + + static func fetchOne(_ db: Database, _ request: R) throws -> DecodedType? { + let (statement, adapter) = try request.prepare(db) + return try fetchOne(statement, adapter: adapter) + } +} + +/// Requests can fetch, too: +/// +/// struct Decoder: DatabaseDecoder { ... } +/// try dbQueue.read { db in +/// let request = SQLRequest("SELECT ...") +/// let values = try request.fetchAll(db) +/// } +/// +/// extension Decoder: TableRecord { ... } +/// try dbQueue.read { db in +/// let request = Decoder.filter(...).order(...) +/// let values = try request.fetchAll(db) +/// } +extension FetchRequest where RowDecoder: DatabaseDecoder { + func fetchCursor(_ db: Database) throws -> MapCursor { + return try RowDecoder.fetchCursor(db, self) + } + + func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] { + return try RowDecoder.fetchAll(db, self) + } + + func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? { + return try RowDecoder.fetchOne(db, self) + } +} + +// MARK: Fetching From SQL + +/// Fetch from SQL: +/// +/// struct Decoder: DatabaseDecoder { ... } +/// try dbQueue.read { db in +/// let values = try Decoder.fetchAll(db, "SELECT ...") +/// } +extension DatabaseDecoder { + static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } +} + +// ============================================================================= + +class Base { + var id: Int64 + var description: String { return "Base(\(id))" } + init(id: Int64) { + self.id = id + } +} + +class Foo: Base { + var name: String + override var description: String { return "Foo(\(id),\(name))" } + init(id: Int64, name: String) { + self.name = name + super.init(id: id) + } +} + +class Bar: Base { + var score: Int + override var description: String { return "Bar(\(id),\(score))" } + init(id: Int64, score: Int) { + self.score = score + super.init(id: id) + } +} + +// ============================================================================= + +extension Base: TableRecord { + static let databaseTableName = "base" +} + +extension Base: DatabaseDecoder { + static func decode(row: Row) -> Base { + switch row["type"] as String { + case "Foo": + return Foo(id: row["id"], name: row["name"]) + case "Bar": + return Bar(id: row["id"], score: row["score"]) + case let type: + fatalError("Unknown type: \(type)") + } + } +} + +// ============================================================================= + +let dbQueue = DatabaseQueue() +try dbQueue.write { db in + try db.create(table: "base") { t in + t.autoIncrementedPrimaryKey("id") + t.column("type", .text).notNull() + t.column("name", .text) + t.column("score", .integer) + } + try db.execute(""" + INSERT INTO base (type, name, score) VALUES (?, ?, ?); + INSERT INTO base (type, name, score) VALUES (?, ?, ?); + """, arguments: [ + "Foo", "Arthur", nil, + "Bar", nil, 100 + ]) + + do { + // Fetch from SQL + let bases = try Base.fetchAll(db, "SELECT * FROM base") + for base in bases { + print(base.description) + } + } + + do { + // Fetch from query interface request + let bases = try Base.order(Column("id").desc).fetchAll(db) + for base in bases { + print(base.description) + } + } +} diff --git a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground new file mode 100644 index 000000000..63b6dd8df --- /dev/null +++ b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file From 1f274f5c0450ed98d4249ac76735caec5676fbce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 May 2018 18:47:12 +0200 Subject: [PATCH 266/348] More AlternateRowDecoder playground --- .../Contents.swift | 278 +++++++++++++----- .../contents.xcplayground | 2 +- 2 files changed, 213 insertions(+), 67 deletions(-) diff --git a/Playgrounds/AlternateRowDecoder.playground/Contents.swift b/Playgrounds/AlternateRowDecoder.playground/Contents.swift index 31f6de510..6f11c5843 100644 --- a/Playgrounds/AlternateRowDecoder.playground/Contents.swift +++ b/Playgrounds/AlternateRowDecoder.playground/Contents.swift @@ -1,10 +1,188 @@ import GRDB +//: This playground demonstrates how one can implement **customized decoding of +//: database rows**. +//: +//: Customized row decoding allows you to go beyong the built-in support for +//: requests of raw rows, values, or types that adopt the +//: FetchableRecord protocol. +//: +//: For example: +//: +//: - Your application needs polymorphic row decoding (which means decoding some +//: class or another depending on the values contained in a database row). +//: +//: - Your application needs to decode rows with a context - which means that +//: each decoded value should be initialized with some extra value that does not +//: come from the database. +//: +//: - Your application needs a record type that supports untrusted databases, +//: and may fail at decoding database rows (throw an error when a row contains +//: invalid values). +//: +//: None of those use cases can be handled by the built-in `FetchableRecord` +//: protocol and its `init(row:)` initializer. They need *customized +//: row decoding*. +//: +//: In this playground, we will provide some sample code that performs +//: polymorphic row decoding. Given a base class, `Base`, and two subclasses +//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the +//: value found in the `type` column of the `base` database table. +//: +//: From this sample code, we hope that you will be able to derive your own +//: customized decoding. +//: +//: Everything starts from our class hierarchy: + +class Base { + var description: String { return "Base" } + init() { } +} + +class Foo: Base { + var name: String + override var description: String { return "Foo: \(name)" } + init(name: String) { + self.name = name + super.init() + } +} + +class Bar: Base { + var score: Int + override var description: String { return "Bar: \(score)" } + init(score: Int) { + self.score = score + super.init() + } +} + +//: We need a database, a table, and a few values so that we can do a real demo: + +// An in-memory database is good enough +let dbQueue = DatabaseQueue() + +try dbQueue.write { db in + // Database table + try db.create(table: "base") { t in + t.column("type", .text).notNull() // Contains "Foo" or "Bar" + t.column("fooName", .text) // Contains a Foo's name + t.column("barScore", .integer) // Contains a Bar's score + } + + // Demo values: two Foo and one Bar + try db.execute(""" + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?); + """, arguments: [ + "Foo", "Arthur", nil, + "Bar", nil, 100, + "Foo", "Barbara", nil, + ]) +} + +//: We also need a method that decodes database rows into `Foo` or `Bar` +//: instances: let's call it `Base.decode(row:)`: + +extension Base { + static func decode(row: Row) -> Base { + switch row["type"] as String { + case "Foo": + return Foo(name: row["fooName"]) + case "Bar": + return Bar(score: row["barScore"]) + case let type: + fatalError("Unknown Base type: \(type)") + } + } +} + +//: Now we are able to express the kind of request we'd like to write. For +//: example, we could fetch all Base values from the database: +//: +//: try dbQueue.read { db in +//: // An array [Base] that constains Foo and Bar instances +//: let bases = try Base.fetchAll(db) +//: } +//: +//: But so far, we have a compiler error: + +// Compiler error: Type 'Base' has no member 'fetchAll' +//try dbQueue.read { db in +// let bases = try Base.fetchAll(db) +//} + +//: We'll see that this goal can be achieved by declaring a protocol, writing a +//: few extensions that guarantee the most efficient use of GRDB, and have the +//: Base class adopt this protocol. +//: +//: But first, let's see how polymorphic decoding can be done as simply as +//: possible. After all, it is useless to design a full-fledged protocol unless +//: we need to use this protocol several times, or write code that is as +//: streamlined as possible. Keep it simple, stupid! +//: +//: Can we fetch Foo and Bar values from an SQL request? Sure: + +try dbQueue.read { db in + print("> KISS: Fetch from SQL") + let rows = try Row.fetchAll(db, "SELECT * FROM base") // Fetch database rows + let bases = rows.map { row in // Decode database rows + Base.decode(row: row) + } + for base in bases { // Use fetched values + print(base.description) + } +} + +//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the +//: `TableRecord` protocol: + +extension Base: TableRecord { + static let databaseTableName = "base" +} + +try dbQueue.read { db in + print("> KISS: Fetch from query interface request") + let request = Base.filter(Column("type") == "Foo") // Define a request + let rows = try Row.fetchAll(db, request) // Fetch database rows + let bases = rows.map { row in // Decode database rows + Base.decode(row: row) + } + for base in bases { // Use fetched values + print(base.description) + } +} + +//: As seen above, we can perform polymorphic requests with the standard GRDB, +//: by fetching raw rows and mapping them through a decoding method. +//: +//: The resulting code is not as streamlined as usual GRDB code, but we could +//: already do what we needed without much effort. +//: +//: In the rest of this playground, we will define a **new realm of requests**. +//: +//: GRDB ships with three build-in realms of requests: requests of raw rows, +//: requests of values, and requests of record types that adopt the +//: `FetchableRecord` protocol. +//: +//: We'll define requests of record types that adopt the custom +//: `DatabaseDecoder` protocol: + protocol DatabaseDecoder { associatedtype DecodedType static func decode(row: Row) -> DecodedType } +//: Types that adopt the DatabaseDecoder protocol are able to perform the +//: polymorphic decoding of our Base type: + +extension Base: DatabaseDecoder { + // Uses the decode(row: Row) already declared above +} + +//: + // MARK: Fetching From SelectStatement /// Fetch from prepared statement: @@ -105,82 +283,50 @@ extension DatabaseDecoder { } } -// ============================================================================= +// MARK: Fetching From Base Tye -class Base { - var id: Int64 - var description: String { return "Base(\(id))" } - init(id: Int64) { - self.id = id +/// Fetch from SQL: +/// +/// struct Decoder: DatabaseDecoder { ... } +/// try dbQueue.read { db in +/// let values = try Decoder.fetchAll(db) +/// } +extension DatabaseDecoder where Self: TableRecord { + static func fetchCursor(_ db: Database) throws -> MapCursor { + return try all().fetchCursor(db) } -} - -class Foo: Base { - var name: String - override var description: String { return "Foo(\(id),\(name))" } - init(id: Int64, name: String) { - self.name = name - super.init(id: id) - } -} - -class Bar: Base { - var score: Int - override var description: String { return "Bar(\(id),\(score))" } - init(id: Int64, score: Int) { - self.score = score - super.init(id: id) - } -} - -// ============================================================================= - -extension Base: TableRecord { - static let databaseTableName = "base" -} - -extension Base: DatabaseDecoder { - static func decode(row: Row) -> Base { - switch row["type"] as String { - case "Foo": - return Foo(id: row["id"], name: row["name"]) - case "Bar": - return Bar(id: row["id"], score: row["score"]) - case let type: - fatalError("Unknown type: \(type)") - } - } -} - -// ============================================================================= - -let dbQueue = DatabaseQueue() -try dbQueue.write { db in - try db.create(table: "base") { t in - t.autoIncrementedPrimaryKey("id") - t.column("type", .text).notNull() - t.column("name", .text) - t.column("score", .integer) - } - try db.execute(""" - INSERT INTO base (type, name, score) VALUES (?, ?, ?); - INSERT INTO base (type, name, score) VALUES (?, ?, ?); - """, arguments: [ - "Foo", "Arthur", nil, - "Bar", nil, 100 - ]) + static func fetchAll(_ db: Database) throws -> [DecodedType] { + return try all().fetchAll(db) + } + + static func fetchOne(_ db: Database) throws -> DecodedType? { + return try all().fetchOne(db) + } +} + +// ============================================================================= + +try dbQueue.read { db in do { - // Fetch from SQL + print("> Fetch from SQL") let bases = try Base.fetchAll(db, "SELECT * FROM base") for base in bases { print(base.description) } } - + do { - // Fetch from query interface request - let bases = try Base.order(Column("id").desc).fetchAll(db) + print("> Fetch from query interface request") + let bases = try Base.filter(Column("type") == "Foo").fetchAll(db) + for base in bases { + print(base.description) + } + } + + do { + print("> Fetch right from the Base type") + let bases = try Base.fetchAll(db) for base in bases { print(base.description) } diff --git a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground index 63b6dd8df..b1148fc50 100644 --- a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground +++ b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file From 0a3a8d738abfb4b6e5835b3104c376f3d56bb75d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 18 May 2018 19:20:03 +0200 Subject: [PATCH 267/348] AlternateRowDecoder playground --- .../Contents.swift | 237 +++++++++++------- 1 file changed, 144 insertions(+), 93 deletions(-) diff --git a/Playgrounds/AlternateRowDecoder.playground/Contents.swift b/Playgrounds/AlternateRowDecoder.playground/Contents.swift index 6f11c5843..9253c1565 100644 --- a/Playgrounds/AlternateRowDecoder.playground/Contents.swift +++ b/Playgrounds/AlternateRowDecoder.playground/Contents.swift @@ -1,3 +1,13 @@ +//: # Customized Decoding of Database Rows +//: +//: To run this playground: +//: +//: - Open GRDB.xcworkspace +//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX +//: - Build: menu Product > Build +//: - Select the playground in the Playgrounds Group +//: - Run the playground + import GRDB //: This playground demonstrates how one can implement **customized decoding of @@ -24,6 +34,8 @@ import GRDB //: protocol and its `init(row:)` initializer. They need *customized //: row decoding*. //: +//: ## An Example: Polymorphic Decoding +//: //: In this playground, we will provide some sample code that performs //: polymorphic row decoding. Given a base class, `Base`, and two subclasses //: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the @@ -117,10 +129,12 @@ extension Base { //: few extensions that guarantee the most efficient use of GRDB, and have the //: Base class adopt this protocol. //: +//: ## Keep It Simple, Stupid! +//: //: But first, let's see how polymorphic decoding can be done as simply as //: possible. After all, it is useless to design a full-fledged protocol unless //: we need to use this protocol several times, or write code that is as -//: streamlined as possible. Keep it simple, stupid! +//: streamlined as possible. //: //: Can we fetch Foo and Bar values from an SQL request? Sure: @@ -160,6 +174,8 @@ try dbQueue.read { db in //: The resulting code is not as streamlined as usual GRDB code, but we could //: already do what we needed without much effort. //: +//: ## Custom Protocol: MyDatabaseDecoder +//: //: In the rest of this playground, we will define a **new realm of requests**. //: //: GRDB ships with three build-in realms of requests: requests of raw rows, @@ -167,57 +183,79 @@ try dbQueue.read { db in //: `FetchableRecord` protocol. //: //: We'll define requests of record types that adopt the custom -//: `DatabaseDecoder` protocol: +//: `MyDatabaseDecoder` protocol: -protocol DatabaseDecoder { +protocol MyDatabaseDecoder { associatedtype DecodedType static func decode(row: Row) -> DecodedType } -//: Types that adopt the DatabaseDecoder protocol are able to perform the -//: polymorphic decoding of our Base type: +//: Types that adopt the MyDatabaseDecoder protocol are able, among other +//: things, to perform polymorphic decoding. Our Base class, for example: -extension Base: DatabaseDecoder { - // Uses the decode(row: Row) already declared above +extension Base: MyDatabaseDecoder { + // Already declared above: + // static func decode(row: Row) -> Base { ... } } -//: +//: Now let's see how we can define a new realm of requests based on the +//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as +//: raedy-made requests of rows, values and FetchableRecord. +//: +//: All we need is a set of *extensions* that define the classic GRDB fetching +//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one +//: is `fetchCursor`, because from it we can derive the two others. +//: +//: The first extension is the most low-level one: fetching from SQLite +//: **prepared statement**: +//: +//: try dbQueue.read { db in +//: let statement = try db.makeSelectStatement("SELECT ...") +//: try Base.fetchCursor(statement) // Cursor of Base +//: try Base.fetchAll(statement) // [Base] +//: try Base.fetchOne(statement) // Base? +//: } -// MARK: Fetching From SelectStatement - -/// Fetch from prepared statement: -/// -/// struct Decoder: DatabaseDecoder { ... } -/// try dbQueue.read { db in -/// let statement = try db.makeSelectStatement("SELECT ...") -/// let values = try Decoder.fetchAll(statement) -/// } -extension DatabaseDecoder { +extension MyDatabaseDecoder { static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + // Turn the cursor of raw rows into a cursor of decoded rows return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { self.decode(row: $0) } } static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + // Turn the cursor into an Array return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter)) } static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + // Consume the first value of the cursor return try fetchCursor(statement, arguments: arguments, adapter: adapter).next() } } -// MARK: Fetching From FetchRequest +try dbQueue.read { db in + print("> Fetch from prepared statement") + let statement = try db.makeSelectStatement("SELECT * FROM base") + let bases = try Base.fetchAll(statement) + for base in bases { + print(base.description) + } +} -/// Fetch from request: -/// -/// struct Decoder: DatabaseDecoder { ... } -/// try dbQueue.read { db in -/// let request = SQLRequest("SELECT ...") -/// let values = try Decoder.fetchAll(db, request) -/// } -extension DatabaseDecoder { +//: Now that we can fetch from prepared statements, we can fetch when given a +//: **request**, as defined by the `FetchRequest` protocol. This is the +//: protocol for query interface requests such as `Base.all()`, or +//: `SQLRequest`, etc. +//: +//: try dbQueue.read { db in +//: let request = Base.all() +//: try Base.fetchCursor(db, request) // Cursor of Base +//: try Base.fetchAll(db, request) // [Base] +//: try Base.fetchOne(db, request) // Base? +//: } +extension MyDatabaseDecoder { static func fetchCursor(_ db: Database, _ request: R) throws -> MapCursor { let (statement, adapter) = try request.prepare(db) return try fetchCursor(statement, adapter: adapter) @@ -234,20 +272,25 @@ extension DatabaseDecoder { } } -/// Requests can fetch, too: -/// -/// struct Decoder: DatabaseDecoder { ... } -/// try dbQueue.read { db in -/// let request = SQLRequest("SELECT ...") -/// let values = try request.fetchAll(db) -/// } -/// -/// extension Decoder: TableRecord { ... } -/// try dbQueue.read { db in -/// let request = Decoder.filter(...).order(...) -/// let values = try request.fetchAll(db) -/// } -extension FetchRequest where RowDecoder: DatabaseDecoder { +try dbQueue.read { db in + print("> Fetch given a request") + let request = Base.all() + let bases = try Base.fetchAll(db, request) + for base in bases { + print(base.description) + } +} + +//: When it's fine to fetch given a request, it's even better when requests can +//: fetch, too: +//: +//: try dbQueue.read { db in +//: let request = Base.all() +//: try request.fetchCursor(db) // Cursor of Base +//: try request.fetchAll(db) // [Base] +//: try request.fetchOne(db) // Base? +//: } +extension FetchRequest where RowDecoder: MyDatabaseDecoder { func fetchCursor(_ db: Database) throws -> MapCursor { return try RowDecoder.fetchCursor(db, self) } @@ -261,37 +304,24 @@ extension FetchRequest where RowDecoder: DatabaseDecoder { } } -// MARK: Fetching From SQL - -/// Fetch from SQL: -/// -/// struct Decoder: DatabaseDecoder { ... } -/// try dbQueue.read { db in -/// let values = try Decoder.fetchAll(db, "SELECT ...") -/// } -extension DatabaseDecoder { - static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { - return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) - } - - static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { - return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) - } - - static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { - return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) +try dbQueue.read { db in + print("> Fetch from request") + let request = Base.all() + let bases = try request.fetchAll(db) + for base in bases { + print(base.description) } } -// MARK: Fetching From Base Tye - -/// Fetch from SQL: -/// -/// struct Decoder: DatabaseDecoder { ... } -/// try dbQueue.read { db in -/// let values = try Decoder.fetchAll(db) -/// } -extension DatabaseDecoder where Self: TableRecord { +//: Types that adopt both FetchableRecord and TableRecord are able to fetch +//: right from the base type. Let's allow this as well for MyDatabaseDecoder: +//: +//: try dbQueue.read { db in +//: try Base.fetchCursor(db) // Cursor of Base +//: try Base.fetchAll(db) // [Base] +//: try Base.fetchOne(db) // Base? +//: } +extension MyDatabaseDecoder where Self: TableRecord { static func fetchCursor(_ db: Database) throws -> MapCursor { return try all().fetchCursor(db) } @@ -305,30 +335,51 @@ extension DatabaseDecoder where Self: TableRecord { } } -// ============================================================================= - try dbQueue.read { db in - do { - print("> Fetch from SQL") - let bases = try Base.fetchAll(db, "SELECT * FROM base") - for base in bases { - print(base.description) - } - } - - do { - print("> Fetch from query interface request") - let bases = try Base.filter(Column("type") == "Foo").fetchAll(db) - for base in bases { - print(base.description) - } - } - - do { - print("> Fetch right from the Base type") - let bases = try Base.fetchAll(db) - for base in bases { - print(base.description) - } + print("> Fetch from base type") + let bases = try Base.fetchAll(db) + for base in bases { + print(base.description) } } + +//: Finally, you don't have a true GRDB record unless it allows fetching from +//: raw SQL: +//: +//: try dbQueue.read { db in +//: try Base.fetchCursor(db, "SELECT ...") // Cursor of Base +//: try Base.fetchAll(db, "SELECT ...") // [Base] +//: try Base.fetchOne(db, "SELECT ...") // Base? +//: } +extension MyDatabaseDecoder { + static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] { + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } + + static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? { + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) + } +} + +try dbQueue.read { db in + print("> Fetch from SQL") + let bases = try Base.fetchAll(db, "SELECT * FROM base") + for base in bases { + print(base.description) + } +} + +//: This is the end of this tour of **customized decoding of database rows**. +//: +//: In this tour, you have learned: +//: +//: - to keep things simple: as long as you can fetch rows, you can decode them +//: the way you want. +//: - to define a whole new realm of requests based on a custom protocol. This +//: involves writing a few extensions that give your protocol the same fluent +//: interface that is ready-made for the built-in FetchableRecord protocol. This +//: is more work, but you are granted with the full customization power. From 5637514dd6a04b845830f7836aee1601f09a1b61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 12:25:35 +0200 Subject: [PATCH 268/348] AlternateRowDecoder playground --- .../Contents.swift | 82 +++++++++++++++++-- .../contents.xcplayground | 2 +- 2 files changed, 75 insertions(+), 9 deletions(-) diff --git a/Playgrounds/AlternateRowDecoder.playground/Contents.swift b/Playgrounds/AlternateRowDecoder.playground/Contents.swift index 9253c1565..d1f6c7d76 100644 --- a/Playgrounds/AlternateRowDecoder.playground/Contents.swift +++ b/Playgrounds/AlternateRowDecoder.playground/Contents.swift @@ -217,6 +217,8 @@ extension Base: MyDatabaseDecoder { //: } extension MyDatabaseDecoder { + // SelectStatement, StatementArguments, and RowAdapter are the fundamental + // fetching parameters of GRDB. Make sure to accept them all: static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor { // Turn the cursor of raw rows into a cursor of decoded rows return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { @@ -373,13 +375,77 @@ try dbQueue.read { db in } } -//: This is the end of this tour of **customized decoding of database rows**. +//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in +//: `FetchableRecord` protocol. //: -//: In this tour, you have learned: +//: To sum up, you have learned: //: -//: - to keep things simple: as long as you can fetch rows, you can decode them -//: the way you want. -//: - to define a whole new realm of requests based on a custom protocol. This -//: involves writing a few extensions that give your protocol the same fluent -//: interface that is ready-made for the built-in FetchableRecord protocol. This -//: is more work, but you are granted with the full customization power. +//: - how to keep things simple: as long as you can fetch rows, you can decode +//: them the way you want. +//: - how to define a whole new realm of requests based on a custom protocol. +//: This involves writing a few extensions that give your protocol the same +//: fluent interface that is ready-made for the built-in FetchableRecord +//: protocol. This is more work, but you are granted with the full +//: customization freedom. +//: +//: To end this tour, let's quickly look at two other possible customized +//: row decoding strategies: +//: +//: - Your application needs to decode rows with a context - which means that +//: each decoded value should be initialized with some extra value that does not +//: come from the database. +//: +//: In this case, you may define a `ContextFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as above): + +protocol ContextFetchableRecord { + associatedtype Context + init(row: Row, context: Context) +} + +extension ContextFetchableRecord { + static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil, + context: Context) + throws -> MapCursor + { + // Turn the cursor of raw rows into a cursor of decoded rows + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + self.init(row: $0, context: context) + } + } + + // Define fetchAll, fetchOne, ... +} + +//: - Your application needs a record type that supports untrusted databases, +//: and may fail at decoding database rows (throw an error when a row contains +//: invalid values). +//: +//: In this case, you may define a `FailableFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as above): + +protocol FailableFetchableRecord { + init(row: Row) throws +} + +extension FailableFetchableRecord { + static func fetchCursor( + _ statement: SelectStatement, + arguments: StatementArguments? = nil, + adapter: RowAdapter? = nil) + throws -> MapCursor + { + // Turn the cursor of raw rows into a cursor of decoded rows + return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map { + try self.init(row: $0) + } + } + + // Define fetchAll, fetchOne, ... +} + diff --git a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground index b1148fc50..3a493ef23 100644 --- a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground +++ b/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file From 2ce2b4885d5995693ed8441c4a77a8d5d2356da0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 12:26:38 +0200 Subject: [PATCH 269/348] Rename playground --- GRDB.xcworkspace/contents.xcworkspacedata | 2 +- .../Contents.swift | 0 .../contents.xcplayground | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename Playgrounds/{AlternateRowDecoder.playground => CustomizedDecodingOfDatabaseRows.playground}/Contents.swift (100%) rename Playgrounds/{AlternateRowDecoder.playground => CustomizedDecodingOfDatabaseRows.playground}/contents.xcplayground (100%) diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index 5856985d6..3a81d3df3 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -20,7 +20,7 @@ location = "group:Issue156.playground"> + location = "group:/Users/groue/Documents/git/groue/GRDB.swift/Playgrounds/CustomizedDecodingOfDatabaseRows.playground"> diff --git a/Playgrounds/AlternateRowDecoder.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift similarity index 100% rename from Playgrounds/AlternateRowDecoder.playground/Contents.swift rename to Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift diff --git a/Playgrounds/AlternateRowDecoder.playground/contents.xcplayground b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground similarity index 100% rename from Playgrounds/AlternateRowDecoder.playground/contents.xcplayground rename to Playgrounds/CustomizedDecodingOfDatabaseRows.playground/contents.xcplayground From 785853dd2b3b17c278a9b0225cb2a638727624b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 12:28:52 +0200 Subject: [PATCH 270/348] Move the Custom Value Types chapter --- README.md | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 9f51449ee..3d6f7c1a3 100644 --- a/README.md +++ b/README.md @@ -545,11 +545,11 @@ SQLite API - [Date and DateComponents](#date-and-datecomponents) - [NSNumber and NSDecimalNumber](#nsnumber-and-nsdecimalnumber) - [Swift enums](#swift-enums) + - [Custom Value Types](#custom-value-types) - [Transactions and Savepoints](#transactions-and-savepoints) Advanced topics: -- [Custom Value Types](#custom-value-types) - [Prepared Statements](#prepared-statements) - [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) - [Database Schema Introspection](#database-schema-introspection) @@ -1327,6 +1327,27 @@ Grape.fromDatabaseValue(row[0]) // nil ``` +### Custom Value Types + +Conversion to and from the database is based on the `DatabaseValueConvertible` protocol: + +```swift +protocol DatabaseValueConvertible { + /// Returns a value that can be stored in the database. + var databaseValue: DatabaseValue { get } + + /// Returns a value initialized from dbValue, if possible. + static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? +} +``` + +All types that adopt this protocol can be used like all other [values](#values) (Bool, Int, String, Date, Swift enums, etc.) + +The `databaseValue` property returns [DatabaseValue](#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail. + +The `fromDatabaseValue()` factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly). + + ## Transactions and Savepoints - [Transactions and Safety](#transactions-and-safety) @@ -1537,27 +1558,6 @@ dbQueue.inTransaction(.exclusive) { db in ... } ``` -## Custom Value Types - -Conversion to and from the database is based on the `DatabaseValueConvertible` protocol: - -```swift -protocol DatabaseValueConvertible { - /// Returns a value that can be stored in the database. - var databaseValue: DatabaseValue { get } - - /// Returns a value initialized from dbValue, if possible. - static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? -} -``` - -All types that adopt this protocol can be used like all other [values](#values) (Bool, Int, String, Date, Swift enums, etc.) - -The `databaseValue` property returns [DatabaseValue](#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail. - -The `fromDatabaseValue()` factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly). - - ## Prepared Statements **Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments. From 6037c418cb9e91cff71039bf14f3ebea3c52c377 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 12:52:51 +0200 Subject: [PATCH 271/348] New "Customized Decoding of Database Rows" documentation chapter --- CHANGELOG.md | 17 +++++++++-------- .../Contents.swift | 16 ++++++++-------- README.md | 19 +++++++++++++++++++ 3 files changed, 36 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82c337c18..c23bf0cef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,14 +41,15 @@ It comes with new features, but also a few breaking changes, and a set of update ### Documentation Diff - [Associations](Documentation/AssociationsBasics.md): Discover the major GRDB 3 feature -- [Database Queues](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-queues): focus on the `read` and `write` methods. -- [Database Pools](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#database-pools): focus on the `read` and `write` methods. -- [Transactions and Savepoints](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. -- [ScopeAdapter](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#scopeadapter): do you use row adapters? If so, have a look. -- [Examples of Record Definitions](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). -- [SQL Operators](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. -- [Custom Requests](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. -- [Migrations](https://github.com/groue/GRDB.swift/blob/GRDB3/README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). +- [Database Queues](README.md#database-queues): focus on the `read` and `write` methods. +- [Database Pools](README.md#database-pools): focus on the `read` and `write` methods. +- [Transactions and Savepoints](README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. +- [ScopeAdapter](README.md#scopeadapter): do you use row adapters? If so, have a look. +- [Examples of Record Definitions](README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). +- [SQL Operators](README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. +- [Custom Requests](README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. +- [Customized Decoding of Database Rows](README.md#customized-decoding-of-database-rows): learn how to escape the ready-made `FetchableRecord` protocol when it does not fit your needs. +- [Migrations](README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests). diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index d1f6c7d76..9d02e4313 100644 --- a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -19,12 +19,12 @@ import GRDB //: //: For example: //: -//: - Your application needs polymorphic row decoding (which means decoding some -//: class or another depending on the values contained in a database row). +//: - Your application needs polymorphic row decoding: it decodes some class or +//: another, depending on the values contained in a database row. //: -//: - Your application needs to decode rows with a context - which means that -//: each decoded value should be initialized with some extra value that does not -//: come from the database. +//: - Your application needs to decode rows with a context: each decoded value +//: should be initialized with some extra value that does not come from +//: the database. //: //: - Your application needs a record type that supports untrusted databases, //: and may fail at decoding database rows (throw an error when a row contains @@ -391,9 +391,9 @@ try dbQueue.read { db in //: To end this tour, let's quickly look at two other possible customized //: row decoding strategies: //: -//: - Your application needs to decode rows with a context - which means that -//: each decoded value should be initialized with some extra value that does not -//: come from the database. +//: - Your application needs to decode rows with a context: each decoded value +//: should be initialized with some extra value that does not come from +//: the database. //: //: In this case, you may define a `ContextFetchableRecord` protocol, and //: derive all other fetching methods from the most fundamental one, which diff --git a/README.md b/README.md index 3d6f7c1a3..5a2ed9396 100644 --- a/README.md +++ b/README.md @@ -2033,6 +2033,7 @@ Your custom structs and classes can adopt each protocol individually, and opt in - [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) +- [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) **Records in a Glance** @@ -2143,6 +2144,7 @@ Details follow: - [Record Comparison] - [Conflict Resolution](#conflict-resolution) - [The Implicit RowID Primary Key](#the-implicit-rowid-primary-key) +- [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) - [Examples of Record Definitions](#examples-of-record-definitions) - [List of Record Methods](#list-of-record-methods) @@ -2278,6 +2280,8 @@ try Place.fetchOne(db, "SELECT ...", arguments:...) // Place? See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/Structs/StatementArguments.html) for more information about the query arguments. +> :point_up: **Note**: The `FetchableRecord.init(row:)` initializer fits the needs of most applications. But some application are more demanding than others. When FetchableRecord does not exactly provide the support you need, have a look at the [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) chapter. + ## TableRecord Protocol @@ -2928,6 +2932,21 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu ``` +## Customized Decoding of Database Rows + +**Some GRDB users eventually discover that the [FetchableRecord] protocol does not fit all situations.** Use cases that are not well handled by FetchableRecord include: + +- Your application needs polymorphic row decoding: it decodes some class or another, depending on the values contained in a database row. + +- Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database. + +- Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values). + +Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework. + +Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. + + ## Examples of Record Definitions We will show below how to declare a record type for the following database table: From 4f5fdf45e865fc4e790bd26bf0ac2f950517b909 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 13:27:24 +0200 Subject: [PATCH 272/348] More reasons not to fear leaving FetchableRecord --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5a2ed9396..0207ec9a1 100644 --- a/README.md +++ b/README.md @@ -2944,7 +2944,7 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](#fu Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework. -Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. +Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols. ## Examples of Record Definitions From 3017668ba2b3af80fbc64348b6ead9604be4ab86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 13:58:57 +0200 Subject: [PATCH 273/348] Fix typo --- .../CustomizedDecodingOfDatabaseRows.playground/Contents.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index 9d02e4313..7ab00a62f 100644 --- a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -200,7 +200,7 @@ extension Base: MyDatabaseDecoder { //: Now let's see how we can define a new realm of requests based on the //: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as -//: raedy-made requests of rows, values and FetchableRecord. +//: ready-made requests of rows, values and FetchableRecord. //: //: All we need is a set of *extensions* that define the classic GRDB fetching //: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one From 88c4f02f5db0c5bf3626dd4e52208daff5539e27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 18:04:55 +0200 Subject: [PATCH 274/348] Fix typo --- .../CustomizedDecodingOfDatabaseRows.playground/Contents.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index 7ab00a62f..ea4f540bd 100644 --- a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -178,7 +178,7 @@ try dbQueue.read { db in //: //: In the rest of this playground, we will define a **new realm of requests**. //: -//: GRDB ships with three build-in realms of requests: requests of raw rows, +//: GRDB ships with three built-in realms of requests: requests of raw rows, //: requests of values, and requests of record types that adopt the //: `FetchableRecord` protocol. //: From 2a1c87f24a90e9bf57d2b364905bfcdbde0c66ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 19 May 2018 18:45:13 +0200 Subject: [PATCH 275/348] Link to "Customized Decoding of Database Rows" from the "Custom Requests" chapter --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0207ec9a1..d59c2a933 100644 --- a/README.md +++ b/README.md @@ -4224,7 +4224,7 @@ try request.fetchAll(db) // [Player] See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll` and `fetchOne` methods. -When the RowDecoder type associated with the FetchRequest is not Row, DatabaseValueConvertible, or FetchableRecord, you can write your own convenience methods in an extension of the FetchRequest protocol. +The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) chapter for more information. Application Tools From 55472c2d7f1b533eadc7c9784396f37eda7c6ade Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sat, 19 May 2018 18:52:35 +0200 Subject: [PATCH 276/348] Main framework compiles on Linux --- GRDB/Core/Database.swift | 8 +++++++- GRDB/Core/StatementAuthorizer.swift | 3 +++ GRDB/Core/Support/CoreGraphics/CGFloat.swift | 2 ++ GRDB/Core/Support/Foundation/Date.swift | 2 ++ GRDB/Core/Support/Foundation/NSData.swift | 2 ++ GRDB/Core/Support/Foundation/NSNumber.swift | 2 ++ GRDB/Core/Support/Foundation/NSString.swift | 2 ++ GRDB/Core/Support/Foundation/URL.swift | 2 ++ GRDB/Core/Support/Foundation/UUID.swift | 6 ++++-- 9 files changed, 26 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index cdde29f8b..71fd0f761 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -304,7 +304,7 @@ extension Database { let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() db.configuration.trace!(sql) }, dbPointer) - #else + #elseif !os(Linux) if #available(iOS 10.0, OSX 10.12, watchOS 3.0, *) { sqlite3_trace_v2(sqliteConnection, UInt32(SQLITE_TRACE_STMT), { (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in guard let stmt = stmt else { return SQLITE_OK } @@ -322,6 +322,12 @@ extension Database { db.configuration.trace!(sql) }, dbPointer) } + #else + sqlite3_trace(sqliteConnection, { (dbPointer, sql) in + guard let sql = sql.map({ String(cString: $0) }) else { return } + let db = Unmanaged.fromOpaque(dbPointer!).takeUnretainedValue() + db.configuration.trace!(sql) + }, dbPointer) #endif } diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index 080820908..7a2750e43 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,3 +1,6 @@ +#if os(Linux) + import Glibc +#endif #if SWIFT_PACKAGE import CSQLite #elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER diff --git a/GRDB/Core/Support/CoreGraphics/CGFloat.swift b/GRDB/Core/Support/CoreGraphics/CGFloat.swift index 7359eb3fd..0b7fb1f3c 100644 --- a/GRDB/Core/Support/CoreGraphics/CGFloat.swift +++ b/GRDB/Core/Support/CoreGraphics/CGFloat.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import CoreGraphics /// CGFloat adopts DatabaseValueConvertible @@ -16,3 +17,4 @@ extension CGFloat : DatabaseValueConvertible { return CGFloat(double) } } +#endif diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index 78cdbbd30..c5e1e1d6b 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -5,6 +5,7 @@ import Foundation import SQLite3 #endif +#if !os(Linux) /// NSDate is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. extension NSDate : DatabaseValueConvertible { @@ -31,6 +32,7 @@ extension NSDate : DatabaseValueConvertible { return cast(date) } } +#endif /// Date is stored in the database using the format /// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone. diff --git a/GRDB/Core/Support/Foundation/NSData.swift b/GRDB/Core/Support/Foundation/NSData.swift index 28a7ae8ba..8bd9d2ecf 100644 --- a/GRDB/Core/Support/Foundation/NSData.swift +++ b/GRDB/Core/Support/Foundation/NSData.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation /// NSData is convertible to and from DatabaseValue. @@ -17,3 +18,4 @@ extension NSData : DatabaseValueConvertible { return cast(data) } } +#endif diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 2a00c1618..2caf60868 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation private let integerRoundingBehavior = NSDecimalNumberHandler(roundingMode: .plain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) @@ -65,3 +66,4 @@ extension NSNumber : DatabaseValueConvertible { } } } +#endif diff --git a/GRDB/Core/Support/Foundation/NSString.swift b/GRDB/Core/Support/Foundation/NSString.swift index 577725992..d5455bed4 100644 --- a/GRDB/Core/Support/Foundation/NSString.swift +++ b/GRDB/Core/Support/Foundation/NSString.swift @@ -1,3 +1,4 @@ +#if !os(Linux) import Foundation /// NSString adopts DatabaseValueConvertible @@ -16,3 +17,4 @@ extension NSString : DatabaseValueConvertible { return self.init(string: string) } } +#endif diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index 516dcc1fb..4cc95b1b4 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -1,5 +1,6 @@ import Foundation +#if !os(Linux) /// NSURL stores its absoluteString in the database. extension NSURL : DatabaseValueConvertible { @@ -17,6 +18,7 @@ extension NSURL : DatabaseValueConvertible { return cast(URL(string: string)) } } +#endif /// URL stores its absoluteString in the database. extension URL : DatabaseValueConvertible { } diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 5d6d7cfee..78a9062dd 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,5 +1,6 @@ import Foundation +#if !os(Linux) /// NSUUID adopts DatabaseValueConvertible extension NSUUID : DatabaseValueConvertible { @@ -8,18 +9,19 @@ extension NSUUID : DatabaseValueConvertible { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in getBytes(buffer.baseAddress!) - return NSData(bytes: buffer.baseAddress, length: 16).databaseValue + return Data(bytes: buffer.baseAddress, length: 16).databaseValue } } /// Returns an NSUUID initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else { + guard let data = Data.fromDatabaseValue(dbValue), data.length == 16 else { return nil } return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self)) } } +#endif /// UUID adopts DatabaseValueConvertible extension UUID : DatabaseValueConvertible { } From df8887be050cfcc7492ae753b22c957548dfb386 Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sun, 20 May 2018 00:27:02 +0200 Subject: [PATCH 277/348] Fix NSUUID compilation issue (now using more Swift code) --- GRDB/Core/Support/Foundation/UUID.swift | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 78a9062dd..15dd51e6f 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -9,16 +9,18 @@ extension NSUUID : DatabaseValueConvertible { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in getBytes(buffer.baseAddress!) - return Data(bytes: buffer.baseAddress, length: 16).databaseValue + return Data(buffer: buffer).databaseValue } } /// Returns an NSUUID initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - guard let data = Data.fromDatabaseValue(dbValue), data.length == 16 else { + guard let data = Data.fromDatabaseValue(dbValue), data.count == 16 else { return nil } - return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self)) + return data.withUnsafeBytes { buffer in + self.init(uuidBytes: buffer) + } } } #endif From 34db8efea0546983b51d941e78131c903449a840 Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sun, 20 May 2018 00:44:59 +0200 Subject: [PATCH 278/348] Added missing LinuxMain.swift --- Tests/LinuxMain.swift | 160 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 Tests/LinuxMain.swift diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift new file mode 100644 index 000000000..833229ec6 --- /dev/null +++ b/Tests/LinuxMain.swift @@ -0,0 +1,160 @@ +import Foundation +@testable import GRDBTests + +XCTMain([ + testCase(AnyCursorTests.allTests), + testCase(AssociationBelongsToDecodableRecordTests.allTests), + testCase(AssociationBelongsToFetchableRecordTests.allTests), + testCase(AssociationBelongsToRowScopeTests.allTests), + testCase(AssociationBelongsToSQLDerivationTests.allTests), + testCase(AssociationBelongsToSQLTests.allTests), + testCase(AssociationChainRowScopesTests.allTests), + testCase(AssociationChainSQLTests.allTests), + testCase(AssociationHasOneSQLDerivationTests.allTests), + testCase(AssociationHasOneSQLTests.allTests), + testCase(AssociationParallelDecodableRecordTests.allTests), + testCase(AssociationParallelRowScopesTests.allTests), + testCase(AssociationParallelSQLTests.allTests), + testCase(AssociationRowScopeSearchTests.allTests), + testCase(AssociationTableAliasTestsSQLTests.allTests), + testCase(CGFloatTests.allTests), + testCase(ColumnExpressionTests.allTests), + testCase(ColumnInfoTests.allTests), + testCase(CompilationProtocolTests.allTests), + testCase(CompilationSubClassTests.allTests), + testCase(CursorTests.allTests), + testCase(DataMemoryTests.allTests), + testCase(DatabaseAfterNextTransactionCommitTests.allTests), + testCase(DatabaseAggregateTests.allTests), + testCase(DatabaseCollationTests.allTests), + testCase(DatabaseCursorTests.allTests), + testCase(DatabaseErrorTests.allTests), + testCase(DatabaseFunctionTests.allTests), + testCase(DatabaseLogErrorTests.allTests), + testCase(DatabaseMigratorTests.allTests), + testCase(DatabasePoolBackupTests.allTests), + testCase(DatabasePoolCollationTests.allTests), + testCase(DatabasePoolConcurrencyTests.allTests), + testCase(DatabasePoolFunctionTests.allTests), + testCase(DatabasePoolReadOnlyTests.allTests), + testCase(DatabasePoolReleaseMemoryTests.allTests), + testCase(DatabasePoolSchemaCacheTests.allTests), + testCase(DatabaseQueueBackupTests.allTests), + testCase(DatabaseQueueConcurrencyTests.allTests), + testCase(DatabaseQueueInMemoryTests.allTests), + testCase(DatabaseQueueReadOnlyTests.allTests), + testCase(DatabaseQueueReleaseMemoryTests.allTests), + testCase(DatabaseQueueSchemaCacheTests.allTests), + testCase(DatabaseQueueTests.allTests), + testCase(DatabaseReaderTests.allTests), + testCase(DatabaseRegionTests.allTests), + testCase(DatabaseSavepointTests.allTests), + testCase(DatabaseSnapshotTests.allTests), + testCase(DatabaseTests.allTests), + testCase(DatabaseTimestampTests.allTests), + testCase(DatabaseValueConversionTests.allTests), + testCase(DatabaseValueConvertibleDecodableTests.allTests), + testCase(DatabaseValueConvertibleEncodableTests.allTests), + testCase(DatabaseValueConvertibleEscapingTests.allTests), + testCase(DatabaseValueConvertibleFetchTests.allTests), + testCase(DatabaseValueConvertibleSubclassTests.allTests), + testCase(DatabaseValueTests.allTests), + testCase(DatabaseWriterTests.allTests), + testCase(DerivableRequestTests.allTests), + testCase(DropFirstCursorTests.allTests), + testCase(DropWhileCursorTests.allTests), + testCase(EncryptionTests.allTests), + testCase(EnumeratedCursorTests.allTests), + testCase(FTS3PatternTests.allTests), + testCase(FTS3RecordTests.allTests), + testCase(FTS3TableBuilderTests.allTests), + testCase(FTS3TokenizerTests.allTests), + testCase(FTS4RecordTests.allTests), + testCase(FTS4TableBuilderTests.allTests), + testCase(FTS5CustomTokenizerTests.allTests), + testCase(FTS5PatternTests.allTests), + testCase(FTS5RecordTests.allTests), + testCase(FTS5TableBuilderTests.allTests), + testCase(FTS5TokenizerTests.allTests), + testCase(FTS5WrapperTokenizerTests.allTests), + testCase(FetchRequestTests.allTests), + testCase(FetchableRecord+QueryInterfaceRequestTests.allTests), + testCase(FetchableRecordDecodableTests.allTests), + testCase(FetchableRecordTests.allTests), + testCase(FetchedRecordsControllerTests.allTests), + testCase(FilterCursorTests.allTests), + testCase(FlattenCursorTests.allTests), + testCase(ForeignKeyInfoTests.allTests), + testCase(FoundationDataTests.allTests), + testCase(FoundationDateComponentsTests.allTests), + testCase(FoundationDateTests.allTests), + testCase(FoundationNSDataTests.allTests), + testCase(FoundationNSDateTests.allTests), + testCase(FoundationNSDecimalNumberTests.allTests), + testCase(FoundationNSNullTests.allTests), + testCase(FoundationNSNumberTests.allTests), + testCase(FoundationNSStringTests.allTests), + testCase(FoundationNSURLTests.allTests), + testCase(FoundationNSUUIDTests.allTests), + testCase(FoundationURLTests.allTests), + testCase(FoundationUUIDTests.allTests), + testCase(GRDBTestCase.allTests), + testCase(IndexInfoTests.allTests), + testCase(JoinSupportTests.allTests), + testCase(MapCursorTests.allTests), + testCase(MutablePersistableRecordChangesTests.allTests), + testCase(MutablePersistableRecordDeleteTests.allTests), + testCase(MutablePersistableRecordEncodableTests.allTests), + testCase(MutablePersistableRecordPersistenceConflictPolicyTests.allTests), + testCase(MutablePersistableRecordTests.allTests), + testCase(NumericOverflowTests.allTests), + testCase(PersistableRecordTests.allTests), + testCase(PrefixCursorTests.allTests), + testCase(PrefixWhileCursorTests.allTests), + testCase(PrimaryKeyInfoTests.allTests), + testCase(QueryInterfaceExpressionsTests.allTests), + testCase(QueryInterfaceExtensibilityTests.allTests), + testCase(QueryInterfaceRequestTests.allTests), + testCase(RawRepresentable+DatabaseValueConvertibleTests.allTests), + testCase(Record+QueryInterfaceRequestTests.allTests), + testCase(RecordCopyTests.allTests), + testCase(RecordEditedTests.allTests), + testCase(RecordInitializersTests.allTests), + testCase(RecordMinimalPrimaryKeyRowIDTests.allTests), + testCase(RecordMinimalPrimaryKeySingleTests.allTests), + testCase(RecordPersistenceConflictPolicy.allTests), + testCase(RecordPrimaryKeyHiddenRowIDTests.allTests), + testCase(RecordPrimaryKeyMultipleTests.allTests), + testCase(RecordPrimaryKeyNoneTests.allTests), + testCase(RecordPrimaryKeyRowIDTests.allTests), + testCase(RecordPrimaryKeySingleTests.allTests), + testCase(RecordPrimaryKeySingleWithReplaceConflictResolutionTests.allTests), + testCase(RecordSubClassTests.allTests), + testCase(RecordUniqueIndexTests.allTests), + testCase(RecordWithColumnNameManglingTests.allTests), + testCase(ResultCodeTests.allTests), + testCase(Row+FoundationTests.allTests), + testCase(RowAdapterTests.allTests), + testCase(RowCopiedFromStatementTests.allTests), + testCase(RowFetchTests.allTests), + testCase(RowFromDictionaryLiteralTests.allTests), + testCase(RowFromDictionaryTests.allTests), + testCase(RowFromStatementTests.allTests), + testCase(RowTestCase.allTests), + testCase(SQLExpressionLiteralTests.allTests), + testCase(SQLRequestTests.allTests), + testCase(SchedulingWatchdogTests.allTests), + testCase(SelectStatementTests.allTests), + testCase(StatementArguments+FoundationTests.allTests), + testCase(StatementArgumentsTests.allTests), + testCase(StatementColumnConvertibleFetchTests.allTests), + testCase(StatementColumnConvertibleTests.allTests), + testCase(TableDefinitionTests.allTests), + testCase(TableRecord+QueryInterfaceRequestTests.allTests), + testCase(TableRecordTests.allTests), + testCase(TransactionObserverSavepointsTests.allTests), + testCase(TransactionObserverTests.allTests), + testCase(TruncateOptimizationTests.allTests), + testCase(UpdateStatementTests.allTests), + testCase(VirtualTableModuleTests.allTests) +]) From da65deec695bec9a0ae00df15bfc5fa879671006 Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sun, 20 May 2018 14:21:41 +0200 Subject: [PATCH 279/348] Removed LinuxMain.swift --- Tests/LinuxMain.swift | 160 ------------------------------------------ 1 file changed, 160 deletions(-) delete mode 100644 Tests/LinuxMain.swift diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift deleted file mode 100644 index 833229ec6..000000000 --- a/Tests/LinuxMain.swift +++ /dev/null @@ -1,160 +0,0 @@ -import Foundation -@testable import GRDBTests - -XCTMain([ - testCase(AnyCursorTests.allTests), - testCase(AssociationBelongsToDecodableRecordTests.allTests), - testCase(AssociationBelongsToFetchableRecordTests.allTests), - testCase(AssociationBelongsToRowScopeTests.allTests), - testCase(AssociationBelongsToSQLDerivationTests.allTests), - testCase(AssociationBelongsToSQLTests.allTests), - testCase(AssociationChainRowScopesTests.allTests), - testCase(AssociationChainSQLTests.allTests), - testCase(AssociationHasOneSQLDerivationTests.allTests), - testCase(AssociationHasOneSQLTests.allTests), - testCase(AssociationParallelDecodableRecordTests.allTests), - testCase(AssociationParallelRowScopesTests.allTests), - testCase(AssociationParallelSQLTests.allTests), - testCase(AssociationRowScopeSearchTests.allTests), - testCase(AssociationTableAliasTestsSQLTests.allTests), - testCase(CGFloatTests.allTests), - testCase(ColumnExpressionTests.allTests), - testCase(ColumnInfoTests.allTests), - testCase(CompilationProtocolTests.allTests), - testCase(CompilationSubClassTests.allTests), - testCase(CursorTests.allTests), - testCase(DataMemoryTests.allTests), - testCase(DatabaseAfterNextTransactionCommitTests.allTests), - testCase(DatabaseAggregateTests.allTests), - testCase(DatabaseCollationTests.allTests), - testCase(DatabaseCursorTests.allTests), - testCase(DatabaseErrorTests.allTests), - testCase(DatabaseFunctionTests.allTests), - testCase(DatabaseLogErrorTests.allTests), - testCase(DatabaseMigratorTests.allTests), - testCase(DatabasePoolBackupTests.allTests), - testCase(DatabasePoolCollationTests.allTests), - testCase(DatabasePoolConcurrencyTests.allTests), - testCase(DatabasePoolFunctionTests.allTests), - testCase(DatabasePoolReadOnlyTests.allTests), - testCase(DatabasePoolReleaseMemoryTests.allTests), - testCase(DatabasePoolSchemaCacheTests.allTests), - testCase(DatabaseQueueBackupTests.allTests), - testCase(DatabaseQueueConcurrencyTests.allTests), - testCase(DatabaseQueueInMemoryTests.allTests), - testCase(DatabaseQueueReadOnlyTests.allTests), - testCase(DatabaseQueueReleaseMemoryTests.allTests), - testCase(DatabaseQueueSchemaCacheTests.allTests), - testCase(DatabaseQueueTests.allTests), - testCase(DatabaseReaderTests.allTests), - testCase(DatabaseRegionTests.allTests), - testCase(DatabaseSavepointTests.allTests), - testCase(DatabaseSnapshotTests.allTests), - testCase(DatabaseTests.allTests), - testCase(DatabaseTimestampTests.allTests), - testCase(DatabaseValueConversionTests.allTests), - testCase(DatabaseValueConvertibleDecodableTests.allTests), - testCase(DatabaseValueConvertibleEncodableTests.allTests), - testCase(DatabaseValueConvertibleEscapingTests.allTests), - testCase(DatabaseValueConvertibleFetchTests.allTests), - testCase(DatabaseValueConvertibleSubclassTests.allTests), - testCase(DatabaseValueTests.allTests), - testCase(DatabaseWriterTests.allTests), - testCase(DerivableRequestTests.allTests), - testCase(DropFirstCursorTests.allTests), - testCase(DropWhileCursorTests.allTests), - testCase(EncryptionTests.allTests), - testCase(EnumeratedCursorTests.allTests), - testCase(FTS3PatternTests.allTests), - testCase(FTS3RecordTests.allTests), - testCase(FTS3TableBuilderTests.allTests), - testCase(FTS3TokenizerTests.allTests), - testCase(FTS4RecordTests.allTests), - testCase(FTS4TableBuilderTests.allTests), - testCase(FTS5CustomTokenizerTests.allTests), - testCase(FTS5PatternTests.allTests), - testCase(FTS5RecordTests.allTests), - testCase(FTS5TableBuilderTests.allTests), - testCase(FTS5TokenizerTests.allTests), - testCase(FTS5WrapperTokenizerTests.allTests), - testCase(FetchRequestTests.allTests), - testCase(FetchableRecord+QueryInterfaceRequestTests.allTests), - testCase(FetchableRecordDecodableTests.allTests), - testCase(FetchableRecordTests.allTests), - testCase(FetchedRecordsControllerTests.allTests), - testCase(FilterCursorTests.allTests), - testCase(FlattenCursorTests.allTests), - testCase(ForeignKeyInfoTests.allTests), - testCase(FoundationDataTests.allTests), - testCase(FoundationDateComponentsTests.allTests), - testCase(FoundationDateTests.allTests), - testCase(FoundationNSDataTests.allTests), - testCase(FoundationNSDateTests.allTests), - testCase(FoundationNSDecimalNumberTests.allTests), - testCase(FoundationNSNullTests.allTests), - testCase(FoundationNSNumberTests.allTests), - testCase(FoundationNSStringTests.allTests), - testCase(FoundationNSURLTests.allTests), - testCase(FoundationNSUUIDTests.allTests), - testCase(FoundationURLTests.allTests), - testCase(FoundationUUIDTests.allTests), - testCase(GRDBTestCase.allTests), - testCase(IndexInfoTests.allTests), - testCase(JoinSupportTests.allTests), - testCase(MapCursorTests.allTests), - testCase(MutablePersistableRecordChangesTests.allTests), - testCase(MutablePersistableRecordDeleteTests.allTests), - testCase(MutablePersistableRecordEncodableTests.allTests), - testCase(MutablePersistableRecordPersistenceConflictPolicyTests.allTests), - testCase(MutablePersistableRecordTests.allTests), - testCase(NumericOverflowTests.allTests), - testCase(PersistableRecordTests.allTests), - testCase(PrefixCursorTests.allTests), - testCase(PrefixWhileCursorTests.allTests), - testCase(PrimaryKeyInfoTests.allTests), - testCase(QueryInterfaceExpressionsTests.allTests), - testCase(QueryInterfaceExtensibilityTests.allTests), - testCase(QueryInterfaceRequestTests.allTests), - testCase(RawRepresentable+DatabaseValueConvertibleTests.allTests), - testCase(Record+QueryInterfaceRequestTests.allTests), - testCase(RecordCopyTests.allTests), - testCase(RecordEditedTests.allTests), - testCase(RecordInitializersTests.allTests), - testCase(RecordMinimalPrimaryKeyRowIDTests.allTests), - testCase(RecordMinimalPrimaryKeySingleTests.allTests), - testCase(RecordPersistenceConflictPolicy.allTests), - testCase(RecordPrimaryKeyHiddenRowIDTests.allTests), - testCase(RecordPrimaryKeyMultipleTests.allTests), - testCase(RecordPrimaryKeyNoneTests.allTests), - testCase(RecordPrimaryKeyRowIDTests.allTests), - testCase(RecordPrimaryKeySingleTests.allTests), - testCase(RecordPrimaryKeySingleWithReplaceConflictResolutionTests.allTests), - testCase(RecordSubClassTests.allTests), - testCase(RecordUniqueIndexTests.allTests), - testCase(RecordWithColumnNameManglingTests.allTests), - testCase(ResultCodeTests.allTests), - testCase(Row+FoundationTests.allTests), - testCase(RowAdapterTests.allTests), - testCase(RowCopiedFromStatementTests.allTests), - testCase(RowFetchTests.allTests), - testCase(RowFromDictionaryLiteralTests.allTests), - testCase(RowFromDictionaryTests.allTests), - testCase(RowFromStatementTests.allTests), - testCase(RowTestCase.allTests), - testCase(SQLExpressionLiteralTests.allTests), - testCase(SQLRequestTests.allTests), - testCase(SchedulingWatchdogTests.allTests), - testCase(SelectStatementTests.allTests), - testCase(StatementArguments+FoundationTests.allTests), - testCase(StatementArgumentsTests.allTests), - testCase(StatementColumnConvertibleFetchTests.allTests), - testCase(StatementColumnConvertibleTests.allTests), - testCase(TableDefinitionTests.allTests), - testCase(TableRecord+QueryInterfaceRequestTests.allTests), - testCase(TableRecordTests.allTests), - testCase(TransactionObserverSavepointsTests.allTests), - testCase(TransactionObserverTests.allTests), - testCase(TruncateOptimizationTests.allTests), - testCase(UpdateStatementTests.allTests), - testCase(VirtualTableModuleTests.allTests) -]) From c0bd8ce9177aa4aa4d7d13eb2e51ad5bed131f95 Mon Sep 17 00:00:00 2001 From: Florent Pillet Date: Sun, 20 May 2018 14:37:59 +0200 Subject: [PATCH 280/348] Rolled back to previous NSUUID extension as compiler freaks out on a more modern implementation --- GRDB/Core/Support/Foundation/UUID.swift | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 15dd51e6f..7deb4e2cf 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -9,19 +9,17 @@ extension NSUUID : DatabaseValueConvertible { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in getBytes(buffer.baseAddress!) - return Data(buffer: buffer).databaseValue + return NSData(bytes: buffer.baseAddress, length: 16).databaseValue } } /// Returns an NSUUID initialized from *dbValue*, if possible. public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? { - guard let data = Data.fromDatabaseValue(dbValue), data.count == 16 else { + guard let data = NSData.fromDatabaseValue(dbValue), data.length == 16 else { return nil } - return data.withUnsafeBytes { buffer in - self.init(uuidBytes: buffer) - } - } + return self.init(uuidBytes: data.bytes.assumingMemoryBound(to: UInt8.self)) + } } #endif From 67e48f8ad7f85eab20daa849e09d0fdf2928b1fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 15:45:59 +0200 Subject: [PATCH 281/348] CustomizedDecodingOfDatabaseRows --- .../Contents.swift | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift index ea4f540bd..2b1a387ba 100644 --- a/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift +++ b/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift @@ -129,7 +129,7 @@ extension Base { //: few extensions that guarantee the most efficient use of GRDB, and have the //: Base class adopt this protocol. //: -//: ## Keep It Simple, Stupid! +//: ### Keep It Simple, Stupid! //: //: But first, let's see how polymorphic decoding can be done as simply as //: possible. After all, it is useless to design a full-fledged protocol unless @@ -174,7 +174,7 @@ try dbQueue.read { db in //: The resulting code is not as streamlined as usual GRDB code, but we could //: already do what we needed without much effort. //: -//: ## Custom Protocol: MyDatabaseDecoder +//: ### Custom Protocol: MyDatabaseDecoder //: //: In the rest of this playground, we will define a **new realm of requests**. //: @@ -389,15 +389,18 @@ try dbQueue.read { db in //: customization freedom. //: //: To end this tour, let's quickly look at two other possible customized -//: row decoding strategies: +//: row decoding strategies. //: -//: - Your application needs to decode rows with a context: each decoded value +//: ## An Example: Contextualized Records +//: +//: Your application needs to decode rows with a context: each decoded value //: should be initialized with some extra value that does not come from //: the database. //: -//: In this case, you may define a `ContextFetchableRecord` protocol, and -//: derive all other fetching methods from the most fundamental one, which -//: fetches a cursor from a prepared statement (as above): +//: In this case, you may define a `ContextFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as we did for the +//: MyDatabaseDecoder protocol, above): protocol ContextFetchableRecord { associatedtype Context @@ -418,16 +421,19 @@ extension ContextFetchableRecord { } } - // Define fetchAll, fetchOne, ... + // Define fetchAll, fetchOne, and other extensions... } -//: - Your application needs a record type that supports untrusted databases, +//: ## An Example: Failable Records +//: +//: Your application needs a record type that supports untrusted databases, //: and may fail at decoding database rows (throw an error when a row contains //: invalid values). //: -//: In this case, you may define a `FailableFetchableRecord` protocol, and -//: derive all other fetching methods from the most fundamental one, which -//: fetches a cursor from a prepared statement (as above): +//: In this case, you may define a `FailableFetchableRecord` protocol, and +//: derive all other fetching methods from the most fundamental one, which +//: fetches a cursor from a prepared statement (as we did for the +//: MyDatabaseDecoder protocol, above): protocol FailableFetchableRecord { init(row: Row) throws @@ -446,6 +452,5 @@ extension FailableFetchableRecord { } } - // Define fetchAll, fetchOne, ... + // Define fetchAll, fetchOne, and other extensions... } - From 7be345521bbd9a40cd2bee321bea1fa31fbddadd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 16:14:23 +0200 Subject: [PATCH 282/348] Associations: new "DerivableRequest Protocol" documentation chapter --- Documentation/AssociationsBasics.md | 39 ++++++++++++- Tests/GRDBTests/DerivableRequestTests.swift | 64 ++++++++++++++++++--- 2 files changed, 93 insertions(+), 10 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 18c4c0c0a..c21aa4a0f 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -26,6 +26,7 @@ GRDB Associations - [The Structure of a Joined Request] - [Decoding a Joined Request with a Decodable Record] - [Decoding a Joined Request with FetchableRecord] +- [DerivableRequest Protocol] - [Known Issues] - [Future Directions] @@ -1245,6 +1246,41 @@ let country: Country? = row["country"] You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information. +## DerivableRequest Protocol + +The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis. + +For example: + +```swift +extension DerivableRequest where RowDecoder == Author { + func filter(country: String) -> Self { + return filter(Column("country") == country) + } + + func orderByFullName() -> Self { + return order( + Column("lastName").collating(.localizedCaseInsensitiveCompare), + Column("firstName").collating(.localizedCaseInsensitiveCompare)) + } +} +``` + +Thanks to DerivableRequest, both the `filter(country:)` and `orderByFullName()` methods are now available for both Author-based requests and associations: + +```swift +// French authors sorted by full name: +let request = Author.all() + .filter(country: "FR") + .orderByFullName() + +// French books, sorted by full name of author: +let request = Book.joining(required: Book.author + .filter(country: "FR") + .orderByFullName()) +``` + + ## Known Issues **You can't chain a required association on an optional association:** @@ -1373,4 +1409,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Custom Requests]: ../README.md#custom-requests [Known Issues]: #known-issues [Future Directions]: #future-directions -[Row Adapters]: ../README.md#row-adapters \ No newline at end of file +[Row Adapters]: ../README.md#row-adapters +[query interface requests]: ../README.md#requests \ No newline at end of file diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index bc5a9381a..1286ecffb 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -9,8 +9,14 @@ import GRDB private struct Author: FetchableRecord, PersistableRecord, Codable { var id: Int64 - var name: String + var firstName: String? + var lastName: String? var country: String + var fullName: String { + return [firstName, lastName] + .compactMap { $0 } + .joined(separator: " ") + } static let databaseTableName = "author" static let books = hasMany(Book.self) @@ -35,7 +41,8 @@ private var libraryMigrator: DatabaseMigrator = { migrator.registerMigration("library") { db in try db.create(table: "author") { t in t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() + t.column("firstName", .text) + t.column("lastName", .text) t.column("country", .text).notNull() } try db.create(table: "book") { t in @@ -45,11 +52,10 @@ private var libraryMigrator: DatabaseMigrator = { } } migrator.registerMigration("fixture") { db in - try Author(id: 1, name: "Melville", country: "US").insert(db) - try Author(id: 2, name: "Proust", country: "FR").insert(db) + try Author(id: 1, firstName: "Herman", lastName: "Melville", country: "US").insert(db) + try Author(id: 2, firstName: "Marcel", lastName: "Proust", country: "FR").insert(db) try Book(id: 1, authorId: 1, title: "Moby-Dick").insert(db) try Book(id: 2, authorId: 2, title: "Du côté de chez Swann").insert(db) - try Book(id: 3, authorId: 2, title: "Le Côté de Guermantes").insert(db) } return migrator }() @@ -59,10 +65,16 @@ extension DerivableRequest where RowDecoder == Author { func filter(country: String) -> Self { return filter(Column("country") == country) } + + func orderByFullName() -> Self { + return order( + Column("lastName").collating(.localizedCaseInsensitiveCompare), + Column("firstName").collating(.localizedCaseInsensitiveCompare)) + } } class DerivableRequestTests: GRDBTestCase { - func testDerivation() throws { + func testFilter() throws { let dbQueue = try makeDatabaseQueue() try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in @@ -70,8 +82,8 @@ class DerivableRequestTests: GRDBTestCase { let frenchAuthorNames = try Author.all() .filter(country: "FR") .fetchAll(db) - .map { $0.name } - XCTAssertEqual(frenchAuthorNames, ["Proust"]) + .map { $0.fullName } + XCTAssertEqual(frenchAuthorNames, ["Marcel Proust"]) // ... for two requests (2) let frenchBookTitles = try Book @@ -79,7 +91,41 @@ class DerivableRequestTests: GRDBTestCase { .order(Column("title")) .fetchAll(db) .map { $0.title } - XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann", "Le Côté de Guermantes"]) + XCTAssertEqual(frenchBookTitles, ["Du côté de chez Swann"]) + } + } + + func testOrder() throws { + let dbQueue = try makeDatabaseQueue() + try libraryMigrator.migrate(dbQueue) + try dbQueue.inDatabase { db in + // ... for two requests (1) + let authorNames = try Author.all() + .orderByFullName() + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(authorNames, ["Herman Melville", "Marcel Proust"]) + + let reversedAuthorNames = try Author.all() + .orderByFullName() + .reversed() + .fetchAll(db) + .map { $0.fullName } + XCTAssertEqual(reversedAuthorNames, ["Marcel Proust", "Herman Melville"]) + + // ... for two requests (2) + let bookTitles = try Book + .joining(required: Book.author.orderByFullName()) + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(bookTitles, ["Moby-Dick", "Du côté de chez Swann"]) + + let reversedBookTitles = try Book + .joining(required: Book.author.orderByFullName()) + .reversed() + .fetchAll(db) + .map { $0.title } + XCTAssertEqual(reversedBookTitles, ["Du côté de chez Swann", "Moby-Dick"]) } } } From 9be001533c73766d2fedcc436925d1c23b4aa0b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 16:16:02 +0200 Subject: [PATCH 283/348] Fix inner link --- Documentation/AssociationsBasics.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index c21aa4a0f..348990721 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1407,6 +1407,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Decoding a Hierarchical Decodable Record]: #decoding-a-hierarchical-decodable-record [Decoding a Joined Request with FetchableRecord]: #decoding-a-joined-request-with-fetchablerecord [Custom Requests]: ../README.md#custom-requests +[DerivableRequest Protocol]: #derivablerequest-protocol [Known Issues]: #known-issues [Future Directions]: #future-directions [Row Adapters]: ../README.md#row-adapters From aa81b992c416ec7df26bba2841c2ec2aa45e94fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 17:48:22 +0200 Subject: [PATCH 284/348] Associations: inline documentation --- Documentation/AssociationsBasics.md | 5 +- .../Association/BelongsToAssociation.swift | 57 ++++++++++++++++++- .../Association/HasManyAssociation.swift | 57 ++++++++++++++++++- .../Association/HasOneAssociation.swift | 57 ++++++++++++++++++- 4 files changed, 170 insertions(+), 6 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 348990721..1fab19016 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -101,7 +101,7 @@ let books = try author.books.fetchAll(db) As for loading all pairs of books and authors, it is not only easier, but also *far much efficient*: ```swift -struct BookInfo: FetchableRecord, Codable { +struct BookInfo: FetchableRecord, Decodable { let book: Book let author: Author? } @@ -295,7 +295,7 @@ struct Author: FetchableRecord, TableRecord { } // A pair made of a book and its author -struct BookInfo: FetchableRecord, Codable { +struct BookInfo: FetchableRecord, Decodable { let book: Book let author: Author? } @@ -1382,7 +1382,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone [Self Joins]: #self-joins [The Types of Associations]: #the-types-of-associations -[Codable]: https://developer.apple.com/documentation/swift/codable [FetchableRecord]: ../README.md#fetchablerecord-protocols [migration]: ../README.md#migrations [Record]: ../README.md#records diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index b2f7b111d..187ff9e9d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -37,7 +37,62 @@ extension BelongsToAssociation: TableRequest where Destination: TableRecord { } extension TableRecord { - /// TODO + /// Creates a "Belongs To" association between Self and the + /// destination type. + /// + /// struct Author: TableRecord { ... } + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all books with their authors: + /// let request = Book.including(optional: Book.author) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct BookInfo: FetchableRecord, Decodable { + /// var book: Book + /// var author: Author? + /// } + /// + /// let bookInfos = try dbQueue.read { db in + /// return try BookInfo.fetchAll(db, request) + /// } + /// for bookInfo in bookInfos { + /// print("\(bookInfo.book.title) by \(bookInfo.author.name)") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// var author: QueryInterfaceRequest { + /// return request(for: Book.author) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let book: Book = ... + /// let author = try book.author.fetchOne(db) // Author? + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key to the destination table, or when the schema defines several + /// foreign keys to the destination table. public static func belongsTo( _ destination: Destination.Type, key: String? = nil, diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 249593787..b430a5886 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -37,7 +37,62 @@ extension HasManyAssociation: TableRequest where Destination: TableRecord { } extension TableRecord { - /// TODO + /// Creates a "Has many" association between Self and the + /// destination type. + /// + /// struct Book: TableRecord { ... } + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all (author, book) pairs: + /// let request = Author.including(required: Author.books) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct Authorship: FetchableRecord, Decodable { + /// var author: Author + /// var book: Book + /// } + /// + /// let authorships = try dbQueue.read { db in + /// return try Authorship.fetchAll(db, request) + /// } + /// for authorship in authorships { + /// print("\(authorship.author.name) wrote \(authorship.book.title)") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Author: TableRecord { + /// static let books = hasMany(Book.self) + /// var books: QueryInterfaceRequest { + /// return request(for: Author.books) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let author: Author = ... + /// let books = try author.books.fetchAll(db) // [Book] + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. public static func hasMany( _ destination: Destination.Type, key: String? = nil, diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index b5ef7be12..e53b35d62 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -37,7 +37,62 @@ extension HasOneAssociation: TableRequest where Destination: TableRecord { } extension TableRecord { - /// TODO + /// Creates a "Has one" association between Self and the + /// destination type. + /// + /// struct Demographics: TableRecord { ... } + /// struct Country: TableRecord { + /// static let demographics = hasOne(Demographics.self) + /// } + /// + /// The association will let you define requests that load both the source + /// and the destination type: + /// + /// // A request for all countries with their demographic profile: + /// let request = Country.including(optional: Country.demographics) + /// + /// To consume those requests, define a type that adopts both the + /// FetchableRecord and Decodable protocols: + /// + /// struct CountryInfo: FetchableRecord, Decodable { + /// var country: Country + /// var demographics: Demographics? + /// } + /// + /// let countryInfos = try dbQueue.read { db in + /// return try CountryInfo.fetchAll(db, request) + /// } + /// for countryInfo in countryInfos { + /// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens") + /// } + /// + /// It is recommended that you define, alongside the association, a property + /// with the same name: + /// + /// struct Country: TableRecord { + /// static let demographics = hasOne(Demographics.self) + /// var demographics: QueryInterfaceRequest { + /// return request(for: Country.demographics) + /// } + /// } + /// + /// This property will let you navigate from the source type to the + /// destination type: + /// + /// try dbQueue.read { db in + /// let country: Country = ... + /// let demographics = try country.demographics.fetchOne(db) // Demographics? + /// } + /// + /// - parameters: + /// - destination: The record type at the other side of the association. + /// - key: An eventual decoding key for the association. By default, it + /// is `destination.databaseTableName`. + /// - foreignKey: An eventual foreign key. You need to provide an + /// explicit foreign key when GRDB can't infer one from the database + /// schema. This happens when the schema does not define any foreign + /// key from the destination table, or when the schema defines several + /// foreign keys from the destination table. public static func hasOne( _ destination: Destination.Type, key: String? = nil, From 02d5b9c01485cee139ae86d93ff6713751fd9829 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 18:13:34 +0200 Subject: [PATCH 285/348] Associations: inline documentation --- .../Association/BelongsToAssociation.swift | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index 187ff9e9d..bde6e005a 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -1,3 +1,63 @@ +/// The BelongsTo association sets up a one-to-one connection from a record +/// type to another record type, such as each instance of the declaring record +/// "belongs to" an instance of the other record. +/// +/// For example, if your application includes authors and books, and each book +/// is assigned its author, you'd declare the association this way: +/// +/// struct Author: TableRecord { ... } +/// struct Book: TableRecord { +/// static let author = belongsTo(Author.self) +/// ... +/// } +/// +/// A BelongsTo associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) // (2) +/// .notNull() // (3) +/// .indexed() // (4) +/// .references("author", onDelete: .cascade) // (5) +/// t.column("title", .text) +/// } +/// +/// 1. The author table has a primary key. +/// 2. The book.authorId column is used to link a book to the author it +/// belongs to. +/// 3. Make the book.authorId column not null if you want SQLite to guarantee +/// that all books have an author. +/// 4. Create an index on the book.authorId column in order to ease the +/// selection of an author's books. +/// 5. Create a foreign key from book.authorId column to authors.id, so that +/// SQLite guarantees that no book refers to a missing author. The +/// `onDelete: .cascade` option has SQLite automatically delete all of an +/// author's books when that author is deleted. +/// See https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses auto-incremented primary keys. But generally +/// speaking, all primary keys are supported. +/// +/// If the database schema does not define foreign keys between tables, you can +/// still use BelongsTo associations. But your help is needed to define the +/// missing foreign key: +/// +/// struct Book: FetchableRecord, TableRecord { +/// static let author = belongsTo(Author.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. public struct BelongsToAssociation: Association { fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest From 0191d64f56d8e9d7f02278d4ff7703c75822d549 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 18:55:14 +0200 Subject: [PATCH 286/348] Associations: inline documentation --- .../Association/HasManyAssociation.swift | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index b430a5886..68b872a24 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -1,3 +1,63 @@ +/// The HasMany association indicates a one-to-many connection between two +/// record types, such as each instance of the declaring record "has many" +/// instances of the other record. +/// +/// For example, if your application includes authors and books, and each author +/// is assigned zero or more books, you'd declare the association this way: +/// +/// struct Book: TableRecord { ... } +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self) +/// ... +/// } +/// +/// HasMany associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// try db.create(table: "author") { t in +/// t.autoIncrementedPrimaryKey("id") // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "book") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("authorId", .integer) // (2) +/// .notNull() // (3) +/// .indexed() // (4) +/// .references("author", onDelete: .cascade) // (5) +/// t.column("title", .text) +/// } +/// +/// 1. The author table has a primary key. +/// 2. The book.authorId column is used to link a book to the author it +/// belongs to. +/// 3. Make the book.authorId column not null if you want SQLite to guarantee +/// that all books have an author. +/// 4. Create an index on the book.authorId column in order to ease the +/// selection of an author's books. +/// 5. Create a foreign key from book.authorId column to authors.id, so that +/// SQLite guarantees that no book refers to a missing author. The +/// `onDelete: .cascade` option has SQLite automatically delete all of an +/// author's books when that author is deleted. +/// See https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses auto-incremented primary keys. But generally +/// speaking, all primary keys are supported. +/// +/// If the database schema does not define foreign keys between tables, you can +/// still use BelongsTo associations. But your help is needed to define the +/// missing foreign key: +/// +/// struct Author: TableRecord { +/// static let books = hasMany(Book.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. public struct HasManyAssociation: Association { fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest From b98992eb187bbb6756360b046595aefc024e18ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 19:05:45 +0200 Subject: [PATCH 287/348] Associations: inline documentation --- Documentation/AssociationsBasics.md | 2 +- .../Association/HasManyAssociation.swift | 2 +- .../Association/HasOneAssociation.swift | 62 +++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 1fab19016..406dceb78 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -428,7 +428,7 @@ struct Demographics: FetchableRecord, TableRecord { If the database schema does not follow this convention, and does not define foreign keys between tables, you can still use HasOne associations. But your help is needed to define the missing foreign key: ```swift -struct Book: FetchableRecord, TableRecord { +struct Country: FetchableRecord, TableRecord { static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) } ``` diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 68b872a24..575cf8dc0 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -50,7 +50,7 @@ /// speaking, all primary keys are supported. /// /// If the database schema does not define foreign keys between tables, you can -/// still use BelongsTo associations. But your help is needed to define the +/// still use HasMany associations. But your help is needed to define the /// missing foreign key: /// /// struct Author: TableRecord { diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index e53b35d62..4df3f5f59 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -1,3 +1,65 @@ +/// The HasOne association indicates a one-to-one connection between two +/// record types, such as each instance of the declaring record "has one" +/// instances of the other record. +/// +/// For example, if your application has one database table for countries, and +/// another for their demographic profiles, you'd declare the association +/// this way: +/// +/// struct Demographics: TableRecord { ... } +/// struct Country: TableRecord { +/// static let demographics = hasOne(Demographics.self) +/// ... +/// } +/// +/// HasOne associations should be supported by an SQLite foreign key. +/// +/// Foreign keys are the recommended way to declare relationships between +/// database tables because not only will SQLite guarantee the integrity of your +/// data, but GRDB will be able to use those foreign keys to automatically +/// configure your association. +/// +/// You define the foreign key when you create database tables. For example: +/// +/// try db.create(table: "country") { t in +/// t.column("code", .text).primaryKey() // (1) +/// t.column("name", .text) +/// } +/// try db.create(table: "demographics") { t in +/// t.autoIncrementedPrimaryKey("id") +/// t.column("countryCode", .text) // (2) +/// .notNull() // (3) +/// .unique() // (4) +/// .references("country", onDelete: .cascade) // (5) +/// t.column("population", .integer) +/// t.column("density", .double) +/// } +/// +/// 1. The country table has a primary key. +/// 2. The demographics.countryCode column is used to link a demographic +/// profile to the country it belongs to. +/// 3. Make the demographics.countryCode column not null if you want SQLite to +/// guarantee that all profiles are linked to a country. +/// 4. Create a unique index on the demographics.countryCode column in order to +/// guarantee the unicity of any country's profile. +/// 5. Create a foreign key from demographics.countryCode column to +/// country.code, so that SQLite guarantees that no profile refers to a +/// missing country. The `onDelete: .cascade` option has SQLite automatically +/// delete a profile when its country is deleted. +/// See https://sqlite.org/foreignkeys.html#fk_actions for more information. +/// +/// The example above uses a string primary for the country table. But generally +/// speaking, all primary keys are supported. +/// +/// If the database schema does not follow this convention, and does not define +/// foreign keys between tables, you can still use HasOne associations. But +/// your help is needed to define the missing foreign key: +/// +/// struct Country: FetchableRecord, TableRecord { +/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...)) +/// } +/// +/// See ForeignKey for more information. public struct HasOneAssociation : Association { fileprivate let joinConditionRequest: ForeignKeyJoinConditionRequest From dadece1b04e0ee8c22dcaff5af2859ee9edc0dfe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 20 May 2018 19:35:18 +0200 Subject: [PATCH 288/348] Associations: inline documentation --- Documentation/AssociationsBasics.md | 2 +- .../Association/ForeignKey.swift | 58 ++++++++++++++++++- 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 406dceb78..f137641d2 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -544,7 +544,7 @@ struct Person: TableRecord { } ``` -Foreign keys can also be defined from `Column`: +Foreign keys can also be defined from query interface columns: ```swift struct Book: TableRecord { diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift index 032694e69..db2fca074 100644 --- a/GRDB/QueryInterface/Association/ForeignKey.swift +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -1,4 +1,60 @@ -/// A Foreign Key that helps building associations. +/// A ForeignKey helps building associations when GRDB can't infer a foreign +/// key from the database schema. +/// +/// Sometimes the database schema does not define any foreign key between two +/// tables. And sometimes, there are several foreign keys from a table +/// to another: +/// +/// Table book Table author +/// • id +--> • id +/// • authorId ------+ • name +/// • translatorId --+ +/// • title +/// +/// When this happens, associations can't be automatically inferred from the +/// database schema. GRDB will complain with a fatal error such as "Ambiguous +/// foreign key from book to author", or "Could not infer foreign key from book +/// to author". +/// +/// Your help is needed. You have to instruct GRDB which foreign key to use: +/// +/// struct Book: TableRecord { +/// // Define foreign keys +/// static let authorForeignKey = ForeignKey(["authorId"])) +/// static let translatorForeignKey = ForeignKey(["translatorId"])) +/// +/// // Use foreign keys to define associations: +/// static let author = belongsTo(Person.self, using: authorForeignKey) +/// static let translator = belongsTo(Person.self, using: translatorForeignKey) +/// } +/// +/// Foreign keys are always defined from the table that contains the columns at +/// the origin of the foreign key. Person's symmetric HasMany associations reuse +/// Book's foreign keys: +/// +/// struct Person: TableRecord { +/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey) +/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey) +/// } +/// +/// Foreign keys can also be defined from query interface columns: +/// +/// struct Book: TableRecord { +/// enum Columns: String, ColumnExpression { +/// case id, title, authorId, translatorId +/// } +/// +/// static let authorForeignKey = ForeignKey([Columns.authorId])) +/// static let translatorForeignKey = ForeignKey([Columns.translatorId])) +/// } +/// +/// When the destination table of a foreign key does not define any primary key, +/// you need to provide the full definition of a foreign key: +/// +/// struct Book: TableRecord { +/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])) +/// static let author = belongsTo(Person.self, using: authorForeignKey) +/// } public struct ForeignKey { let originColumns: [String] let destinationColumns: [String]? From 07176e941b9daa44ed221180032be728e4eca593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 21 May 2018 07:35:25 +0200 Subject: [PATCH 289/348] Associations: inline documentation --- Documentation/AssociationsBasics.md | 2 +- .../Association/ForeignKey.swift | 54 +++++++++++++++---- 2 files changed, 46 insertions(+), 10 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index f137641d2..ccaf0dda8 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -519,7 +519,7 @@ Sometimes the database schema does not define any foreign key. And sometimes, th ![AmbiguousForeignKeys](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/AmbiguousForeignKeys.svg) -When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to author", or "Could not infer foreign key from book to author". +When this happens, associations can't be automatically inferred from the database schema. GRDB will complain with a fatal error such as "Ambiguous foreign key from book to person", or "Could not infer foreign key from book to person". Your help is needed. You have to instruct GRDB which foreign key to use: diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift index db2fca074..d1e80ab2c 100644 --- a/GRDB/QueryInterface/Association/ForeignKey.swift +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -5,16 +5,17 @@ /// tables. And sometimes, there are several foreign keys from a table /// to another: /// -/// Table book Table author -/// • id +--> • id -/// • authorId ------+ • name -/// • translatorId --+ -/// • title +/// | Table book | | Table person | +/// | ------------ | | ------------ | +/// | id | +-->• id | +/// | authorId •---+ | name | +/// | translatorId •---+ +/// | title | /// /// When this happens, associations can't be automatically inferred from the /// database schema. GRDB will complain with a fatal error such as "Ambiguous -/// foreign key from book to author", or "Could not infer foreign key from book -/// to author". +/// foreign key from book to person", or "Could not infer foreign key from book +/// to person". /// /// Your help is needed. You have to instruct GRDB which foreign key to use: /// @@ -59,13 +60,48 @@ public struct ForeignKey { let originColumns: [String] let destinationColumns: [String]? - /// TODO + /// Creates a ForeignKey intended to define a record association. + /// + /// struct Book: TableRecord { + /// // Define foreign keys + /// static let authorForeignKey = ForeignKey(["authorId"])) + /// static let translatorForeignKey = ForeignKey(["translatorId"])) + /// + /// // Use foreign keys to define associations: + /// static let author = belongsTo(Person.self, using: authorForeignKey) + /// static let translator = belongsTo(Person.self, using: translatorForeignKey) + /// } + /// + /// - parameter originColumns: The columns at the origin of the foreign key. + /// - parameter destinationColumns: The columns at the destination of the + /// foreign key. When nil (the default), GRDB automatically uses the + /// primary key. public init(_ originColumns: [String], to destinationColumns: [String]? = nil) { self.originColumns = originColumns self.destinationColumns = destinationColumns } - /// TODO + /// Creates a ForeignKey intended to define a record association. + /// + /// struct Book: TableRecord { + /// // Define columns + /// enum Columns: String, ColumnExpression { + /// case id, title, authorId, translatorId + /// } + /// + /// // Define foreign keys + /// static let authorForeignKey = ForeignKey([Columns.authorId])) + /// static let translatorForeignKey = ForeignKey([Columns.translatorId])) + /// + /// // Use foreign keys to define associations: + /// static let author = belongsTo(Person.self, using: authorForeignKey) + /// static let translator = belongsTo(Person.self, using: translatorForeignKey) + /// } + /// + /// - parameter originColumns: The columns at the origin of the foreign key. + /// - parameter destinationColumns: The columns at the destination of the + /// foreign key. When nil (the default), GRDB automatically uses the + /// primary key. public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) { self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name }) } From 4eac0797fa8f47b8b520b0fb9d93b1247166be82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 21 May 2018 07:39:30 +0200 Subject: [PATCH 290/348] Less TODO --- GRDB/QueryInterface/Association/ForeignKeyRequest.swift | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift index 014c07b8c..771e90a77 100644 --- a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -41,8 +41,8 @@ struct ForeignKeyRequest { return false } } - // TODO: test if let destinationColumns = destinationColumns { + // TODO: test let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() }) let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() }) if destinationColumns != foreignKeyColumns { @@ -56,7 +56,6 @@ struct ForeignKeyRequest { if let foreignKey = foreignKeys.first { if foreignKeys.count == 1 { // Non-ambiguous - // TODO: test return foreignKey } else { // Ambiguous: can't choose @@ -68,7 +67,6 @@ struct ForeignKeyRequest { if let originColumns = originColumns { let destinationColumns = try db.primaryKey(destinationTable).columns if (originColumns.count == destinationColumns.count) { - // TODO: test let mapping = zip(originColumns, destinationColumns).map { (origin: $0, destination: $1) } From 0620b1b513f890fa72050110160cb5b8ca8ecb2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 21 May 2018 07:53:06 +0200 Subject: [PATCH 291/348] Associations: inline documentation --- GRDB/QueryInterface/Association/Association.swift | 7 ++++--- GRDB/QueryInterface/Association/AssociationRequest.swift | 1 + GRDB/QueryInterface/Association/BelongsToAssociation.swift | 1 + GRDB/QueryInterface/Association/ForeignKey.swift | 4 ++-- GRDB/QueryInterface/Association/ForeignKeyRequest.swift | 1 - GRDB/QueryInterface/Association/HasManyAssociation.swift | 1 + GRDB/QueryInterface/Association/HasOneAssociation.swift | 1 + GRDB/QueryInterface/Column.swift | 5 ++--- 8 files changed, 12 insertions(+), 9 deletions(-) diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index 2c034f97b..c578b78e1 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -48,11 +48,9 @@ public protocol Association: DerivableRequest { /// } func forKey(_ key: String) -> Self - // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: var request: AssociationRequest { get } - // TODO: this one prevents "through" associations like HasOneThrough, HasManyThrough, etc. /// :nodoc: func joinCondition(_ db: Database) throws -> JoinCondition @@ -213,6 +211,8 @@ extension Association { } } +/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features) +/// :nodoc: public typealias JoinCondition = (_ leftAlias: TableAlias, _ rightAlias: TableAlias) -> SQLExpression? /// Turns a ForeignKeyRequest into a JoinCondition @@ -288,7 +288,8 @@ extension Association where OriginRowDecoder: MutablePersistableRecord { let associationAlias = TableAlias() let recordAlias = TableAlias() - // Turn JOIN into SELECT FROM + // Turn the association request into a query interface request: + // JOIN association -> SELECT FROM association return QueryInterfaceRequest(request) // Turn the JOIN condition into a regular WHERE condition diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 789e1326a..3f7909a5e 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -2,6 +2,7 @@ /// /// In `SELECT a.*, b.* FROM a JOIN b ON b.aid = a.id AND b.name = 'foo'`, /// the AssociationRequest is (`b.*` + `b.name = 'foo'`). +/// :nodoc: public struct AssociationRequest { let query: AssociationQuery diff --git a/GRDB/QueryInterface/Association/BelongsToAssociation.swift b/GRDB/QueryInterface/Association/BelongsToAssociation.swift index bde6e005a..3b9fd882d 100644 --- a/GRDB/QueryInterface/Association/BelongsToAssociation.swift +++ b/GRDB/QueryInterface/Association/BelongsToAssociation.swift @@ -91,6 +91,7 @@ public struct BelongsToAssociation: Association { } } +// Allow BelongsToAssociation(...).filter(key: ...) extension BelongsToAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } diff --git a/GRDB/QueryInterface/Association/ForeignKey.swift b/GRDB/QueryInterface/Association/ForeignKey.swift index d1e80ab2c..5b4312762 100644 --- a/GRDB/QueryInterface/Association/ForeignKey.swift +++ b/GRDB/QueryInterface/Association/ForeignKey.swift @@ -57,8 +57,8 @@ /// static let author = belongsTo(Person.self, using: authorForeignKey) /// } public struct ForeignKey { - let originColumns: [String] - let destinationColumns: [String]? + var originColumns: [String] + var destinationColumns: [String]? /// Creates a ForeignKey intended to define a record association. /// diff --git a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift index 771e90a77..077581950 100644 --- a/GRDB/QueryInterface/Association/ForeignKeyRequest.swift +++ b/GRDB/QueryInterface/Association/ForeignKeyRequest.swift @@ -79,5 +79,4 @@ struct ForeignKeyRequest { } /// The (origin, destination) column pairs that join a left table to a right table. -/// :nodoc: typealias ForeignKeyMapping = [(origin: String, destination: String)] diff --git a/GRDB/QueryInterface/Association/HasManyAssociation.swift b/GRDB/QueryInterface/Association/HasManyAssociation.swift index 575cf8dc0..7e0fa6b72 100644 --- a/GRDB/QueryInterface/Association/HasManyAssociation.swift +++ b/GRDB/QueryInterface/Association/HasManyAssociation.swift @@ -91,6 +91,7 @@ public struct HasManyAssociation: Association { } } +// Allow HasManyAssociation(...).filter(key: ...) extension HasManyAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } diff --git a/GRDB/QueryInterface/Association/HasOneAssociation.swift b/GRDB/QueryInterface/Association/HasOneAssociation.swift index 4df3f5f59..58bb5eea6 100644 --- a/GRDB/QueryInterface/Association/HasOneAssociation.swift +++ b/GRDB/QueryInterface/Association/HasOneAssociation.swift @@ -93,6 +93,7 @@ public struct HasOneAssociation : Association { } } +// Allow HasOneAssociation(...).filter(key: ...) extension HasOneAssociation: TableRequest where Destination: TableRecord { /// :nodoc: public var databaseTableName: String { return Destination.databaseTableName } diff --git a/GRDB/QueryInterface/Column.swift b/GRDB/QueryInterface/Column.swift index bcdc7fe86..e66ca6ba4 100644 --- a/GRDB/QueryInterface/Column.swift +++ b/GRDB/QueryInterface/Column.swift @@ -1,12 +1,11 @@ -/// Adopt the ColumnExpression protocol in order to define a custom column type. +/// Adopt the ColumnExpression protocol when you define a column type. /// /// You can, for example, define a String-based column enum: /// /// enum Columns: String, ColumnExpression { /// case id, name, score /// } -/// let nameColumn = Columns.name -/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) +/// let arthur = try Player.filter(Columns.name == "Arthur").fetchOne(db) /// /// You can also define a genuine column type: /// From cacc3e84564dae12938e586a5392228d1870307f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 21 May 2018 08:21:36 +0200 Subject: [PATCH 292/348] Fix DatabasePool.makeSnapshot() documentation --- GRDB/Core/DatabasePool.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 29dee73e4..21e908166 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -645,7 +645,7 @@ extension DatabasePool { /// /// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in /// try Player.deleteAll() - /// return dbPool.makeSnapshot() + /// return try dbPool.makeSnapshot() /// } /// // <- Other threads may modify the database here /// let snapshot2 = try dbPool.makeSnapshot() @@ -668,7 +668,7 @@ extension DatabasePool { /// try db.inTransaction { /// try Player.deleteAll() /// // fatal error: makeSnapshot() must not be called from inside a transaction - /// let snapshot = dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() /// return .commit /// } /// } @@ -676,9 +676,9 @@ extension DatabasePool { /// To avoid this fatal error, create the snapshot *before* or *after* the /// transaction: /// - /// try dbPool.write { db in + /// try dbPool.writeWithoutTransaction { db in /// // OK - /// let snapshot = dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() /// /// try db.inTransaction { /// try Player.deleteAll() @@ -686,7 +686,7 @@ extension DatabasePool { /// } /// /// // OK - /// let snapshot = dbPool.makeSnapshot() + /// let snapshot = try dbPool.makeSnapshot() /// } /// /// You can create as many snapshots as you need, regardless of the maximum From 5d7245af2af005b872f3cbe9180c52fa34b4b767 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 21 May 2018 08:26:06 +0200 Subject: [PATCH 293/348] Fix DatabaseRegion documentation formatting --- GRDB/Core/DatabaseRegion.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index 9758b1b41..dca47393f 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -6,12 +6,12 @@ /// cover a full table, or the combination of columns and rows (identified by /// their rowids): /// -/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | -/// |-------| |-------| |-------| |-------| |-------| -/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | -/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | -/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | -/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | +/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 | +/// |-------| |-------| |-------| |-------| |-------| +/// |x|x|x|x| |x| | | | |x|x|x|x| |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | |x| | | +/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | | +/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | | /// /// You don't create a database region directly. Instead, you use one of /// those methods: From 86f084cb3e0953602ca08d2be6a07fc04a6e6d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Rou=C3=A9?= Date: Mon, 21 May 2018 08:27:47 +0200 Subject: [PATCH 294/348] Fix DatabaseRegion inline documentation --- GRDB/Core/DatabaseRegion.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index dca47393f..490450ebb 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -22,7 +22,7 @@ /// print(statement.databaseRegion) /// // prints "player(name,score)" /// -/// - `Request.databaseRegion(_:)` +/// - `FetchRequest.databaseRegion(_:)` /// /// let request = Player.filter(key: 1) /// try print(request.databaseRegion(db)) From cdf5462005e5fe6e4a98f2055be5de6dc5684830 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 21 May 2018 08:39:48 +0200 Subject: [PATCH 295/348] Harmonize fetching methods with CustomizedDecodingOfDatabaseRows playground --- GRDB/Core/DatabaseValueConvertible.swift | 10 +++++----- GRDB/Core/Row.swift | 6 +++--- GRDB/Core/StatementColumnConvertible.swift | 10 +++++----- GRDB/Record/FetchableRecord.swift | 6 +++--- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index e5e35095b..2a72042eb 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -218,7 +218,7 @@ extension DatabaseValueConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. @@ -233,7 +233,7 @@ extension DatabaseValueConvertible { /// - returns: An array. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. @@ -251,7 +251,7 @@ extension DatabaseValueConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } @@ -446,7 +446,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. @@ -461,7 +461,7 @@ extension Optional where Wrapped: DatabaseValueConvertible { /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index 5c385ec99..804054651 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -717,7 +717,7 @@ extension Row { /// - returns: A cursor over fetched rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of rows fetched from an SQL query. @@ -732,7 +732,7 @@ extension Row { /// - returns: An array of rows. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single row fetched from an SQL query. @@ -747,7 +747,7 @@ extension Row { /// - returns: An optional row. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index fa7ef5446..499c39dd9 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -249,7 +249,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: A cursor over fetched values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> ColumnCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of values fetched from an SQL query. @@ -264,7 +264,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An array of values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single value fetched from an SQL query. @@ -279,7 +279,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// - returns: An optional value. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } @@ -471,7 +471,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: A cursor over fetched optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableColumnCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of optional values fetched from an SQL query. @@ -486,7 +486,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv /// - returns: An array of optional values. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index b4212b398..fa7db477e 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -149,7 +149,7 @@ extension FetchableRecord { /// - returns: A cursor over fetched records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchCursor(db) + return try fetchCursor(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns an array of records fetched from an SQL query. @@ -164,7 +164,7 @@ extension FetchableRecord { /// - returns: An array of records. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchAll(db) + return try fetchAll(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } /// Returns a single record fetched from an SQL query. @@ -179,7 +179,7 @@ extension FetchableRecord { /// - returns: An optional record. /// - throws: A DatabaseError is thrown whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { - return try SQLRequest(sql, arguments: arguments, adapter: adapter).fetchOne(db) + return try fetchOne(db, SQLRequest(sql, arguments: arguments, adapter: adapter)) } } From 5de7a5274ee42a1ece810a291172bf8b377d6ac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 20:32:24 +0200 Subject: [PATCH 296/348] Remove useless #if swift(>=3.1) --- GRDB/Record/Record.swift | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 021a15a66..f13962220 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -150,14 +150,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { /// /// - returns: A copy of self. open func copy() -> Self { - let row: Row - #if swift(>=3.1) - row = Row(self) - #else - // workaround weird Swift 3.0 glitch - row = Row(self as! MutablePersistableRecord) - #endif - let copy = type(of: self).init(row: row) + let copy = type(of: self).init(row: Row(self)) copy.referenceRow = referenceRow return copy } From af8971bcd826d366b0004d6789c3fb9fd2aa6cc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 22:14:18 +0200 Subject: [PATCH 297/348] Default implementation for TableRecord.databaseTableName --- GRDB/Record/TableRecord.swift | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 60c9478d4..1c36ce8fe 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -50,6 +50,40 @@ public protocol TableRecord { } extension TableRecord { + + /// The default name of the database table used to build requests. + /// + /// - Player -> "player" + /// - Place -> "place" + /// - PostalAddress -> "postalAddress" + /// - HTTPRequest -> "httpRequest" + /// - TOEFL -> "toefl" + internal static var defaultDatabaseTableName: String { + let typeName = "\(Self.self)".replacingOccurrences(of: "(.)\\b.*$", with: "$1", options: [.regularExpression]) + let initial = typeName.replacingOccurrences(of: "^([A-Z]+).*$", with: "$1", options: [.regularExpression]) + switch initial.count { + case typeName.count: + return initial.lowercased() + case 0: + return typeName + case 1: + return initial.lowercased() + typeName.dropFirst() + default: + return initial.dropLast().lowercased() + typeName.dropFirst(initial.count - 1) + } + } + + /// The default name of the database table used to build requests. + /// + /// - Player -> "player" + /// - Place -> "place" + /// - PostalAddress -> "postalAddress" + /// - HTTPRequest -> "httpRequest" + /// - TOEFL -> "toefl" + public static var databaseTableName: String { + return defaultDatabaseTableName + } + /// Default value: `[AllColumns()]`. public static var databaseSelection: [SQLSelectable] { return [AllColumns()] From 7b59c097c614f08fcee3f200e7415c3f64879342 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 22:43:01 +0200 Subject: [PATCH 298/348] Test for default implementation for TableRecord.databaseTableName --- Tests/GRDBTests/TableRecordTests.swift | 87 ++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index fefb44642..e33b18046 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -7,8 +7,95 @@ import XCTest import GRDB #endif +private struct RecordStruct: TableRecord { } +private struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } +private class RecordClass: TableRecord { } +private class RecordSubClass: RecordClass { } +private class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } +private class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } +private class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } +private enum Namespace { + struct RecordStruct: TableRecord { } + struct CustomizedRecordStruct: TableRecord { static let databaseTableName = "CustomizedRecordStruct" } + class RecordClass: TableRecord { } + class RecordSubClass: RecordClass { } + class CustomizedRecordClass: TableRecord { class var databaseTableName: String { return "CustomizedRecordClass" } } + class CustomizedRecordSubClass: CustomizedRecordClass { override class var databaseTableName: String { return "CustomizedRecordSubClass" } } + class CustomizedPlainRecord: Record { override class var databaseTableName: String { return "CustomizedPlainRecord" } } +} +struct HTTPRequest: TableRecord { } +struct TOEFL: TableRecord { } + class TableRecordTests: GRDBTestCase { + func testDefaultDatabaseTableName() { + struct InnerRecordStruct: TableRecord { } + struct InnerCustomizedRecordStruct: TableRecord { static let databaseTableName = "InnerCustomizedRecordStruct" } + class InnerRecordClass: TableRecord { } + class InnerRecordSubClass: InnerRecordClass { } + class InnerCustomizedRecordClass: TableRecord { class var databaseTableName: String { return "InnerCustomizedRecordClass" } } + class InnerCustomizedRecordSubClass: InnerCustomizedRecordClass { override class var databaseTableName: String { return "InnerCustomizedRecordSubClass" } } + class InnerCustomizedPlainRecord: Record { override class var databaseTableName: String { return "InnerCustomizedPlainRecord" } } + + XCTAssertEqual(RecordStruct.databaseTableName, "recordStruct") + XCTAssertEqual(CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") + XCTAssertEqual(RecordClass.databaseTableName, "recordClass") + XCTAssertEqual(RecordSubClass.databaseTableName, "recordSubClass") + XCTAssertEqual(CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") + XCTAssertEqual(CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") + XCTAssertEqual(CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") + + XCTAssertEqual(Namespace.RecordStruct.databaseTableName, "recordStruct") + XCTAssertEqual(Namespace.CustomizedRecordStruct.databaseTableName, "CustomizedRecordStruct") + XCTAssertEqual(Namespace.RecordClass.databaseTableName, "recordClass") + XCTAssertEqual(Namespace.RecordSubClass.databaseTableName, "recordSubClass") + XCTAssertEqual(Namespace.CustomizedRecordClass.databaseTableName, "CustomizedRecordClass") + XCTAssertEqual(Namespace.CustomizedRecordSubClass.databaseTableName, "CustomizedRecordSubClass") + XCTAssertEqual(Namespace.CustomizedPlainRecord.databaseTableName, "CustomizedPlainRecord") + + XCTAssertEqual(InnerRecordStruct.databaseTableName, "innerRecordStruct") + XCTAssertEqual(InnerCustomizedRecordStruct.databaseTableName, "InnerCustomizedRecordStruct") + XCTAssertEqual(InnerRecordClass.databaseTableName, "innerRecordClass") + XCTAssertEqual(InnerRecordSubClass.databaseTableName, "innerRecordSubClass") + XCTAssertEqual(InnerCustomizedRecordClass.databaseTableName, "InnerCustomizedRecordClass") + XCTAssertEqual(InnerCustomizedRecordSubClass.databaseTableName, "InnerCustomizedRecordSubClass") + XCTAssertEqual(InnerCustomizedPlainRecord.databaseTableName, "InnerCustomizedPlainRecord") + + XCTAssertEqual(HTTPRequest.databaseTableName, "httpRequest") + XCTAssertEqual(TOEFL.databaseTableName, "toefl") + + func tableName(_ type: T.Type) -> String { + return T.databaseTableName + } + + XCTAssertEqual(tableName(RecordStruct.self), "recordStruct") + XCTAssertEqual(tableName(CustomizedRecordStruct.self), "CustomizedRecordStruct") + XCTAssertEqual(tableName(RecordClass.self), "recordClass") + XCTAssertEqual(tableName(RecordSubClass.self), "recordSubClass") + XCTAssertEqual(tableName(CustomizedRecordClass.self), "CustomizedRecordClass") + XCTAssertEqual(tableName(CustomizedRecordSubClass.self), "CustomizedRecordSubClass") + XCTAssertEqual(tableName(CustomizedPlainRecord.self), "CustomizedPlainRecord") + + XCTAssertEqual(tableName(Namespace.RecordStruct.self), "recordStruct") + XCTAssertEqual(tableName(Namespace.CustomizedRecordStruct.self), "CustomizedRecordStruct") + XCTAssertEqual(tableName(Namespace.RecordClass.self), "recordClass") + XCTAssertEqual(tableName(Namespace.RecordSubClass.self), "recordSubClass") + XCTAssertEqual(tableName(Namespace.CustomizedRecordClass.self), "CustomizedRecordClass") + XCTAssertEqual(tableName(Namespace.CustomizedRecordSubClass.self), "CustomizedRecordSubClass") + XCTAssertEqual(tableName(Namespace.CustomizedPlainRecord.self), "CustomizedPlainRecord") + + XCTAssertEqual(tableName(InnerRecordStruct.self), "innerRecordStruct") + XCTAssertEqual(tableName(InnerCustomizedRecordStruct.self), "InnerCustomizedRecordStruct") + XCTAssertEqual(tableName(InnerRecordClass.self), "innerRecordClass") + XCTAssertEqual(tableName(InnerRecordSubClass.self), "innerRecordSubClass") + XCTAssertEqual(tableName(InnerCustomizedRecordClass.self), "InnerCustomizedRecordClass") + XCTAssertEqual(tableName(InnerCustomizedRecordSubClass.self), "InnerCustomizedRecordSubClass") + XCTAssertEqual(tableName(InnerCustomizedPlainRecord.self), "InnerCustomizedPlainRecord") + + XCTAssertEqual(tableName(HTTPRequest.self), "httpRequest") + XCTAssertEqual(tableName(TOEFL.self), "toefl") + } + func testDefaultDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" From 76299d9302e192eea4477e54e143ed1109d05ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 22:58:15 +0200 Subject: [PATCH 299/348] Document default implementation for TableRecord.databaseTableName in GRDB2 Migration Guide --- Documentation/GRDB2MigrationGuide.md | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 7791dd2df..7c730a105 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -17,6 +17,7 @@ GRDB 3 comes with new features, but also a few breaking changes, and a set of up - [If You Use Database Queues] - [If You Use Database Pools] - [If You Use Database Snapshots] +- [If You Use Record Types] - [If You Use Custom Requests] - [If You Use RxGRDB] - [Notable Documentation Updates] @@ -88,6 +89,8 @@ GRDB 3 still accepts any database, but brings two schema recommendations: - :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. + + This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below. Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema: @@ -349,6 +352,46 @@ let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in ``` +## If You Use Record Types + +Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name: + +```swift +// GRDB 2 +struct Place: TableMapping { + static let databaseTableName = "place" +} +print(Place.databaseTableName) // print "place" +``` + +With GRDB 3, the `databaseTableName` property gets a default implementation: + +```swift +// GRDB 3 +struct Place: TableRecord { } +print(Place.databaseTableName) // print "place" +``` + +That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier: + +- Place: `place` +- Country: `country` +- PostalAddrress: `postalAddress` +- HTTPRequest: `httpRequest` +- TOELF: `toefl` + +When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name: + +```swift +// GRDB 3 +class Place: Record { + override var databaseTableName: String { + return "place" + } +} +``` + + ## If You Use Custom Requests [Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need. @@ -469,6 +512,7 @@ If you have time, you may dig deeper in GRDB 3 with those updated documentation [If You Use Database Queues]: #if-you-use-database-queues [If You Use Database Pools]: #if-you-use-database-pools [If You Use Database Snapshots]: #if-you-use-database-snapshots +[If You Use Record Types]: #if-you-use-record-types [If You Use Custom Requests]: #if-you-use-custom-requests [If You Use RxGRDB]: #if-you-use-rxgrdb [Notable Documentation Updates]: #notable-documentation-updates From 1213fa0a433b65c99ed76c37b708c593eeb1ab05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 23:18:33 +0200 Subject: [PATCH 300/348] Document default implementation for TableRecord.databaseTableName --- Documentation/GRDB2MigrationGuide.md | 8 ++-- README.md | 60 ++++++++++++++-------------- 2 files changed, 35 insertions(+), 33 deletions(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index 7c730a105..bcb4cefc1 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -86,7 +86,7 @@ GRDB 3 still accepts any database, but brings two schema recommendations: } ``` -- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. +- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. @@ -376,14 +376,14 @@ That default name follows the [Database Schema Recommendations]: it is singular, - Place: `place` - Country: `country` -- PostalAddrress: `postalAddress` +- PostalAddress: `postalAddress` - HTTPRequest: `httpRequest` -- TOELF: `toefl` +- TOEFL: `toefl` When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name: ```swift -// GRDB 3 +// GRDB 2 and GRDB 3 class Place: Record { override var databaseTableName: String { return "place" diff --git a/README.md b/README.md index d59c2a933..030eb920d 100644 --- a/README.md +++ b/README.md @@ -2294,17 +2294,35 @@ protocol TableRecord { } ``` -The `databaseTableName` type property is the name of a database table. `databaseSelection` is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. +**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. -**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. For example: +- The `databaseTableName` type property is the name of a database table. By default, it is derived from the type name: + + - Place: `place` + - Country: `country` + - PostalAddress: `postalAddress` + - HTTPRequest: `httpRequest` + - TOEFL: `toefl` + + ```swift + struct Place: TableRecord { } + print(Place.databaseTableName) // prints "place" + ``` + + Subclasses of the [Record](#record-class) class can't profit from this default name, and must explicitly override their superclass's `databaseTableName` property: + + ```swift + class Place: Record { + override class var databaseTableName: String { + return "place" + } + } + print(Place.databaseTableName) // prints "place" + ``` + +- The `databaseSelection` type property is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. -```swift -extension Place : TableRecord { - static let databaseTableName = "place" -} -``` - -Adopting types can be fetched without SQL, using the [query interface](#the-query-interface): +Adopting types can generate SQL. When they also adopt FetchableRecord, they can be fetched using the [query interface](#the-query-interface): ```swift // SELECT * FROM place WHERE name = 'Paris' @@ -2523,9 +2541,7 @@ struct Player: Codable { } // Adopt Record protocols... -extension Player: FetchableRecord, PersistableRecord { - static let databaseTableName = "player" -} +extension Player: FetchableRecord, PersistableRecord { } // ...and you can save and fetch players: try dbQueue.write { db in @@ -2539,8 +2555,6 @@ GRDB support for Codable works well with "flat" records, whose stored properties ```swift // Can't take profit from Codable code generation: struct Place: FetchableRecord, PersistableRecord, Codable { - static let databaseTableName = "place" - var title: String var coordinate: CLLocationCoordinate2D // <- Not a simple value! } @@ -2570,9 +2584,7 @@ struct Place: Codable { } // Free database support! -extension Place: FetchableRecord, PersistableRecord { - static let databaseTableName = "place" -} +extension Place: FetchableRecord, PersistableRecord { } ``` GRDB ships with support for nested codable records, but this is a more complex topic. See [Joined Queries Support](#joined-queries-support) for more information. @@ -2589,8 +2601,6 @@ struct Place: Codable { } extension Place: FetchableRecord, MutablePersistableRecord { - static let databaseTableName = "place" - mutating func didInsert(with rowID: Int64, for column: String?) { // Update id after insertion id = rowID @@ -2994,10 +3004,7 @@ struct Place: Codable { } // SQL generation -extension Place: TableRecord { - /// The table name - static let databaseTableName = "place" -} +extension Place: TableRecord { } // Fetching methods extension Place: FetchableRecord { } @@ -3028,9 +3035,6 @@ struct Place { // SQL generation extension Place: TableRecord { - /// The table name - static let databaseTableName = "place" - /// The table columns enum Columns: String, ColumnExpression { case id, title, favorite, latitude, longitude @@ -3323,7 +3327,7 @@ try db.create(table: "example") { t in ... } try db.create(table: "example", temporary: true, ifNotExists: true) { t in ``` -> :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`. +> :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. > > This will help you using the new [Associations](Documentation/AssociationsBasics.md) feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. @@ -5320,12 +5324,10 @@ You can consume complex joined queries with Codable records as well. As a demons ```swift struct Player: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "player" var id: Int64 var name: String } struct Team: Decodable, FetchableRecord, TableRecord { - static let databaseTableName = "team" var id: Int64 var name: String var color: Color From ce03deeccc62c29785248d0a9b68ff906a45e375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 23:31:37 +0200 Subject: [PATCH 301/348] Change log for default implementation for TableRecord.databaseTableName --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c23bf0cef..b73c0ae7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,8 @@ It comes with new features, but also a few breaking changes, and a set of update - Upgrade custom SQLite builds to [v3.23.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)). - Improve Row descriptions ([#331](https://github.com/groue/GRDB.swift/pull/331)). - Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)). +- Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)). +- Automatic table name generation ([#355](https://github.com/groue/GRDB.swift/pull/355)). ### Breaking Changes @@ -45,6 +47,7 @@ It comes with new features, but also a few breaking changes, and a set of update - [Database Pools](README.md#database-pools): focus on the `read` and `write` methods. - [Transactions and Savepoints](README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature. - [ScopeAdapter](README.md#scopeadapter): do you use row adapters? If so, have a look. +- [TableRecord Protocol](README.md#tablerecord-protocol): updated for the new automatic generation of database table name. - [Examples of Record Definitions](README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass). - [SQL Operators](README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`. - [Custom Requests](README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter. From dcb626b32bcc8b5a58287963747132e874e61a13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 23:48:01 +0200 Subject: [PATCH 302/348] TableRecord documentation --- README.md | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 030eb920d..c84caf55e 100644 --- a/README.md +++ b/README.md @@ -2285,7 +2285,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor ## TableRecord Protocol -**Adopt the TableRecord protocol** on top of [FetchableRecord], and you are granted with the full [query interface](#the-query-interface). +**The TableRecord protocol** generates SQL for you. To use TableRecord, subclass the [Record](#record-class) class, or adopt it explicitly: ```swift protocol TableRecord { @@ -2294,19 +2294,28 @@ protocol TableRecord { } ``` -**To use TableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. - - The `databaseTableName` type property is the name of a database table. By default, it is derived from the type name: + ```swift + struct Place: TableRecord { } + print(Place.databaseTableName) // prints "place" + ``` + + For example: + - Place: `place` - Country: `country` - PostalAddress: `postalAddress` - HTTPRequest: `httpRequest` - TOEFL: `toefl` + You can still provide a custom table name: + ```swift - struct Place: TableRecord { } - print(Place.databaseTableName) // prints "place" + struct Place: TableRecord { + static let databaseTableName = "location" + } + print(Place.databaseTableName) // prints "location" ``` Subclasses of the [Record](#record-class) class can't profit from this default name, and must explicitly override their superclass's `databaseTableName` property: @@ -2322,7 +2331,7 @@ protocol TableRecord { - The `databaseSelection` type property is optional, and documented in the [Columns Selected by a Request](#columns-selected-by-a-request) chapter. -Adopting types can generate SQL. When they also adopt FetchableRecord, they can be fetched using the [query interface](#the-query-interface): +When a type adopts both TableRecord and [FetchableRecord](#fetchablerecord-protocol), it can be fetched using the [query interface](#the-query-interface): ```swift // SELECT * FROM place WHERE name = 'Paris' From 2e477feb3393f518d6b5c130b61d59535fe5a989 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 22 May 2018 23:51:19 +0200 Subject: [PATCH 303/348] TableRecord documentation --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c84caf55e..0b306fd8c 100644 --- a/README.md +++ b/README.md @@ -2318,7 +2318,7 @@ protocol TableRecord { print(Place.databaseTableName) // prints "location" ``` - Subclasses of the [Record](#record-class) class can't profit from this default name, and must explicitly override their superclass's `databaseTableName` property: + Subclasses of the [Record](#record-class) class must always override their superclass's `databaseTableName` property: ```swift class Place: Record { From c93f3cda06e3efff3787b9226b16b7c542040043 Mon Sep 17 00:00:00 2001 From: pocketpixels Date: Tue, 22 May 2018 23:18:18 -0400 Subject: [PATCH 304/348] Fixed type used in 'Demographics BelongsTo Country' example I am reading this for the first time, so I might be wrong, but I strongly suspect the type in the belongsTo() call should be Country? --- Documentation/AssociationsBasics.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index ccaf0dda8..59e2b62a8 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -221,7 +221,7 @@ struct Country: TableRecord, FetchableRecord { } struct Demographics: TableRecord, FetchableRecord { - static let country = belongsTo(Demographics.self) + static let country = belongsTo(Country.self) ... } ``` @@ -1410,4 +1410,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Known Issues]: #known-issues [Future Directions]: #future-directions [Row Adapters]: ../README.md#row-adapters -[query interface requests]: ../README.md#requests \ No newline at end of file +[query interface requests]: ../README.md#requests From 051f0416a42fe4342325986569d7096c779f4227 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 May 2018 08:19:40 +0200 Subject: [PATCH 305/348] Extend the "thank you" notice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0b306fd8c..80307fcd1 100644 --- a/README.md +++ b/README.md @@ -7388,7 +7388,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [@pocketpixels](https://github.com/pocketpixels) [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From ac955873f27467073c63cb6c38cfd919699dc62f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 May 2018 08:36:29 +0200 Subject: [PATCH 306/348] Improve documentation for persistable protocol choice --- README.md | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 80307fcd1..a83125218 100644 --- a/README.md +++ b/README.md @@ -2369,9 +2369,6 @@ try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Ci ```swift protocol MutablePersistableRecord : TableRecord { - /// The name of the database table (from TableRecord) - static var databaseTableName: String { get } - /// Defines the values persisted in the database func encode(to container: inout PersistenceContainer) @@ -2390,23 +2387,22 @@ protocol PersistableRecord : MutablePersistableRecord { Yes, two protocols instead of one. Both grant exactly the same advantages. Here is how you pick one or the other: -- *If your type is a struct that mutates on insertion*, choose `MutablePersistableRecord`. - - For example, your table has an INTEGER PRIMARY KEY and you want to store the inserted id on successful insertion. Or your table has a UUID primary key, and you want to automatically generate one on insertion. +- **If your type is a class**, choose `PersistableRecord`. On top of that, implement `didInsert(with:for:)` if the database table has an auto-incremented primary key. -- Otherwise, stick with `PersistableRecord`. Particularly if your type is a class. +- **If your type is a struct, and the database table has an auto-incremented primary key**, choose `MutablePersistableRecord`, and implement `didInsert(with:for:)`. + +- **Otherwise**, choose `PersistableRecord`, and ignore `didInsert(with:for:)`. The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Date, Swift enums, etc.) are assigned to database columns. > :bulb: **Tip**: `encode(to:)` can be automatically generated when your type adopts the standard `Encodable` protocol. See [Codable Records](#codable-records) for more information. -The optional `didInsert` method lets the adopting type store its rowID after successful insertion. If your table has an INTEGER PRIMARY KEY column, you are likely to define this method. Otherwise, you can safely ignore it. It is called from a protected dispatch queue, and serialized with all database updates. +The optional `didInsert` method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates. -**To use those protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitly. For example: +**To use the persistable protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitly. For example: ```swift extension Place : MutablePersistableRecord { - /// The values persisted in the database func encode(to container: inout PersistenceContainer) { container["id"] = id @@ -7388,7 +7384,7 @@ Sample Code **Thanks** - [Pierlis](http://pierlis.com), where we write great software. -- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [@pocketpixels](https://github.com/pocketpixels) [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. +- [Vladimir Babin](https://github.com/Chiliec), [Darren Clark](https://github.com/darrenclark), [Pascal Edmond](https://github.com/pakko972), [Andrey Fidrya](https://github.com/zmeyc), [Cristian Filipov](https://github.com/cfilipov), [Matt Greenfield](https://github.com/sobri909), [David Hart](https://github.com/hartbit), [@kluufger](https://github.com/kluufger), [Brad Lindsay](https://github.com/bfad), [@peter-ss](https://github.com/peter-ss), [Florent Pillet](http://github.com/fpillet), [@pocketpixels](https://github.com/pocketpixels), [Pierre-Loïc Raynaud](https://github.com/pierlo), [Stefano Rodriguez](https://github.com/sroddy), [Steven Schveighoffer](https://github.com/schveiguy), [@swiftlyfalling](https://github.com/swiftlyfalling), and [Kevin Wooten](https://github.com/kdubb) for their contributions, help, and feedback on GRDB. - [@aymerick](https://github.com/aymerick) and [Mathieu "Kali" Poumeyrol](https://github.com/kali) because SQL. - [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency. From eb7c98c510b168b276d3fed66800737b26a99c49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 23 May 2018 12:11:43 +0200 Subject: [PATCH 307/348] Fix GRDB3 SPM doc --- Documentation/GRDB2MigrationGuide.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GRDB2MigrationGuide.md b/Documentation/GRDB2MigrationGuide.md index bcb4cefc1..5ef3899ef 100644 --- a/Documentation/GRDB2MigrationGuide.md +++ b/Documentation/GRDB2MigrationGuide.md @@ -42,7 +42,7 @@ Update your Package.swift file: ```swift let package = Package( dependencies: [ - .package(url: "https://github.com/groue/GRDB.swift.git", branch: "GRDB3") + .package(url: "https://github.com/groue/GRDB.swift.git", .branchItem("GRDB3")) ] ) ``` From 318e7455e7b3f43519dc0a686e9d81f4e442aa61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 24 May 2018 05:56:03 +0200 Subject: [PATCH 308/348] Update Package.swift for Swift 4.1 --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index af21e70db..76aa827c5 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:4.0 +// swift-tools-version:4.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription From 0d2079df4288baf9c976f0fccaa3a660fbf5c0c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 24 May 2018 05:56:29 +0200 Subject: [PATCH 309/348] keypath-based expressions? --- TODO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/TODO.md b/TODO.md index 010fa5da5..a5076c93f 100644 --- a/TODO.md +++ b/TODO.md @@ -44,6 +44,8 @@ GRDB 3.0 let players = Player.filter(color: .red) // Possible ?? let teamPlayers = Team.players.filter(color: .red) ``` +- [ ] From vapor: How do they use [keypaths](https://docs.vapor.codes/3.0/fluent/querying/) for filtering? + Not sure From 4e73c31662d733f498de7caff5037658658c8368 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 24 May 2018 23:05:59 +0200 Subject: [PATCH 310/348] Fix documentation typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a83125218..b0a9327c9 100644 --- a/README.md +++ b/README.md @@ -4183,7 +4183,7 @@ let request = Player.all() ```swift extension Player { static func filter(color: Color) -> SQLRequest { - let request = SQLRequest( + return SQLRequest( "SELECT * FROM player WHERE color = ?" arguments: [color]) } From 366e049ddfae3b3fb0ff6fe6506ff684f851c927 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Fri, 25 May 2018 07:26:15 +0200 Subject: [PATCH 311/348] Bring GRDBDemo to GRDB 3 --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 33 ++-- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 15 +- .../GRDBDemoiOS/Base.lproj/Main.storyboard | 81 ++++----- .../{Person.swift => Player.swift} | 48 ++---- ...wift => PlayerEditionViewController.swift} | 41 ++--- ...ller.swift => PlayersViewController.swift} | 158 +++++++++--------- .../SimplePersonsViewController.swift | 114 ------------- .../SimplePlayersViewController.swift | 107 ++++++++++++ 8 files changed, 279 insertions(+), 318 deletions(-) rename DemoApps/GRDBDemoiOS/GRDBDemoiOS/{Person.swift => Player.swift} (50%) rename DemoApps/GRDBDemoiOS/GRDBDemoiOS/{PersonEditionViewController.swift => PlayerEditionViewController.swift} (67%) rename DemoApps/GRDBDemoiOS/GRDBDemoiOS/{PersonsViewController.swift => PlayersViewController.swift} (55%) delete mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift create mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 4ae785152..80062ba5e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -21,11 +21,11 @@ 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; }; 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; }; 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; - 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Person.swift */; }; + 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; }; - 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */; }; - 56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */; }; - 56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */; }; + 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; + 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; }; + 56B036251E8D9F4C003B6DA4 /* SimplePlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */; }; 56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; }; 56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ @@ -195,11 +195,11 @@ 56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 56B0361A1E8D9F38003B6DA4 /* Person.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Person.swift; sourceTree = ""; }; + 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = ""; }; - 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonEditionViewController.swift; sourceTree = ""; }; - 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersonsViewController.swift; sourceTree = ""; }; - 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePersonsViewController.swift; sourceTree = ""; }; + 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; + 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; + 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePlayersViewController.swift; sourceTree = ""; }; 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ @@ -270,7 +270,7 @@ children = ( 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, - 56B0361A1E8D9F38003B6DA4 /* Person.swift */, + 56B0361A1E8D9F38003B6DA4 /* Player.swift */, 56B0361D1E8D9F3D003B6DA4 /* Controllers */, 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */, @@ -284,9 +284,9 @@ isa = PBXGroup; children = ( 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */, - 56B0361F1E8D9F4C003B6DA4 /* PersonEditionViewController.swift */, - 56B036201E8D9F4C003B6DA4 /* PersonsViewController.swift */, - 56B036211E8D9F4C003B6DA4 /* SimplePersonsViewController.swift */, + 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, + 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */, + 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */, ); name = Controllers; sourceTree = ""; @@ -524,12 +524,12 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 56B0361C1E8D9F38003B6DA4 /* Person.swift in Sources */, + 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */, 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, - 56B036241E8D9F4C003B6DA4 /* PersonsViewController.swift in Sources */, - 56B036231E8D9F4C003B6DA4 /* PersonEditionViewController.swift in Sources */, - 56B036251E8D9F4C003B6DA4 /* SimplePersonsViewController.swift in Sources */, + 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */, + 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */, + 56B036251E8D9F4C003B6DA4 /* SimplePlayersViewController.swift in Sources */, 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -770,7 +770,6 @@ GCC_WARN_UNUSED_VARIABLE = YES; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; SWIFT_VERSION = 4.0; VALIDATE_PRODUCT = YES; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index aa51dbb34..387e0273a 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -25,14 +25,14 @@ struct AppDatabase { static var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - migrator.registerMigration("createPersons") { db in + migrator.registerMigration("createPlayerTable") { db in // Create a table // See https://github.com/groue/GRDB.swift#create-tables - try db.create(table: "persons") { t in - // An integer primary key auto-generates unique IDs - t.column("id", .integer).primaryKey() + try db.create(table: "player") { t in + // An integer primary key auto-increment unique IDs + t.autoIncrementedPrimaryKey("id") - // Sort person names in a localized case insensitive fashion by default + // Sort player names in a localized case insensitive fashion by default // See https://github.com/groue/GRDB.swift/#unicode t.column("name", .text).notNull().collate(.localizedCaseInsensitiveCompare) @@ -41,9 +41,10 @@ struct AppDatabase { } migrator.registerMigration("fixtures") { db in - // Populate the persons table with random data + // Populate the player table with random data for _ in 0..<8 { - try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard index 12b3c428d..1d7751c9f 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard @@ -1,8 +1,11 @@ - - + + + + + - + @@ -10,28 +13,27 @@ - + - - + + - + - + @@ -53,17 +55,17 @@ - + - + - + @@ -72,13 +74,14 @@ - + - + + @@ -94,13 +97,14 @@ - + - + + @@ -124,12 +128,12 @@ - + - + @@ -160,17 +164,16 @@ - + - + @@ -180,17 +183,16 @@ - + - + @@ -218,7 +220,7 @@ - + @@ -234,7 +236,7 @@ - + @@ -248,28 +250,27 @@ - + - - + + - + - + @@ -295,7 +296,7 @@ - + @@ -305,6 +306,6 @@ - + diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift similarity index 50% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift rename to DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 539325d6e..12dd28dbc 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Person.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,49 +1,29 @@ import GRDB -class Person: Record { +struct Player: Codable { var id: Int64? var name: String var score: Int - - init(name: String, score: Int) { - self.name = name - self.score = score - super.init() - } - - // MARK: Record overrides - - override class var databaseTableName: String { - return "persons" - } - - required init(row: Row) { - id = row["id"] - name = row["name"] - score = row["score"] - super.init(row: row) - } - - override func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["name"] = name - container["score"] = score - } - - override func didInsert(with rowID: Int64, for column: String?) { +} + +// MARK: - Player as a GRDB record + +extension Player: FetchableRecord, MutablePersistableRecord { + mutating func didInsert(with rowID: Int64, for column: String?) { id = rowID } - - // MARK: Random - +} + +// MARK: - Random Player + +extension Player { private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"] - class func randomName() -> String { + static func randomName() -> String { return names[Int(arc4random_uniform(UInt32(names.count)))] } - class func randomScore() -> Int { + static func randomScore() -> Int { return 10 * Int(arc4random_uniform(101)) } - } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift similarity index 67% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift rename to DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift index 3711e6920..bf7020e7c 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonEditionViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift @@ -1,14 +1,13 @@ import UIKit -protocol PersonEditionViewControllerDelegate: class { - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) +protocol PlayerEditionViewControllerDelegate: class { + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) } -class PersonEditionViewController: UITableViewController { - weak var delegate: PersonEditionViewControllerDelegate? - var person: Person! { didSet { configureView() } } - var cancelButtonHidden: Bool = false { didSet { configureView() } } - var commitButtonHidden: Bool = false { didSet { configureView() } } +class PlayerEditionViewController: UITableViewController { + weak var delegate: PlayerEditionViewControllerDelegate? + var player: Player! + var commitButtonHidden: Bool = false @IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem! @IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem! @@ -18,10 +17,8 @@ class PersonEditionViewController: UITableViewController { @IBOutlet fileprivate weak var scoreTextField: UITextField! func applyChanges() { - if let name = nameTextField.text, !name.isEmpty { - person.name = name - } - person.score = scoreTextField.text.flatMap { Int($0) } ?? 0 + player.name = nameTextField.text ?? "" + player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 } override func viewDidLoad() { @@ -30,24 +27,18 @@ class PersonEditionViewController: UITableViewController { } private func configureView() { - guard isViewLoaded else { return } - - nameTextField.text = person.name - if person.score == 0 && person.id == nil { + nameTextField.text = player.name + if player.score == 0 && player.id == nil { scoreTextField.text = "" } else { - scoreTextField.text = "\(person.score)" + scoreTextField.text = "\(player.score)" } - if cancelButtonHidden { + if commitButtonHidden { navigationItem.leftBarButtonItem = nil - } else { - navigationItem.leftBarButtonItem = cancelBarButtonItem - } - - if cancelButtonHidden { navigationItem.rightBarButtonItem = nil } else { + navigationItem.leftBarButtonItem = cancelBarButtonItem navigationItem.rightBarButtonItem = commitBarButtonItem } } @@ -56,7 +47,7 @@ class PersonEditionViewController: UITableViewController { // MARK: - Navigation -extension PersonEditionViewController { +extension PlayerEditionViewController { override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { // Force keyboard to dismiss early @@ -69,7 +60,7 @@ extension PersonEditionViewController { if parent == nil { // Self is popping from its navigation controller - delegate?.personEditionControllerDidComplete(self) + delegate?.playerEditionControllerDidComplete(self) } } @@ -78,7 +69,7 @@ extension PersonEditionViewController { // MARK: - Form -extension PersonEditionViewController: UITextFieldDelegate { +extension PlayerEditionViewController: UITextFieldDelegate { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift similarity index 55% rename from DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift rename to DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index d927417fa..bc40e9297 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -1,19 +1,19 @@ import UIKit import GRDB -class PersonsViewController: UITableViewController { - var personsController: FetchedRecordsController! +class PlayersViewController: UITableViewController { + var playersController: FetchedRecordsController! override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPerson), + UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPlayer), editButtonItem ] - personsController = try! FetchedRecordsController(dbQueue, request: personsSortedByScore) - personsController.trackChanges( + playersController = try! FetchedRecordsController(dbQueue, request: playersSortedByScore) + playersController.trackChanges( willChange: { [unowned self] _ in self.tableView.beginUpdates() }, @@ -46,7 +46,7 @@ class PersonsViewController: UITableViewController { didChange: { [unowned self] _ in self.tableView.endUpdates() }) - try! personsController.performFetch() + try! playersController.performFetch() configureToolbar() } @@ -60,54 +60,51 @@ class PersonsViewController: UITableViewController { // MARK: - Navigation -extension PersonsViewController : PersonEditionViewControllerDelegate { +extension PlayersViewController : PlayerEditionViewControllerDelegate { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPerson" { - let person = personsController.record(at: tableView.indexPathForSelectedRow!) - let controller = segue.destination as! PersonEditionViewController - controller.title = person.name - controller.person = person - controller.delegate = self // we will save person when back button is tapped - controller.cancelButtonHidden = true + if segue.identifier == "EditPlayer" { + let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.delegate = self // we will save player when back button is tapped controller.commitButtonHidden = true } - else if segue.identifier == "NewPerson" { + else if segue.identifier == "NewPlayer" { setEditing(false, animated: true) let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PersonEditionViewController - controller.title = "New Person" - controller.person = Person(name: "", score: 0) + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) } } - @IBAction func addPerson(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPerson", sender: sender) + @IBAction func addPlayer(_ sender: AnyObject?) { + performSegue(withIdentifier: "NewPlayer", sender: sender) } - @IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: cancel button was tapped + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: cancel button was tapped } - @IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: commit button was tapped - let controller = segue.source as! PersonEditionViewController + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: commit button was tapped + let controller = segue.source as! PlayerEditionViewController + commitPlayerEdition(from: controller) + } + + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { + // Player edition: back button was tapped + commitPlayerEdition(from: controller) + } + + private func commitPlayerEdition(from controller: PlayerEditionViewController) { controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } - - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) { - // Person edition: back button was tapped - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) + var player = controller.player! + if !player.name.isEmpty { + try! dbQueue.write { db in + try player.save(db) } } } @@ -116,32 +113,32 @@ extension PersonsViewController : PersonEditionViewControllerDelegate { // MARK: - UITableViewDataSource -extension PersonsViewController { +extension PlayersViewController { func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let person = personsController.record(at: indexPath) - cell.textLabel?.text = person.name - cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point" + let player = playersController.record(at: indexPath) + cell.textLabel?.text = player.name + cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" } override func numberOfSections(in tableView: UITableView) -> Int { - return personsController.sections.count + return playersController.sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return personsController.sections[section].numberOfRecords + return playersController.sections[section].numberOfRecords } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath) + let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) configure(cell, at: indexPath) return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - // Delete the person - let person = personsController.record(at: indexPath) - try! dbQueue.inDatabase { db in - _ = try person.delete(db) + // Delete the player + let player = playersController.record(at: indexPath) + try! dbQueue.write { db in + _ = try player.delete(db) } } } @@ -149,7 +146,7 @@ extension PersonsViewController { // MARK: - FetchedRecordsController Demo -extension PersonsViewController { +extension PlayersViewController { fileprivate func configureToolbar() { toolbarItems = [ @@ -163,23 +160,22 @@ extension PersonsViewController { @IBAction func sortByName() { setEditing(false, animated: true) - try! personsController.setRequest(personsSortedByName) + try! playersController.setRequest(playersSortedByName) } @IBAction func sortByScore() { setEditing(false, animated: true) - try! personsController.setRequest(personsSortedByScore) + try! playersController.setRequest(playersSortedByScore) } @IBAction func randomizeScores() { setEditing(false, animated: true) - try! dbQueue.inTransaction { db in - for person in try Person.fetchAll(db) { - person.score = Person.randomScore() - try person.update(db) + try! dbQueue.write { db in + for var player in try Player.fetchAll(db) { + player.score = Player.randomScore() + try player.update(db) } - return .commit } } @@ -188,33 +184,33 @@ extension PersonsViewController { for _ in 0..<50 { DispatchQueue.global().async { - try! dbQueue.inTransaction { db in - if try Person.fetchCount(db) == 0 { - // Insert persons + try! dbQueue.write { db in + if try Player.fetchCount(db) == 0 { + // Insert players for _ in 0..<8 { - try Person(name: Person.randomName(), score: Person.randomScore()).insert(db) + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) } } else { - // Insert a person + // Insert a player if arc4random_uniform(2) == 0 { - let person = Person(name: Person.randomName(), score: Person.randomScore()) - try person.insert(db) + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) } - // Delete a person + // Delete a player if arc4random_uniform(2) == 0 { - if let person = try Person.order(sql: "RANDOM()").fetchOne(db) { - try person.delete(db) + if let player = try Player.order(sql: "RANDOM()").fetchOne(db) { + try player.delete(db) } } - // Update some persons - for person in try Person.fetchAll(db) { + // Update some players + for var player in try Player.fetchAll(db) { if arc4random_uniform(2) == 0 { - person.score = Person.randomScore() - try person.update(db) + player.score = Player.randomScore() + try player.update(db) } } } - return .commit } } } @@ -223,12 +219,12 @@ extension PersonsViewController { // https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3 private extension Selector { - static let addPerson = #selector(PersonsViewController.addPerson(_:)) - static let sortByName = #selector(PersonsViewController.sortByName) - static let sortByScore = #selector(PersonsViewController.sortByScore) - static let randomizeScores = #selector(PersonsViewController.randomizeScores) - static let stressTest = #selector(PersonsViewController.stressTest) + static let addPlayer = #selector(PlayersViewController.addPlayer(_:)) + static let sortByName = #selector(PlayersViewController.sortByName) + static let sortByScore = #selector(PlayersViewController.sortByScore) + static let randomizeScores = #selector(PlayersViewController.randomizeScores) + static let stressTest = #selector(PlayersViewController.stressTest) } -private let personsSortedByName = Person.order(Column("name")) -private let personsSortedByScore = Person.order(Column("score").desc, Column("name")) +private let playersSortedByName = Player.order(Column("name")) +private let playersSortedByScore = Player.order(Column("score").desc, Column("name")) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift deleted file mode 100644 index 8cd4c0e82..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePersonsViewController.swift +++ /dev/null @@ -1,114 +0,0 @@ -import UIKit -import GRDB - -class SimplePersonsViewController: UITableViewController { - var persons: [Person]! - - override func viewDidLoad() { - super.viewDidLoad() - - navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePersonsViewController.addPerson(_:))), - editButtonItem - ] - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - loadPersons() - tableView.reloadData() - } - - private func loadPersons() { - persons = try! dbQueue.inDatabase { db in - try Person.order(Column("score").desc, Column("name")).fetchAll(db) - } - } -} - - -// MARK: - Navigation - -extension SimplePersonsViewController : PersonEditionViewControllerDelegate { - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPerson" { - let person = persons[tableView.indexPathForSelectedRow!.row] - let controller = segue.destination as! PersonEditionViewController - controller.title = person.name - controller.person = person - controller.delegate = self // we will save person when back button is tapped - controller.cancelButtonHidden = true - controller.commitButtonHidden = true - } - else if segue.identifier == "NewPerson" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PersonEditionViewController - controller.title = "New Person" - controller.person = Person(name: "", score: 0) - } - } - - @IBAction func addPerson(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPerson", sender: sender) - } - - @IBAction func cancelPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: cancel button was tapped - } - - @IBAction func commitPersonEdition(_ segue: UIStoryboardSegue) { - // Person creation: commit button was tapped - let controller = segue.source as! PersonEditionViewController - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } - - func personEditionControllerDidComplete(_ controller: PersonEditionViewController) { - // Person edition: back button was tapped - controller.applyChanges() - let person = controller.person! - if !person.name.isEmpty { - try! dbQueue.inDatabase { db in - try person.save(db) - } - } - } -} - - -// MARK: - UITableViewDataSource - -extension SimplePersonsViewController { - func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let person = persons[indexPath.row] - cell.textLabel?.text = person.name - cell.detailTextLabel?.text = abs(person.score) > 1 ? "\(person.score) points" : "0 point" - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return persons.count - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Person", for: indexPath) - configure(cell, at: indexPath) - return cell - } - - override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - // Delete the person - let person = persons[indexPath.row] - try! dbQueue.inDatabase { db in - _ = try person.delete(db) - } - persons.remove(at: indexPath.row) - tableView.deleteRows(at: [indexPath], with: .fade) - } -} diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift new file mode 100644 index 000000000..aa47ea3da --- /dev/null +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift @@ -0,0 +1,107 @@ +import UIKit +import GRDB + +class SimplePlayersViewController: UITableViewController { + var players: [Player]! + + override func viewDidLoad() { + super.viewDidLoad() + + navigationItem.rightBarButtonItems = [ + UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePlayersViewController.addPlayer(_:))), + editButtonItem + ] + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + players = try! dbQueue.read { db in + try Player.order(Column("score").desc, Column("name")).fetchAll(db) + } + tableView.reloadData() + } +} + + +// MARK: - Navigation + +extension SimplePlayersViewController : PlayerEditionViewControllerDelegate { + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "EditPlayer" { + let player = players[tableView.indexPathForSelectedRow!.row] + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.delegate = self // see playerEditionControllerDidComplete + controller.commitButtonHidden = true + } + else if segue.identifier == "NewPlayer" { + setEditing(false, animated: true) + let navigationController = segue.destination as! UINavigationController + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) + } + } + + @IBAction func addPlayer(_ sender: AnyObject?) { + performSegue(withIdentifier: "NewPlayer", sender: sender) + } + + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: cancel button was tapped + } + + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: commit button was tapped + let controller = segue.source as! PlayerEditionViewController + commitPlayerEdition(from: controller) + } + + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { + // Player edition: back button was tapped + commitPlayerEdition(from: controller) + } + + private func commitPlayerEdition(from controller: PlayerEditionViewController) { + controller.applyChanges() + var player = controller.player! + if !player.name.isEmpty { + try! dbQueue.write { db in + try player.save(db) + } + } + } +} + + +// MARK: - UITableViewDataSource + +extension SimplePlayersViewController { + func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { + let player = players[indexPath.row] + cell.textLabel?.text = player.name + cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" + } + + override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + return players.count + } + + override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) + configure(cell, at: indexPath) + return cell + } + + override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { + // Delete the player + let player = players[indexPath.row] + try! dbQueue.write { db in + _ = try player.delete(db) + } + players.remove(at: indexPath.row) + tableView.deleteRows(at: [indexPath], with: .fade) + } +} From e9cbbe29031f3c62f923525075be3cca42674824 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 28 May 2018 14:25:08 +0200 Subject: [PATCH 312/348] Documentation --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b0a9327c9..5818721e1 100644 --- a/README.md +++ b/README.md @@ -2592,7 +2592,7 @@ struct Place: Codable { extension Place: FetchableRecord, PersistableRecord { } ``` -GRDB ships with support for nested codable records, but this is a more complex topic. See [Joined Queries Support](#joined-queries-support) for more information. +GRDB ships with support for nested codable records, but this is a more complex topic. See [Associations](Documentation/AssociationsBasics.md) for more information. As documented with the [PersistableRecord] protocol, have your struct records use MutablePersistableRecord instead of PersistableRecord when they store their automatically incremented row id: @@ -3334,7 +3334,7 @@ try db.create(table: "example", temporary: true, ifNotExists: true) { t in > :bulb: **Tip**: database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'. > -> This will help you using the new [Associations](Documentation/AssociationsBasics.md) feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. +> This will help you using [Associations](Documentation/AssociationsBasics.md) when you need them. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration. **Add regular columns** with their name and eventual type (text, integer, double, numeric, boolean, blob, date and datetime) - see [SQLite data types](https://www.sqlite.org/datatype3.html): From 8a4fbcc725d13cab82afde95c58b4c8c4f69388a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 08:19:49 +0200 Subject: [PATCH 313/348] Associations documentation: avoid explicit databaseTableName when possible --- Documentation/AssociationsBasics.md | 35 ++++++++++++++--------------- 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 59e2b62a8..f585338ee 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -281,17 +281,13 @@ Make them look like Swift identifiers: `book`, `author`, `postalAddress`. This convention helps fetching values from associations. It is used, for example, in the sample code below, where we load all pairs of books along with their authors: ```swift -// The Book record -struct Book: FetchableRecord, TableRecord { - static let databaseTableName = "book" - static let author = belongsTo(Author.self) - ... -} - // The Author record struct Author: FetchableRecord, TableRecord { - static let databaseTableName = "author" - ... +} + +// The Book record +struct Book: FetchableRecord, TableRecord { + static let author = belongsTo(Author.self) } // A pair made of a book and its author @@ -304,13 +300,21 @@ let request = Book.including(optional: Book.author) let bookInfos = BookInfo.fetchAll(db, request) ``` -This sample code only works if the database table for authors is called "author". This name "author" is the key that helps BookInfo initialize its `author` property. +This sample code only works if the database table for authors is called "author". The name "author" is the key that helps BookInfo initialize its `author` property. For your convenience, "author" is also the default value of the `Author.databaseTableName` property (see the [TableRecord] protocol). If the database schema does not follow this convention, and has, for example, database tables named with plural names (`authors` and `books`), you can still use associations. But you need to help row consumption by providing the required key: ```swift +// Setup for a customized table name + +struct Author: FetchableRecord, TableRecord { + // Customized table name + static let databaseTableName = "authors" +} + struct Book: FetchableRecord, TableRecord { - static let author = belongsTo(Author.self).forKey("author") // <- + // Explicit association key + static let author = belongsTo(Author.self, key: "author") } ``` @@ -356,12 +360,10 @@ Following this convention lets you write, for example: ```swift struct Book: FetchableRecord, TableRecord { - static let databaseTableName = "book" static let author = belongsTo(Author.self) } struct Author: FetchableRecord, TableRecord { - static let databaseTableName = "author" } ``` @@ -416,12 +418,10 @@ Following this convention lets you write, for example: ```swift struct Country: FetchableRecord, TableRecord { - static let databaseTableName = "country" static let demographics = hasOne(Demographics.self) } struct Demographics: FetchableRecord, TableRecord { - static let databaseTableName = "demographics" } ``` @@ -475,11 +475,9 @@ Following this convention lets you write, for example: ```swift struct Book: FetchableRecord, TableRecord { - static let databaseTableName = "book" } struct Author: FetchableRecord, TableRecord { - static let databaseTableName = "author" static let books = hasMany(Book.self) } ``` @@ -1194,7 +1192,7 @@ Association keys can also be defined right into the definition of the associatio ```swift struct Book { - static let author = belongsTo(Person.self).forKey("author") + static let author = belongsTo(Person.self, key: "author") } let request = Book @@ -1411,3 +1409,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Future Directions]: #future-directions [Row Adapters]: ../README.md#row-adapters [query interface requests]: ../README.md#requests +[TableRecord]: ../README.md#tablerecord-protocol From 6cdcd97912b8334d1153d6efdfc754cd83f856e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 08:21:07 +0200 Subject: [PATCH 314/348] Associations documentation --- Documentation/AssociationsBasics.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index f585338ee..2f1d5e907 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -305,7 +305,7 @@ This sample code only works if the database table for authors is called "author" If the database schema does not follow this convention, and has, for example, database tables named with plural names (`authors` and `books`), you can still use associations. But you need to help row consumption by providing the required key: ```swift -// Setup for a customized table name +// Setup for customized table names struct Author: FetchableRecord, TableRecord { // Customized table name @@ -313,6 +313,9 @@ struct Author: FetchableRecord, TableRecord { } struct Book: FetchableRecord, TableRecord { + // Customized table name + static let databaseTableName = "books" + // Explicit association key static let author = belongsTo(Author.self, key: "author") } From d601e06f2596c1811962a070afee060949287390 Mon Sep 17 00:00:00 2001 From: David Hart Date: Thu, 31 May 2018 17:07:23 +0200 Subject: [PATCH 315/348] Fix buffer overflow in vsscanf date parsing --- GRDB/Core/Support/Foundation/SQLiteDateParser.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 06813ca5b..ba2f83814 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -55,7 +55,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([yearP, monthP, dayP, hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%10s", pointer) + vsscanf(cString, "%4d-%2d-%2d%*1[ T]%2d:%2d:%2d.%9s", pointer) } } } @@ -100,7 +100,7 @@ class SQLiteDateParser { withUnsafeMutablePointer(to: &parserComponents.second) { secondP in parserComponents.nanosecond.withUnsafeMutableBufferPointer { nanosecondBuffer in withVaList([hourP, minuteP, secondP, nanosecondBuffer.baseAddress!]) { pointer in - vsscanf(cString, "%2d:%2d:%2d.%10s", pointer) + vsscanf(cString, "%2d:%2d:%2d.%9s", pointer) } } } From ead89420c4eae8e02ec907e10f555ea063dc8b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 17:37:46 +0200 Subject: [PATCH 316/348] Avoid undefined behavior (UnsafePointer documentation is scary) --- .../Core/Support/Foundation/DatabaseDateComponents.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index 518aaf024..92e0b9288 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -75,9 +75,14 @@ public struct DatabaseDateComponents : DatabaseValueConvertible, StatementColumn /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. public init(sqliteStatement: SQLiteStatement, index: Int32) { - let cString = UnsafePointer(OpaquePointer(sqlite3_column_text(sqliteStatement, index)!)) + guard let cString = sqlite3_column_text(sqliteStatement, index) else { + fatalError("could not convert database value \(DatabaseValue(sqliteStatement: sqliteStatement, index: index)) to DatabaseDateComponents") + } let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen - guard let components = SQLiteDateParser().components(cString: cString, length: length) else { + let optionalComponents = cString.withMemoryRebound(to: Int8.self, capacity: length + 1 /* trailing \0 */) { cString in + SQLiteDateParser().components(cString: cString, length: length) + } + guard let components = optionalComponents else { fatalError("could not convert database value \(String(cString: cString)) to DatabaseDateComponents") } self.dateComponents = components.dateComponents From 16af4513d6ccd849a197dc441ef3d779230adb17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 22:11:18 +0200 Subject: [PATCH 317/348] Associations documentatiion --- Documentation/AssociationsBasics.md | 37 ++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 2f1d5e907..775d3f47d 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -137,11 +137,14 @@ Each one of the three types of associations is appropriate for a particular data The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such as each instance of the declaring record "belongs to" an instance of the other record. -For example, if your application includes authors and books, and each book is assigned its author, you'd declare the association this way: +For example, if your application includes authors and books, and each book is assigned its author, you'd declare the `Book.author` association as below, with its companion property: ```swift struct Book: TableRecord { static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } ... } @@ -150,6 +153,13 @@ struct Author: TableRecord { } ``` +The `Book.author` association will help you build [association requests]. The property lets you fetch a book's author: + +```swift +let book: Book = ... +let author = try book.author.fetchOne(db) // Author? +``` + The **BelongsTo** association between a book and its author needs that the database table for books has a column that points to the table for authors: ![BelongsToSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/BelongsToSchema.svg) @@ -161,11 +171,14 @@ See [Convention for the BelongsTo Association] for some sample code that defines The **HasOne** association also sets up a one-to-one connection from a record type to another record type, but with different semantics, and underlying database schema. It is usually used when an entity has been denormalized into two database tables. -For example, if your application has one database table for countries, and another for their demographic profiles, you'd declare the association this way: +For example, if your application has one database table for countries, and another for their demographic profiles, you'd declare the `Country.demographics` association as below, with its companion property: ```swift struct Country: TableRecord { static let demographics = hasOne(Demographics.self) + var demographics: QueryInterfaceRequest { + return request(for: Country.demographics) + } ... } @@ -174,6 +187,13 @@ struct Demographics: TableRecord { } ``` +The `Country.demographics` association will help you build [association requests]. The property lets you fetch a country's demographic profile: + +```swift +let country: Country = ... +let demographics = try country.demographics.fetchOne(db) // Demographics? +``` + The **HasOne** association between a country and its demographics needs that the database table for demographics has a column that points to the table for countries: ![HasOneSchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasOneSchema.svg) @@ -185,11 +205,14 @@ See [Convention for the HasOne Association] for some sample code that defines th The **HasMany** association indicates a one-to-many connection between two record types, such as each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association. -For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the association this way: +For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the `Author.books` association as below, with its companion property: ```swift struct Author: TableRecord { static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } } struct Book: TableRecord { @@ -197,6 +220,13 @@ struct Book: TableRecord { } ``` +The `Author.books` association will help you build [association requests]. The property lets you fetch an author's books: + +```swift +let author: Author = ... +let books = try author.books.fetchAll(db) // [Book] +``` + The **HasMany** association between an author and its books needs that the database table for books has a column that points to the table for authors: ![HasManySchema](https://cdn.rawgit.com/groue/GRDB.swift/GRDB3/Documentation/Images/Associations2/HasManySchema.svg) @@ -1413,3 +1443,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [Row Adapters]: ../README.md#row-adapters [query interface requests]: ../README.md#requests [TableRecord]: ../README.md#tablerecord-protocol +[association requests]: #building-requests-from-associations From 62a434f89898e4b0dc6268978c5178286ce811d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 22:21:00 +0200 Subject: [PATCH 318/348] Associations documentatiion --- Documentation/AssociationsBasics.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 775d3f47d..a0206d0d5 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -656,6 +656,16 @@ let author: Author = ... let books = try author.books.fetchAll(db) // [Book] ``` +Requests for associated records can be filtered and ordered like all [query interface requests]: + +```swift +let novels = try author + .books + .filter(Column("kind") == BookKind.novel) + .order(Column("publicationDate").desc) + .fetchAll(db) +``` + Those requests can also turn out useful when you want to track their changes with database observation tools like [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): ```swift From f2b46963bd6c8ea43c8b69af554841670e661997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 22:35:58 +0200 Subject: [PATCH 319/348] minor --- Documentation/AssociationsBasics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index a0206d0d5..3eedba3c4 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -662,7 +662,7 @@ Requests for associated records can be filtered and ordered like all [query inte let novels = try author .books .filter(Column("kind") == BookKind.novel) - .order(Column("publicationDate").desc) + .order(Column("publishDate").desc) .fetchAll(db) ``` From 003020dd29eaf36fd4234485c2f32024eb4e3289 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 22:52:32 +0200 Subject: [PATCH 320/348] Associations documentatiion --- Documentation/AssociationsBasics.md | 9 +++++++++ GRDB/QueryInterface/SQLGenerationContext.swift | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 3eedba3c4..eb162190b 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -1006,6 +1006,15 @@ let request = Book.aliased(bookAlias) .filter(sql: "myBook.publishDate >= myAuthor.deathDate") ``` +> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error: +> +> ```swift +> // Fatal error: A TableAlias most not be used to refer to multiple tables +> let alias = TableAlias() +> let books = Book.aliased(alias)... +> let people = Person.aliased(alias)... +> ``` + Fetching Values from Associations ================================= diff --git a/GRDB/QueryInterface/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGenerationContext.swift index 1fd7830bf..2fbdbff00 100644 --- a/GRDB/QueryInterface/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGenerationContext.swift @@ -204,10 +204,16 @@ public class TableAlias: Hashable { case .undefined(let userName): self.impl = .table(tableName: tableName, userName: userName) case .table(tableName: let initialTableName, userName: _): + // It is a programmer error to reuse the same TableAlias for + // multiple tables. + // + // // Don't do that + // let alias = TableAlias() + // let books = Book.aliased(alias)... + // let authors = Author.aliased(alias)... GRDBPrecondition( tableName.lowercased() == initialTableName.lowercased(), - // Likely a GRDB bug - "Can't change table name of a table alias") + "A TableAlias most not be used to refer to multiple tables") case .proxy(let base): base.setTableName(tableName) } @@ -241,6 +247,12 @@ extension Array where Element == TableAlias { fileprivate var resolvedNames: [TableAlias: String] { // It is a programmer error to reuse the same TableAlias for // multiple tables. + // + // // Don't do that + // let alias = TableAlias() + // let request = Book + // .including(required: Book.author.aliased(alias)...) + // .including(required: Book.author.aliased(alias)...) GRDBPrecondition(count == Set(self).count, "A TableAlias most not be used to refer to multiple tables") let groups = Dictionary(grouping: self) { From cfba53e5861adee9c3bbf8859dd94f731b01cc64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 31 May 2018 22:54:13 +0200 Subject: [PATCH 321/348] Associations documentatiion --- Documentation/AssociationsBasics.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index eb162190b..3dd949da6 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -993,17 +993,17 @@ let request = Book **Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it: ```swift -// SELECT myBook.* -// FROM book myBook -// JOIN person myAuthor ON myAuthor.id = myBook.authorId -// AND myAuthor.countryCode = 'FR' -// WHERE myBook.publishDate >= myAuthor.deathDate -let bookAlias = TableAlias(name: "myBook") -let authorAlias = TableAlias(name: "myAuthor") +// SELECT b.* +// FROM book b +// JOIN person a ON a.id = b.authorId +// AND a.countryCode = 'FR' +// WHERE b.publishDate >= a.deathDate +let bookAlias = TableAlias(name: "b") +let authorAlias = TableAlias(name: "a") let request = Book.aliased(bookAlias) .joining(required: Book.author.aliased(authorAlias) - .filter(sql: "myAuthor.countryCode = ?", arguments: ["FR"])) - .filter(sql: "myBook.publishDate >= myAuthor.deathDate") + .filter(sql: "a.countryCode = ?", arguments: ["FR"])) + .filter(sql: "b.publishDate >= a.deathDate") ``` > :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error: From f8b7156b481428c27b158e73d7106134e1d4c5c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Jun 2018 13:23:31 +0200 Subject: [PATCH 322/348] Simplify demo application --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 20 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift | 11 +- .../GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift | 2 +- .../AppIcon.appiconset/Contents.json | 20 -- .../GRDBDemoiOS/Base.lproj/Main.storyboard | 145 ++------- .../GRDBDemoiOS/DemoViewController.swift | 10 - DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch | Bin 262144 -> 0 bytes DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist | 6 +- DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift | 13 +- .../PlayerEditionViewController.swift | 30 +- .../GRDBDemoiOS/PlayersViewController.swift | 284 ++++++++++-------- .../SimplePlayersViewController.swift | 107 ------- 12 files changed, 210 insertions(+), 438 deletions(-) delete mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift delete mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch delete mode 100644 DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 80062ba5e..22548585a 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -22,10 +22,8 @@ 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; }; 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; - 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */; }; 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; }; - 56B036251E8D9F4C003B6DA4 /* SimplePlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */; }; 56B0365E1E8D9FB1003B6DA4 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; }; 56B0365F1E8D9FB1003B6DA4 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ @@ -196,10 +194,8 @@ 56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; - 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DemoViewController.swift; sourceTree = ""; }; 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = ""; }; - 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SimplePlayersViewController.swift; sourceTree = ""; }; 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../GRDB.xcodeproj; sourceTree = ""; }; /* End PBXFileReference section */ @@ -271,7 +267,8 @@ 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, 56B0361A1E8D9F38003B6DA4 /* Player.swift */, - 56B0361D1E8D9F3D003B6DA4 /* Controllers */, + 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, + 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */, 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */, 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */, @@ -280,17 +277,6 @@ path = GRDBDemoiOS; sourceTree = ""; }; - 56B0361D1E8D9F3D003B6DA4 /* Controllers */ = { - isa = PBXGroup; - children = ( - 56B0361E1E8D9F4C003B6DA4 /* DemoViewController.swift */, - 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, - 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */, - 56B036211E8D9F4C003B6DA4 /* SimplePlayersViewController.swift */, - ); - name = Controllers; - sourceTree = ""; - }; 56B036271E8D9F79003B6DA4 /* Products */ = { isa = PBXGroup; children = ( @@ -529,8 +515,6 @@ 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, 56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */, 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */, - 56B036251E8D9F4C003B6DA4 /* SimplePlayersViewController.swift in Sources */, - 56B036221E8D9F4C003B6DA4 /* DemoViewController.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift index 387e0273a..dd39c279e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift @@ -25,12 +25,12 @@ struct AppDatabase { static var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() - migrator.registerMigration("createPlayerTable") { db in + migrator.registerMigration("createPlayer") { db in // Create a table // See https://github.com/groue/GRDB.swift#create-tables try db.create(table: "player") { t in - // An integer primary key auto-increment unique IDs - t.autoIncrementedPrimaryKey("id") + // An integer primary key auto-generates unique IDs + t.column("id", .integer).primaryKey() // Sort player names in a localized case insensitive fashion by default // See https://github.com/groue/GRDB.swift/#unicode @@ -41,13 +41,13 @@ struct AppDatabase { } migrator.registerMigration("fixtures") { db in - // Populate the player table with random data + // Populate the players table with random data for _ in 0..<8 { var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) try player.insert(db) } } - + // // Migrations for future application versions will be inserted here: // migrator.registerMigration(...) { db in // ... @@ -56,3 +56,4 @@ struct AppDatabase { return migrator } } + diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift index 068caa82a..eaa484e98 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift @@ -18,7 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent("db.sqlite") dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path) - + // Be a nice iOS citizen, and don't consume too much memory // See https://github.com/groue/GRDB.swift/#memory-management dbQueue.setupMemoryManagement(in: application) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json index b51e72289..397149f3e 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,15 +1,5 @@ { "images" : [ - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "2x" - }, - { - "idiom" : "iphone", - "size" : "20x20", - "scale" : "3x" - }, { "idiom" : "iphone", "size" : "29x29", @@ -42,16 +32,6 @@ "filename" : "Icon-60@3x.png", "scale" : "3x" }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "1x" - }, - { - "idiom" : "ipad", - "size" : "20x20", - "scale" : "2x" - }, { "idiom" : "ipad", "size" : "29x29", diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard index 1d7751c9f..c74e6a1c6 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Base.lproj/Main.storyboard @@ -10,62 +10,10 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -128,12 +76,12 @@ - + - + @@ -150,70 +98,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + @@ -229,7 +114,7 @@ - + @@ -240,17 +125,17 @@ - + - + - + @@ -267,6 +152,7 @@ + - + - diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift deleted file mode 100644 index 88bff6034..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/DemoViewController.swift +++ /dev/null @@ -1,10 +0,0 @@ -import UIKit - -class DemoViewController: UITableViewController { - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(true) - navigationController?.isToolbarHidden = true - navigationItem.backBarButtonItem = UIBarButtonItem(title: "Demo", style: .plain, target: nil, action: nil) - } -} diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Icon.sketch deleted file mode 100644 index f2138aaa9edecabdd5d5977897d0a108a7b9ffb2..0000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=ygRVdR<|z6;tr;id@{# z3OBT3IjdR2b=<}s=y`>^T5*Wid5gDsm(MuLSD1Z;d@C*m;Y!(7%C@pR6=+E-+R&bk z_@-C7gOzfv%wq*Na3eQ!E8btZkGna7cUIczDl@Mthq+fpVdhm;sYYuCk-=h?u#Aw!uYQz+JQ;)qr3le;fsPB@R)IYhRHPEo z$WS0dK@DUm&|!fN3+j`~IL0#(H&>vSg1Ojr!9tdyrvlv+$W*YIZRn`Lz6G4aGaC8U=wpp+ zYo;)r8F+teiOWH_z7BopO9}%R%ut4t&T_8e z0d%%rhV_5(4<|W|zSdvhVi0a)FfmyvWPE z${V2{NDH=RMho6e)-O_%Uyp*IUlQ;zafz%3Q(q;L>=C>+LcGVtvb z`gRI)n9fWVuo!zP)J@@Pu0bD#w{bfMc#>!E-4q^1KZW`!)KB5(e2IM)eiwwB%TSgG zqNq$X)rp}8bGVVmIf_5O`5TU*=gmL!8@~tP7Jqh2O9n6ncev$29^oKQIlyG@%u3acf)M+19S;a_e{|pwF#( z+^WN^>)6O9HnWSX*n=Lo-o@SQM~_lqY>}CY%v9vtDbjV(i2C8DWD z4Z7ntw)LhTso43p!3;qU+w#%xwjDgmW7z#Rd*5d7+nz&?ZE|dLKihS=T@Tyc&vtWd zUxDA)uD|VTv9s+Pu($1-*@9WOZ(}EB-hLH(ID}no{{ZuCx3BGA@I62A3xDz#r#Xjt zcbIiYNL}n_M+2IXL|;-c>khN-u=5=w8O0Q)Gn3iKv|~GR?XZU(GVQpI>$#l+=wpX$ zJ3iqvj`B5jvEvveLAbLHP3TH@2BP1cX^dtZ*-U0C3s}rDbhcApJMCcS709&H`#W!9 zFZUqF&ii=;d3HX>TfB?zcFMF CFBundleDevelopmentRegion en - CFBundleDisplayName - GRDB Demo CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -18,6 +16,8 @@ APPL CFBundleShortVersionString 1.0 + CFBundleSignature + ???? CFBundleVersion 1 LSRequiresIPhoneOS @@ -33,6 +33,8 @@ UISupportedInterfaceOrientations UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift index 12dd28dbc..600e6adbe 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift @@ -1,21 +1,20 @@ import GRDB -struct Player: Codable { +struct Player: Codable, FetchableRecord, MutablePersistableRecord { var id: Int64? var name: String var score: Int -} -// MARK: - Player as a GRDB record - -extension Player: FetchableRecord, MutablePersistableRecord { + enum Columns: String, ColumnExpression { + case id, name, score + } + + /// Update player id after successful insertion mutating func didInsert(with rowID: Int64, for column: String?) { id = rowID } } -// MARK: - Random Player - extension Player { private static let names = ["Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", "Zazie", "Zoé"] diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift index bf7020e7c..1d9f3e3af 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayerEditionViewController.swift @@ -6,8 +6,8 @@ protocol PlayerEditionViewControllerDelegate: class { class PlayerEditionViewController: UITableViewController { weak var delegate: PlayerEditionViewControllerDelegate? - var player: Player! - var commitButtonHidden: Bool = false + var player: Player! { didSet { configureView() } } + var commitButtonHidden: Bool = false { didSet { configureView() } } @IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem! @IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem! @@ -16,18 +16,16 @@ class PlayerEditionViewController: UITableViewController { @IBOutlet fileprivate weak var scoreCell: UITableViewCell! @IBOutlet fileprivate weak var scoreTextField: UITextField! - func applyChanges() { - player.name = nameTextField.text ?? "" - player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 - } - override func viewDidLoad() { super.viewDidLoad() configureView() } - private func configureView() { + fileprivate func configureView() { + guard isViewLoaded else { return } + nameTextField.text = player.name + if player.score == 0 && player.id == nil { scoreTextField.text = "" } else { @@ -55,11 +53,18 @@ extension PlayerEditionViewController { return true } + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Commit" { + applyChanges() + } + } + override func willMove(toParentViewController parent: UIViewController?) { super.willMove(toParentViewController: parent) if parent == nil { // Self is popping from its navigation controller + applyChanges() delegate?.playerEditionControllerDidComplete(self) } } @@ -92,4 +97,13 @@ extension PlayerEditionViewController: UITextFieldDelegate { } return false } + + private func applyChanges() { + guard var player = self.player else { + return + } + player.name = nameTextField.text ?? "" + player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 + self.player = player + } } diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index bc40e9297..8c4d66479 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -2,17 +2,93 @@ import UIKit import GRDB class PlayersViewController: UITableViewController { + enum PlayerOrdering { + case byName + case byScore + + var request: QueryInterfaceRequest { + switch self { + case .byName: + return Player.order(Player.Columns.name) + case .byScore: + return Player.order(Player.Columns.score.desc, Player.Columns.name) + } + } + } + var playersController: FetchedRecordsController! + var playerOrdering: PlayerOrdering = .byScore { + didSet { + try! playersController.setRequest(playerOrdering.request) + configureNavigationItem() + } + } + + @IBOutlet weak var newPlayerButtonItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() + configureTableView() + configureToolbar() + configureNavigationItem() + } + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + navigationController?.isToolbarHidden = false + } +} + + +// MARK: - Navigation + +extension PlayersViewController : PlayerEditionViewControllerDelegate { + + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Edit" { + let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.delegate = self // See playerEditionControllerDidComplete + controller.commitButtonHidden = true + } + else if segue.identifier == "New" { + setEditing(false, animated: true) + let navigationController = segue.destination as! UINavigationController + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) + } + } + + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: cancel button was tapped + } + + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation: commit button was tapped + let controller = segue.source as! PlayerEditionViewController + try! dbQueue.write { db in + try controller.player.save(db) + } + } + + func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { + // Player edition: user has finished editing the player + try! dbQueue.write { db in + try controller.player.save(db) + } + } +} + + +// MARK: - UITableViewDataSource + +extension PlayersViewController { + private func configureTableView() { + playersController = try! FetchedRecordsController(dbQueue, request: playerOrdering.request) - navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: .addPlayer), - editButtonItem - ] - - playersController = try! FetchedRecordsController(dbQueue, request: playersSortedByScore) playersController.trackChanges( willChange: { [unowned self] _ in self.tableView.beginUpdates() @@ -45,79 +121,9 @@ class PlayersViewController: UITableViewController { }, didChange: { [unowned self] _ in self.tableView.endUpdates() - }) - try! playersController.performFetch() + }) - configureToolbar() - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - navigationController?.isToolbarHidden = false - } -} - - -// MARK: - Navigation - -extension PlayersViewController : PlayerEditionViewControllerDelegate { - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPlayer" { - let player = playersController.record(at: tableView.indexPathForSelectedRow!) - let controller = segue.destination as! PlayerEditionViewController - controller.title = player.name - controller.player = player - controller.delegate = self // we will save player when back button is tapped - controller.commitButtonHidden = true - } - else if segue.identifier == "NewPlayer" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PlayerEditionViewController - controller.title = "New Player" - controller.player = Player(id: nil, name: "", score: 0) - } - } - - @IBAction func addPlayer(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPlayer", sender: sender) - } - - @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation: cancel button was tapped - } - - @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation: commit button was tapped - let controller = segue.source as! PlayerEditionViewController - commitPlayerEdition(from: controller) - } - - func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { - // Player edition: back button was tapped - commitPlayerEdition(from: controller) - } - - private func commitPlayerEdition(from controller: PlayerEditionViewController) { - controller.applyChanges() - var player = controller.player! - if !player.name.isEmpty { - try! dbQueue.write { db in - try player.save(db) - } - } - } -} - - -// MARK: - UITableViewDataSource - -extension PlayersViewController { - func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let player = playersController.record(at: indexPath) - cell.textLabel?.text = player.name - cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" + try! playersController.performFetch() } override func numberOfSections(in tableView: UITableView) -> Int { @@ -141,90 +147,104 @@ extension PlayersViewController { _ = try player.delete(db) } } + + private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { + let player = playersController.record(at: indexPath) + if player.name.isEmpty { + cell.textLabel?.text = "(anonymous)" + } else { + cell.textLabel?.text = player.name + } + cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" + } } -// MARK: - FetchedRecordsController Demo +// MARK: - Actions extension PlayersViewController { + private func configureNavigationItem() { + navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] + + switch playerOrdering { + case .byScore: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Score ⬇︎", + style: .plain, + target: self, action: #selector(sortByName)) + case .byName: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Name ⬆︎", + style: .plain, + target: self, action: #selector(sortByScore)) + } + } - fileprivate func configureToolbar() { + private func configureToolbar() { toolbarItems = [ - UIBarButtonItem(title: "Name ⬆︎", style: .plain, target: self, action: .sortByName), - UIBarButtonItem(title: "Score ⬇︎", style: .plain, target: self, action: .sortByScore), - UIBarButtonItem(title: "Randomize", style: .plain, target: self, action: .randomizeScores), + UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(title: "💣", style: .plain, target: self, action: .stressTest) + UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), ] } @IBAction func sortByName() { setEditing(false, animated: true) - try! playersController.setRequest(playersSortedByName) + playerOrdering = .byName } @IBAction func sortByScore() { setEditing(false, animated: true) - try! playersController.setRequest(playersSortedByScore) + playerOrdering = .byScore } - @IBAction func randomizeScores() { + @IBAction func deletePlayers() { setEditing(false, animated: true) - try! dbQueue.write { db in - for var player in try Player.fetchAll(db) { - player.score = Player.randomScore() - try player.update(db) - } + _ = try Player.deleteAll(db) } } + @IBAction func refresh() { + setEditing(false, animated: true) + refreshPlayers() + } + @IBAction func stressTest() { setEditing(false, animated: true) - for _ in 0..<50 { DispatchQueue.global().async { - try! dbQueue.write { db in - if try Player.fetchCount(db) == 0 { - // Insert players - for _ in 0..<8 { - var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) - try player.insert(db) - } - } else { - // Insert a player - if arc4random_uniform(2) == 0 { - var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) - try player.insert(db) - } - // Delete a player - if arc4random_uniform(2) == 0 { - if let player = try Player.order(sql: "RANDOM()").fetchOne(db) { - try player.delete(db) - } - } - // Update some players - for var player in try Player.fetchAll(db) { - if arc4random_uniform(2) == 0 { - player.score = Player.randomScore() - try player.update(db) - } - } - } + self.refreshPlayers() + } + } + } + + private func refreshPlayers() { + try! dbQueue.write { db in + if try Player.fetchCount(db) == 0 { + // Insert new random players + for _ in 0..<8 { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + } else { + // Insert a player + if arc4random_uniform(2) == 0 { + var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore()) + try player.insert(db) + } + // Delete a random player + if arc4random_uniform(2) == 0 { + try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) + } + // Update some players + for var player in try Player.fetchAll(db) where arc4random_uniform(2) == 0 { + player.score = Player.randomScore() + try player.update(db) } } } } } - -// https://medium.com/swift-programming/swift-selector-syntax-sugar-81c8a8b10df3 -private extension Selector { - static let addPlayer = #selector(PlayersViewController.addPlayer(_:)) - static let sortByName = #selector(PlayersViewController.sortByName) - static let sortByScore = #selector(PlayersViewController.sortByScore) - static let randomizeScores = #selector(PlayersViewController.randomizeScores) - static let stressTest = #selector(PlayersViewController.stressTest) -} - -private let playersSortedByName = Player.order(Column("name")) -private let playersSortedByScore = Player.order(Column("score").desc, Column("name")) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift deleted file mode 100644 index aa47ea3da..000000000 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SimplePlayersViewController.swift +++ /dev/null @@ -1,107 +0,0 @@ -import UIKit -import GRDB - -class SimplePlayersViewController: UITableViewController { - var players: [Player]! - - override func viewDidLoad() { - super.viewDidLoad() - - navigationItem.rightBarButtonItems = [ - UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(SimplePlayersViewController.addPlayer(_:))), - editButtonItem - ] - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - players = try! dbQueue.read { db in - try Player.order(Column("score").desc, Column("name")).fetchAll(db) - } - tableView.reloadData() - } -} - - -// MARK: - Navigation - -extension SimplePlayersViewController : PlayerEditionViewControllerDelegate { - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "EditPlayer" { - let player = players[tableView.indexPathForSelectedRow!.row] - let controller = segue.destination as! PlayerEditionViewController - controller.title = player.name - controller.player = player - controller.delegate = self // see playerEditionControllerDidComplete - controller.commitButtonHidden = true - } - else if segue.identifier == "NewPlayer" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PlayerEditionViewController - controller.title = "New Player" - controller.player = Player(id: nil, name: "", score: 0) - } - } - - @IBAction func addPlayer(_ sender: AnyObject?) { - performSegue(withIdentifier: "NewPlayer", sender: sender) - } - - @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation: cancel button was tapped - } - - @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation: commit button was tapped - let controller = segue.source as! PlayerEditionViewController - commitPlayerEdition(from: controller) - } - - func playerEditionControllerDidComplete(_ controller: PlayerEditionViewController) { - // Player edition: back button was tapped - commitPlayerEdition(from: controller) - } - - private func commitPlayerEdition(from controller: PlayerEditionViewController) { - controller.applyChanges() - var player = controller.player! - if !player.name.isEmpty { - try! dbQueue.write { db in - try player.save(db) - } - } - } -} - - -// MARK: - UITableViewDataSource - -extension SimplePlayersViewController { - func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let player = players[indexPath.row] - cell.textLabel?.text = player.name - cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" - } - - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return players.count - } - - override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) - configure(cell, at: indexPath) - return cell - } - - override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { - // Delete the player - let player = players[indexPath.row] - try! dbQueue.write { db in - _ = try player.delete(db) - } - players.remove(at: indexPath.row) - tableView.deleteRows(at: [indexPath], with: .fade) - } -} From 0dd8fce8545abfccfee8c38f57699fb583168f3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Jun 2018 18:34:27 +0200 Subject: [PATCH 323/348] GoodPracticesForDesigningRecordTypes.md --- .../GoodPracticesForDesigningRecordTypes.md | 339 ++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 Documentation/GoodPracticesForDesigningRecordTypes.md diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md new file mode 100644 index 000000000..27fb44b81 --- /dev/null +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -0,0 +1,339 @@ +Good Practices for Designing Record Types +========================================= + +This guide aims at helping you leverage the best of GRDB [records] and [associations]. + +Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application. + +To support this guide, we'll design a simply library application that lets the user crawl through books and their authors. + +- [Trust SQLite More Than Yourself] +- [Record Types are Responsible for Their Tables] +- [Compose Records] +- [Fetch In Time] +- [Observe the Database and Refetch when Needed] + + +## Trust SQLite More Than Yourself + +Even if you don't know SQLite and SQL well, you must know that SQLite is a robust database. It is very difficult to corrupt a database file. It can make sure that only valid information is persisted on disk. + +You know that in the process of developing an application, bugs happen, right? Some bugs will even ship in the wild, and affect your application users. Thanks to SQLite, those bugs will be unable to corrupt your precious users' data if you take time to define a robust database schema. + +For example, if we were to define a [migration] that sets up our library database, we could write: + +```swift +var migrator = DatabaseMigrator() + +migrator.registerMigration("createLibrary") { db in + try db.create(table: "author") { t in // (1) + t.autoIncrementedPrimaryKey("id") // (2) + t.column("name", .text).notNull() // (3) + } + + try db.create(table: "book") { t in + t.autoIncrementedPrimaryKey("id") + t.column("authorId", .integer) // (4) + .notNull() // (5) + .indexed() // (6) + .references("author", onDelete: .cascade) // (7) + t.column("title", .text) // (8) + } +} + +try migrator.migrate(dbQueue) +``` + +1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, 'httpRequest'. +2. Each author has a unique id. +3. An author must have a name. +4. The `book.authorId` column is used to link a book to the author it belongs to. +5. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. +6. The `book.authorId` column is indexed in order to ease the selection of an author's books. +7. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. +8. A book must have a title. + +Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc. + +> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema. +> +> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations]. +> +> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with *strings*: +> +> ```swift +> migrator.registerMigration("createLibrary") { db in +> // RECOMMENDED +> try db.create(table: "author") { t in +> t.autoIncrementedPrimaryKey("id") +> ... +> } +> +> // NOT RECOMMENDED +> try db.create(table: Author.databaseTableName) { t in +> t.autoIncrementedPrimaryKey(Author.Columns.id.name) +> ... +> } +> } +> ``` +> +> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application. +> +> So make sure that migrations don't use application types and values: migrations talk to the database, only to the database, and use the database language, which is *strings*. + + +## Record Types are Responsible for Their Tables + +Define one record type per database table. + +In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records. + +```swift +struct Author: Codable, FetchableRecord, MutablePersistableRecord { + var id: Int64? + var name: String + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} + +struct Book: Codable, FetchableRecord, MutablePersistableRecord { + var id: Int64? + var authorId: Int64 + var title: String + + mutating func didInsert(with rowID: Int64, for column: String?) { + id = rowID + } +} +``` + +That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information. + +> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property. +> +> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method: +> +> ```swift +> var author = Author(id: nil, name: "Hermann Melville") +> try author.insert(db) +> print(author.id) // Some non-nil id +> ``` + +Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*. + +Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type". + +> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table. + + +## Compose Records + +Now that we have two types for authors and books, we'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author. + +GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations, along with their companion properties: + +```swift +extension Author { + static let books = hasMany(Book.self) + var books: QueryInterfaceRequest { + return request(for: Author.books) + } +} + +extension Book { + static let author = belongsTo(Author.self) + var author: QueryInterfaceRequest { + return request(for: Book.author) + } +} +``` + +Thanks to this setup, you can fetch associated records: + +```swift +// Fetch an author and its books +struct AuthorInfo { + var author: Author + var books: [Book] +} +let authorInfo = try dbQueue.read { db -> AuthorInfo? in + guard let author = try Author.fetchOne(db, key: 123) else { + return nil + } + let books = try author.books.fetchAll(db) + return AuthorInfo(author: author, books: books) +} + +// Fetch all authorships +struct Authorship: Decodable, FetchableRecord { + var book: Book + var author: Author +} +let authorships = try dbQueue.read { db -> [Authorship] in + let request = Book.including(required: Book.author) + return try Authorship.fetchAll(db, request) +} +``` + +The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they? + +That is because other ORMs perform lazy loading: + +```ruby +# Ruby's Active Record +author = Author.find(123) # fetch author +books = author.books # lazily fetches books on demand +``` + +GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation]. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. GRDB has removed lazy loading from the list of desirable features, on purpose. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information. + +The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below: + +1. Prepare the application screen that lists all authors: + + ```swift + let authors: [Author] = dbQueue.read { db in + Author + .order(Colum("name").collate(.localizedCaseInsensitiveCompare)) + .fetchAll(db) + } + ``` + +2. Prepare the application screen that displays an author and her books: + + ```swift + struct AuthorInfo { + var author: Author + var books: [Book] + } + let authorId = 123 + let authorInfo: AuthorInfo? = dbQueue.read { db in + guard let author = try Author.fetchOne(db, key: authorId) else { + return nil + } + let books = try author + .books + .order(Column("publishDate").desc) + .fetchAll(db) + return AuthorInfo(author: author, books: books) + } + ``` + +3. Prepare the application screen that displays a book information: + + ```swift + struct BookInfo { + var book: Book + var author: Author + } + let bookId = 123 + let bookInfo: BookInfo? = dbQueue.read { db in + guard let book = try Book.fetchOne(db, key: bookId) else { + return nil + } + let author = try book.author.fetchOne(db)! + return BookInfo(book: book, author: author) + } + ``` + +> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less. + + +## Fetch In Time + +> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**. + +```swift +// RECOMMENDED +let bookId = 123 +let bookInfo: BookInfo? = try dbQueue.read { db in + guard let book = try Book.fetchOne(db, key: bookId) else { + return nil + } + let author = try book.author.fetchOne(db)! + return BookInfo(book: book, author: author) +} +if let bookInfo = bookInfo { + // use bookInfo +} + +// NOT RECOMMENDED +let bookId = 123 +if let book = databaseManager.getBook(id: bookId) { + let author = databaseManager.getAuthor(id: book.authorId)! + // use book and author +} +``` + +This tip is paramount, and deserves an explanation: when you do not fetch your data in a single database read, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss. + +Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony: + +```ruby +# Ruby's Active Record +if book = Book.find(123) # fetch book + author = book.author # fetch author + # use book and author +end +``` + +The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests. + +This isolation can be achieved with record management, as in [Core Data] or [Realm], that target with long-running multi-threaded applications. Most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others. + +GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. Unlike web-oriented ORMs, though, GRDB can't provide *implicit* isolation: the application must decide when it wants to safely read information in the database, and this decision is made *explicit* with the `read` GRDB method. + +Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale. + + +## Observe the Database and Refetch when Needed + +We have seen above that the Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it. + +Fetched information eventually becomes obsoleted, as the application modifies the database content. + +It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content. + +This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways. + +Instead, have a look at [Database Observation]: + +> :bulb: **Tip**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way. +> +> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request. +> +> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for database observation, for your most advanced needs. +> +> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones. + + +[records]: ../README.md#records +[associations]: AssociationsBasics.md +[FMDB]: https://github.com/ccgus/fmdb +[Core Data]: https://developer.apple.com/documentation/coredata +[Realm]: https://realm.io +[Active Record]: http://guides.rubyonrails.org/active_record_basics.html +[Django]: https://docs.djangoproject.com/en/2.0/topics/db/ +[record protocols]: ../README.md#record-protocols-overview +[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns +[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle +[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth +[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule +[Why Adopt GRDB?]: WhyAdoptGRDB.md +[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems) +[migrations]: ../README.md#migrations +[migration]: ../README.md#migrations +[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions +[Concurrency Guide]: ../README.md#concurrency +[PersistableRecord]: ../README.md#persistablerecord-protocol +[Database Observation]: ../README.md#database-changes-observation +[FetchedRecordsController]: ../README.md#fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB +[TransactionObserver]: ../README.md#transactionobserver-protocol +[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself +[Record Types are Responsible for Their Tables]: #record-types-are-responsible-for-their-tables +[Compose Records]: #compose-records +[Fetch In Time]: #fetch-in-time +[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed From b8328bd3bba996fac799c5036803140680d67a15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 3 Jun 2018 18:37:00 +0200 Subject: [PATCH 324/348] GoodPracticesForDesigningRecordTypes.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5818721e1..19f01fe5a 100644 --- a/README.md +++ b/README.md @@ -2011,6 +2011,8 @@ Of course, you need to open a [database connection](#database-connections), and Your custom structs and classes can adopt each protocol individually, and opt in to focused sets of features. Or you can subclass the `Record` class, and get the full toolkit in one go: fetching methods, persistence methods, and record comparison. See the [list of record methods](#list-of-record-methods) for an overview. > :point_up: **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, and do not auto-update. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. +> +> :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide. **Overview** From c7f018c6353a5dd160d10bd25734960b1692b65c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 4 Jun 2018 07:40:12 +0200 Subject: [PATCH 325/348] GoodPracticesForDesigningRecordTypes.md --- Documentation/GoodPracticesForDesigningRecordTypes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 27fb44b81..74d9090d7 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -158,7 +158,7 @@ struct AuthorInfo { var author: Author var books: [Book] } -let authorInfo = try dbQueue.read { db -> AuthorInfo? in +let authorInfo: AuthorInfo? = try dbQueue.read { db in guard let author = try Author.fetchOne(db, key: 123) else { return nil } @@ -171,7 +171,7 @@ struct Authorship: Decodable, FetchableRecord { var book: Book var author: Author } -let authorships = try dbQueue.read { db -> [Authorship] in +let authorships: [Authorship] = try dbQueue.read { db in let request = Book.including(required: Book.author) return try Authorship.fetchAll(db, request) } From caea11fbbb9001ff8a3d3f428877dc0775317b7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 4 Jun 2018 11:58:40 +0200 Subject: [PATCH 326/348] Database: a couple more asserts --- GRDB/Core/Database.swift | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 71fd0f761..56e708767 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -670,6 +670,7 @@ extension Database { switch completion { case .commit: try execute("RELEASE SAVEPOINT grdb") + assert(!topLevelSavepoint || !isInsideTransaction) needsRollback = false case .rollback: needsRollback = true @@ -759,11 +760,13 @@ extension Database { if sqlite3_get_autocommit(sqliteConnection) == 0 { try execute("ROLLBACK TRANSACTION") } + assert(!isInsideTransaction) } /// Commits a database transaction. public func commit() throws { try execute("COMMIT TRANSACTION") + assert(!isInsideTransaction) } } From 8b44b0af7bfbce7ca5f8499882e7f36680b79db6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Mon, 4 Jun 2018 11:59:43 +0200 Subject: [PATCH 327/348] Fix SerializedDatabase.reentrantSync check for unsafe transactions --- GRDB/Core/SerializedDatabase.swift | 58 +++++++++++++++++++----------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index 129870a83..9d9a44066 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -61,27 +61,27 @@ final class SerializedDatabase { // // 1. A database is invoked from some queue like the main queue: // - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.sync { db in // <-- we're here // } // // 2. A database is invoked in a reentrant way: // - // dbQueue.inDatabase { db in - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.sync { db in + // serializedDatabase.sync { db in // <-- we're here // } // } // // 3. A database in invoked from another database: // - // dbQueue1.inDatabase { db1 in - // dbQueue2.inDatabase { db2 in // <-- we're here + // serializedDatabase1.sync { db1 in + // serializedDatabase2.sync { db2 in // <-- we're here // } // } guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - defer { preconditionNoTransactionLeft(db) } + defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } } @@ -92,7 +92,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - defer { preconditionNoTransactionLeft(db) } + defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } } @@ -107,42 +107,60 @@ final class SerializedDatabase { // // 1. A database is invoked from some queue like the main queue: // - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.reentrantSync { db in // <-- we're here // } // // 2. A database is invoked in a reentrant way: // - // dbQueue.inDatabase { db in - // dbQueue.inDatabase { db in // <-- we're here + // serializedDatabase.reentrantSync { db in + // serializedDatabase.reentrantSync { db in // <-- we're here // } // } // // 3. A database in invoked from another database: // - // dbQueue1.inDatabase { db1 in - // dbQueue2.inDatabase { db2 in // <-- we're here + // serializedDatabase1.reentrantSync { db1 in + // serializedDatabase2.reentrantSync { db2 in // <-- we're here // } // } guard let watchdog = SchedulingWatchdog.current else { // Case 1 return try queue.sync { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } } // Case 2 if watchdog.allows(db) { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } // Case 3 return try queue.sync { try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { - defer { preconditionNoTransactionLeft(db) } - return try block(db) + // Since we are reentrant, a transaction may already be opened. + // In this case, don't check for unsafe transaction at the end. + if db.isInsideTransaction { + return try block(db) + } else { + defer { preconditionNoUnsafeTransactionLeft(db) } + return try block(db) + } } } } @@ -151,7 +169,7 @@ final class SerializedDatabase { func async(_ block: @escaping (Database) -> Void) { queue.async { block(self.db) - self.preconditionNoTransactionLeft(self.db) + self.preconditionNoUnsafeTransactionLeft(self.db) } } @@ -174,7 +192,7 @@ final class SerializedDatabase { } /// Fatal error if a transaction has been left opened. - func preconditionNoTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { + private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) { GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line) } } From b7f44785ec854e668c26a674f59ad2f22b1b3d8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 08:02:54 +0200 Subject: [PATCH 328/348] The SQL statement generated by record.update(db) lists columns in the same order as in the table definition (this fixes tests made flaky by SE-0206) --- GRDB/Record/PersistableRecord.swift | 27 ++++++++++--------- GRDB/Record/Record.swift | 2 +- ...MutablePersistableRecordChangesTests.swift | 2 +- .../MutablePersistableRecordTests.swift | 2 +- Tests/GRDBTests/PersistableRecordTests.swift | 2 +- 5 files changed, 18 insertions(+), 17 deletions(-) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index b33cd862b..eea99b42d 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -529,7 +529,7 @@ extension MutablePersistableRecord { /// PersistenceError.recordNotFound is thrown if the primary key does not /// match any row in the database. public func performUpdate(_ db: Database, columns: Set) throws { - guard let statement = try DAO(db, self).updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try DAO(db, self).updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } @@ -903,7 +903,7 @@ final class DAO { } /// Returns nil if and only if primary key is nil - func updateStatement(columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { + func updateStatement(_ db: Database, columns: Set, onConflict: Database.ConflictResolution) throws -> UpdateStatement? { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { @@ -911,17 +911,17 @@ final class DAO { } guard primaryKeyValues.contains(where: { !$0.isNull }) else { return nil } - let lowercasePersistentColumns = Set(persistenceContainer.columns.map { $0.lowercased() }) - let lowercasePrimaryKeyColumns = Set(primaryKeyColumns.map { $0.lowercased() }) - var updatedColumns: [String] = [] - for column in columns { - let lowercaseColumn = column.lowercased() - // Don't update columns that are not present in the persistenceContainer - guard lowercasePersistentColumns.contains(lowercaseColumn) else { continue } - // Don't update primary key columns - guard !lowercasePrimaryKeyColumns.contains(lowercaseColumn) else { continue } - updatedColumns.append(column) - } + // Don't update columns not present in columns + // Don't update columns not present in the persistenceContainer + // Don't update primary key columns + let lowercaseUpdatedColumns = Set(columns.map { $0.lowercased() }) + .intersection(persistenceContainer.columns.map { $0.lowercased() }) + .subtracting(primaryKeyColumns.map { $0.lowercased() }) + + var updatedColumns: [String] = try db + .columns(in: databaseTableName) + .map { $0.name } + .filter { lowercaseUpdatedColumns.contains($0.lowercased()) } if updatedColumns.isEmpty { // IMPLEMENTATION NOTE @@ -934,6 +934,7 @@ final class DAO { // including tables made of a single primary key column. updatedColumns = primaryKeyColumns } + let updatedValues = updatedColumns.map { persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null } diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index f13962220..30b0f7894 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -274,7 +274,7 @@ open class Record : FetchableRecord, TableRecord, PersistableRecord { // // But this would trigger two calls to `encode(to:)`. let dao = try DAO(db, self) - guard let statement = try dao.updateStatement(columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { + guard let statement = try dao.updateStatement(db, columns: columns, onConflict: type(of: self).persistenceConflictPolicy.conflictResolutionForUpdate) else { // Nil primary key throw PersistenceError.recordNotFound(self) } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index b7fab1a80..f8b01ebce 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -264,7 +264,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { let totalChangesCount = db.totalChangesCount try XCTAssertTrue(newPlayer.updateChanges(db, from: oldPlayer)) XCTAssertEqual(db.totalChangesCount, totalChangesCount + 1) - XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"NAME\"='Bobby' WHERE \"id\"=1") + XCTAssertEqual(lastSQLQuery, "UPDATE \"players\" SET \"name\"='Bobby' WHERE \"id\"=1") return .rollback } } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 0ef4f7b01..1f2175db2 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -190,7 +190,7 @@ class MutablePersistableRecordTests: GRDBTestCase { do { person1.name = "David" try person1.update(db, columns: ["AgE"]) // case insensitivity - XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"AgE\"=25 WHERE \"id\"=1") + XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"age\"=25 WHERE \"id\"=1") let rows = try Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index 33ddb04d1..3d101212f 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -240,7 +240,7 @@ class PersistableRecordTests: GRDBTestCase { do { person1.name = "David" try person1.update(db, columns: ["AgE"]) // case insensitivity - XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"AgE\"=25 WHERE \"id\"=1") + XCTAssertEqual(self.lastSQLQuery, "UPDATE \"persons\" SET \"age\"=25 WHERE \"id\"=1") let rows = try Row.fetchAll(db, "SELECT * FROM persons ORDER BY id") XCTAssertEqual(rows.count, 2) From 6130c6f985ec1461b0a29dcb2afe6d6059016b64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 08:03:50 +0200 Subject: [PATCH 329/348] Who guessed String ordering would depend on Swift version? Fix a test so that it runs in both Swift 4.1 and Swift 4.2 --- Tests/GRDBTests/DatabaseCollationTests.swift | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/Tests/GRDBTests/DatabaseCollationTests.swift b/Tests/GRDBTests/DatabaseCollationTests.swift index 2e8f4bdab..04297a1db 100644 --- a/Tests/GRDBTests/DatabaseCollationTests.swift +++ b/Tests/GRDBTests/DatabaseCollationTests.swift @@ -22,9 +22,16 @@ class DatabaseCollationTests: GRDBTestCase { try db.execute("INSERT INTO strings VALUES (7, 'Z')") try db.execute("INSERT INTO strings VALUES (8, 'z')") - XCTAssertEqual( - try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), - [1,3,2,6,7,4,5,8]) + // Swift 4.2 and Swift 4.1 don't sort strings in the same way + if "z" < "à" { + XCTAssertEqual( + try Int.fetchAll(db, "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, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.unicodeCompare.name), id"), + [1,3,2,6,7,4,5,8]) + } XCTAssertEqual( try Int.fetchAll(db, "SELECT id FROM strings ORDER BY name COLLATE \(DatabaseCollation.caseInsensitiveCompare.name), id"), [1,3,2,4,6,5,7,8]) From 60eb868fa5b9777ab6853d1a949685af7ef67acc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 14:38:47 +0200 Subject: [PATCH 330/348] Failing tests for Database.indexes(on:) and Database.foreignKeys(on:) --- Tests/GRDBTests/ForeignKeyInfoTests.swift | 8 ++++++++ Tests/GRDBTests/IndexInfoTests.swift | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/Tests/GRDBTests/ForeignKeyInfoTests.swift b/Tests/GRDBTests/ForeignKeyInfoTests.swift index 03c9b53ce..91d8e0d4c 100644 --- a/Tests/GRDBTests/ForeignKeyInfoTests.swift +++ b/Tests/GRDBTests/ForeignKeyInfoTests.swift @@ -28,6 +28,14 @@ class ForeignKeyInfoTests: GRDBTestCase { try db.execute("CREATE TABLE children3 (parentA, parentB, FOREIGN KEY (parentA, parentB) REFERENCES parents2)") try db.execute("CREATE TABLE children4 (parentA1, parentB1, parentA2, parentB2, FOREIGN KEY (parentA1, parentB1) REFERENCES parents2, FOREIGN KEY (parentA2, parentB2) REFERENCES parents2(b, a))") + do { + _ = try db.foreignKeys(on: "missing") + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: missing") + } + do { let foreignKeys = try db.foreignKeys(on: "parents1") XCTAssert(foreignKeys.isEmpty) diff --git a/Tests/GRDBTests/IndexInfoTests.swift b/Tests/GRDBTests/IndexInfoTests.swift index f1a51c5cc..5fc09de3c 100644 --- a/Tests/GRDBTests/IndexInfoTests.swift +++ b/Tests/GRDBTests/IndexInfoTests.swift @@ -12,6 +12,14 @@ class IndexInfoTests: GRDBTestCase { func testIndexes() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in + do { + _ = try db.indexes(on: "missing") + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "no such table: missing") + } + do { try db.execute("CREATE TABLE persons (id INTEGER PRIMARY KEY, name TEXT, email TEXT UNIQUE)") let indexes = try db.indexes(on: "persons") From e915d28cb20619770b8dd80db1604327f7b9daab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 14:38:59 +0200 Subject: [PATCH 331/348] Fix failing tests for Database.indexes(on:) and Database.foreignKeys(on:) --- GRDB/Core/Database+Schema.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index fb0e98d66..ec1eba555 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -174,6 +174,14 @@ extension Database { return IndexInfo(name: indexName, columns: columns, unique: unique) } + if indexes.isEmpty { + // PRAGMA index_list doesn't throw any error when table does + // not exist. So let's check if table exists: + if try tableExists(tableName) == false { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + schemaCache.set(indexes: indexes, forTable: tableName) return indexes } @@ -208,6 +216,14 @@ extension Database { } } + if rawForeignKeys.isEmpty { + // PRAGMA foreign_key_list doesn't throw any error when table does + // not exist. So let's check if table exists: + if try tableExists(tableName) == false { + throw DatabaseError(message: "no such table: \(tableName)") + } + } + let foreignKeys = try rawForeignKeys.map { (destinationTable, columnMapping) -> ForeignKeyInfo in let orderedMapping = columnMapping .sorted { $0.seq < $1.seq } From 2556fd041f98e4f461954d51ff7db8b1c6274fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 22:23:43 +0200 Subject: [PATCH 332/348] Update Makefile for Xcode 9.4 --- Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index a223d02e6..560b77bba 100644 --- a/Makefile +++ b/Makefile @@ -45,7 +45,10 @@ XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null) TEST_ACTIONS = clean build build-for-testing test-without-building # When adding support for an Xcode version, look for available devices with `instruments -s devices` -ifeq ($(XCODEVERSION),9.3) +ifeq ($(XCODEVERSION),9.4) + MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.4" + MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" +else ifeq ($(XCODEVERSION),9.3) MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 8,OS=11.3" MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 4s,OS=9.0" else From fa31c484dae04da628acfe5e732f4b7556e7e6a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 22:46:02 +0200 Subject: [PATCH 333/348] OrderedRequest now waits for the database connection before ordering is computed --- GRDB.xcodeproj/project.pbxproj | 8 ++ .../Association/Association.swift | 10 +-- .../Association/AssociationQuery.swift | 2 +- .../Association/AssociationRequest.swift | 2 +- GRDB/QueryInterface/QueryInterfaceQuery.swift | 88 +------------------ .../QueryInterfaceRequest.swift | 25 ++++-- GRDB/QueryInterface/QueryOrdering.swift | 81 +++++++++++++++++ GRDB/QueryInterface/RequestProtocols.swift | 39 ++++++-- GRDBCipher.xcodeproj/project.pbxproj | 6 ++ GRDBCustom.xcodeproj/project.pbxproj | 6 ++ 10 files changed, 164 insertions(+), 103 deletions(-) create mode 100644 GRDB/QueryInterface/QueryOrdering.swift diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 760ef2cb5..4ee666f45 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -249,6 +249,9 @@ 565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; }; 56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; }; 56553C131C3E906C00522B5C /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; }; + 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; + 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; + 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF4E20C723E300F98521 /* QueryOrdering.swift */; }; 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABC1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -892,6 +895,7 @@ 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; 565490A01D5A4798005622CB /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 56553C181C3E906C00522B5C /* GRDBOSXCrashTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBOSXCrashTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 5656BF4E20C723E300F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1374,6 +1378,7 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB242094A14400F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF4E20C723E300F98521 /* QueryOrdering.swift */, 5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -2308,6 +2313,7 @@ 566475C01D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */, 565490E21D5AE252005622CB /* Record.swift in Sources */, + 5656BF5120C723E300F98521 /* QueryOrdering.swift in Sources */, 565490C11D5AE236005622CB /* FetchRequest.swift in Sources */, 5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */, 56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterfaceRequest.swift in Sources */, @@ -2514,6 +2520,7 @@ C96C0F2C2084A459006B2981 /* SQLiteDateParser.swift in Sources */, 5605F1681C672E4000235C62 /* NSNumber.swift in Sources */, 56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */, + 5656BF5020C723E300F98521 /* QueryOrdering.swift in Sources */, 5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */, 560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */, 560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */, @@ -2915,6 +2922,7 @@ 566475BA1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 5653EB0920944C7C00F46237 /* Association.swift in Sources */, 56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */, + 5656BF4F20C723E300F98521 /* QueryOrdering.swift in Sources */, 5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */, 56A238A41B9C753B0082EB20 /* Record.swift in Sources */, 56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */, diff --git a/GRDB/QueryInterface/Association/Association.swift b/GRDB/QueryInterface/Association/Association.swift index c578b78e1..212fe3452 100644 --- a/GRDB/QueryInterface/Association/Association.swift +++ b/GRDB/QueryInterface/Association/Association.swift @@ -100,7 +100,7 @@ extension Association { return mapRequest { $0.filter(predicate) } } - /// Creates an association with the provided *orderings*. + /// Creates an association with the provided *orderings promise*. /// /// struct Player: TableRecord { /// static let team = belongsTo(Team.self) @@ -110,7 +110,7 @@ extension Association { /// // FROM player /// // JOIN team ON team.id = player.teamId /// // ORDER BY team.name - /// let association = Player.team.order(Column("name")) + /// let association = Player.team.order { _ in [Column("name")] } /// var request = Player.including(required: association) /// /// Any previous ordering is replaced: @@ -120,11 +120,11 @@ extension Association { /// // JOIN team ON team.id = player.teamId /// // ORDER BY team.name /// let association = Player.team - /// .order(Column("color")) + /// .order{ _ in [Column("color")] } /// .reversed() - /// .order(Column("name")) + /// .order{ _ in [Column("name")] } /// var request = Player.including(required: association) - public func order(_ orderings: [SQLOrderingTerm]) -> Self { + public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self { return mapRequest { $0.order(orderings) } } diff --git a/GRDB/QueryInterface/Association/AssociationQuery.swift b/GRDB/QueryInterface/Association/AssociationQuery.swift index a89a25361..fb70e808c 100644 --- a/GRDB/QueryInterface/Association/AssociationQuery.swift +++ b/GRDB/QueryInterface/Association/AssociationQuery.swift @@ -45,7 +45,7 @@ extension AssociationQuery { return query } - func order(_ orderings: [SQLOrderingTerm]) -> AssociationQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationQuery { return order(QueryOrdering(orderings: orderings)) } diff --git a/GRDB/QueryInterface/Association/AssociationRequest.swift b/GRDB/QueryInterface/Association/AssociationRequest.swift index 3f7909a5e..1f52aa2bc 100644 --- a/GRDB/QueryInterface/Association/AssociationRequest.swift +++ b/GRDB/QueryInterface/Association/AssociationRequest.swift @@ -24,7 +24,7 @@ extension AssociationRequest { return AssociationRequest(query: query.filter(predicate)) } - func order(_ orderings: [SQLOrderingTerm]) -> AssociationRequest { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> AssociationRequest { return AssociationRequest(query: query.order(orderings)) } diff --git a/GRDB/QueryInterface/QueryInterfaceQuery.swift b/GRDB/QueryInterface/QueryInterfaceQuery.swift index 2e3eba87a..abb790818 100644 --- a/GRDB/QueryInterface/QueryInterfaceQuery.swift +++ b/GRDB/QueryInterface/QueryInterfaceQuery.swift @@ -104,7 +104,7 @@ extension QueryInterfaceQuery { return query } - func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceQuery { + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceQuery { return order(QueryOrdering(orderings: orderings)) } @@ -248,7 +248,7 @@ extension QueryInterfaceQuery { sql += " HAVING " + havingExpression.expressionSQL(&context) } - let orderings = finalizedOrdering.resolve() + let orderings = try finalizedOrdering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } @@ -300,7 +300,7 @@ extension QueryInterfaceQuery { } if let limit = limit { - let orderings = finalizedOrdering.resolve() + let orderings = try finalizedOrdering.resolve(db) if !orderings.isEmpty { sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ") } @@ -519,88 +519,6 @@ struct AssociationJoin { } } -// MARK: - QueryOrdering - -struct QueryOrdering { - private var elements: [Element] = [] - var isReversed: Bool - - private enum Element { - case orderingTerm(SQLOrderingTerm) - case queryOrdering(QueryOrdering) - - var reversed: Element { - switch self { - case .orderingTerm(let orderingTerm): - return .orderingTerm(orderingTerm.reversed) - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.reversed) - } - } - - func qualified(with alias: TableAlias) -> Element { - switch self { - case .orderingTerm(let orderingTerm): - return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias)) - case .queryOrdering(let queryOrdering): - return .queryOrdering(queryOrdering.qualified(with: alias)) - } - } - - func resolve() -> [SQLOrderingTerm] { - switch self { - case .orderingTerm(let orderingTerm): - return [orderingTerm] - case .queryOrdering(let queryOrdering): - return queryOrdering.resolve() - } - } - } - - private init(elements: [Element], isReversed: Bool) { - self.elements = elements - self.isReversed = isReversed - } - - init() { - self.init( - elements: [], - isReversed: false) - } - - init(orderings: [SQLOrderingTerm]) { - self.init( - elements: orderings.map { .orderingTerm($0) }, - isReversed: false) - } - - var reversed: QueryOrdering { - return QueryOrdering( - elements: elements, - isReversed: !isReversed) - } - - func qualified(with alias: TableAlias) -> QueryOrdering { - return QueryOrdering( - elements: elements.map { $0.qualified(with: alias) }, - isReversed: isReversed) - } - - func appending(_ ordering: QueryOrdering) -> QueryOrdering { - return QueryOrdering( - elements: elements + [.queryOrdering(ordering)], - isReversed: isReversed) - } - - func resolve() -> [SQLOrderingTerm] { - if isReversed { - return elements.flatMap { $0.reversed.resolve() } - } else { - return elements.flatMap { $0.resolve() } - } - } -} - // MARK: - SQLSource enum SQLSource { diff --git a/GRDB/QueryInterface/QueryInterfaceRequest.swift b/GRDB/QueryInterface/QueryInterfaceRequest.swift index f6b62bcda..bf08c5157 100644 --- a/GRDB/QueryInterface/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/QueryInterfaceRequest.swift @@ -97,20 +97,20 @@ extension QueryInterfaceRequest : DerivableRequest, AggregatingRequest { return QueryInterfaceRequest(query: query.having(predicate)) } - /// Creates a request with the provided *orderings*. + /// Creates a request with the provided *orderings promise*. /// /// // SELECT * FROM player ORDER BY name /// var request = Player.all() - /// request = request.order([Column("name")]) + /// request = request.order { _ in [Column("name")] } /// /// Any previous ordering is replaced: /// /// // SELECT * FROM player ORDER BY name /// request - /// .order([Column("email")]) + /// .order{ _ in [Column("email")] } /// .reversed() - /// .order([Column("name")]) - public func order(_ orderings: [SQLOrderingTerm]) -> QueryInterfaceRequest { + /// .order{ _ in [Column("name")] } + public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest { return QueryInterfaceRequest(query: query.order(orderings)) } @@ -360,6 +360,21 @@ extension TableRecord { return all().order(orderings) } + /// Creates a request sorted by primary key. + /// + /// // SELECT * FROM player ORDER BY id + /// let request = Player.orderByPrimaryKey() + /// + /// // SELECT * FROM country ORDER BY code + /// let request = Country.orderByPrimaryKey() + /// + /// The selection defaults to all columns. This default can be changed for + /// all requests by the `TableRecord.databaseSelection` property, or + /// for individual requests with the `TableRecord.select` method. + public static func orderByPrimaryKey() -> QueryInterfaceRequest { + return all().orderByPrimaryKey() + } + /// Creates a request sorted according to *sql*. /// /// // SELECT * FROM player ORDER BY name diff --git a/GRDB/QueryInterface/QueryOrdering.swift b/GRDB/QueryInterface/QueryOrdering.swift new file mode 100644 index 000000000..9d8822f01 --- /dev/null +++ b/GRDB/QueryInterface/QueryOrdering.swift @@ -0,0 +1,81 @@ +/// QueryOrdering provides the order clause to QueryInterfaceQuery +/// and AssociationQuery. +struct QueryOrdering { + private var elements: [Element] = [] + var isReversed: Bool + + private enum Element { + case orderingTerms((Database) throws -> [SQLOrderingTerm]) + case queryOrdering(QueryOrdering) + + var reversed: Element { + switch self { + case .orderingTerms(let orderings): + return .orderingTerms { db in try orderings(db).map { $0.reversed } } + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.reversed) + } + } + + func qualified(with alias: TableAlias) -> Element { + switch self { + case .orderingTerms(let orderings): + return .orderingTerms { db in try orderings(db).map { $0.qualifiedOrdering(with: alias) } } + case .queryOrdering(let queryOrdering): + return .queryOrdering(queryOrdering.qualified(with: alias)) + } + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + switch self { + case .orderingTerms(let orderings): + return try orderings(db) + case .queryOrdering(let queryOrdering): + return try queryOrdering.resolve(db) + } + } + } + + private init(elements: [Element], isReversed: Bool) { + self.elements = elements + self.isReversed = isReversed + } + + init() { + self.init( + elements: [], + isReversed: false) + } + + init(orderings: @escaping (Database) throws -> [SQLOrderingTerm]) { + self.init( + elements: [.orderingTerms(orderings)], + isReversed: false) + } + + var reversed: QueryOrdering { + return QueryOrdering( + elements: elements, + isReversed: !isReversed) + } + + func qualified(with alias: TableAlias) -> QueryOrdering { + return QueryOrdering( + elements: elements.map { $0.qualified(with: alias) }, + isReversed: isReversed) + } + + func appending(_ ordering: QueryOrdering) -> QueryOrdering { + return QueryOrdering( + elements: elements + [.queryOrdering(ordering)], + isReversed: isReversed) + } + + func resolve(_ db: Database) throws -> [SQLOrderingTerm] { + if isReversed { + return try elements.flatMap { try $0.reversed.resolve(db) } + } else { + return try elements.flatMap { try $0.resolve(db) } + } + } +} diff --git a/GRDB/QueryInterface/RequestProtocols.swift b/GRDB/QueryInterface/RequestProtocols.swift index a47975774..9182a9eb7 100644 --- a/GRDB/QueryInterface/RequestProtocols.swift +++ b/GRDB/QueryInterface/RequestProtocols.swift @@ -202,6 +202,16 @@ extension TableRequest where Self: FilteredRequest { } } +extension TableRequest where Self: OrderedRequest { + /// Creates a request ordered by primary key. + public func orderByPrimaryKey() -> Self { + let tableName = self.databaseTableName + return order { db in + try db.primaryKey(tableName).columns.map { Column($0) } + } + } +} + // MARK: - AggregatingRequest /// The protocol for all requests that can aggregate. @@ -246,20 +256,20 @@ extension AggregatingRequest { /// The protocol for all requests that be ordered. public protocol OrderedRequest { - /// Creates a request with the provided *orderings*. + /// Creates a request with the provided *orderings promise*. /// /// // SELECT * FROM player ORDER BY name /// var request = Player.all() - /// request = request.order([Column("name")]) + /// request = request.order { _ in [Column("name")] } /// /// Any previous ordering is replaced: /// /// // SELECT * FROM player ORDER BY name /// request - /// .order([Column("email")]) + /// .order{ _ in [Column("email")] } /// .reversed() - /// .order([Column("name")]) - func order(_ orderings: [SQLOrderingTerm]) -> Self + /// .order{ _ in [Column("name")] } + func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self /// Creates a request that reverses applied orderings. /// @@ -290,7 +300,24 @@ extension OrderedRequest { /// .reversed() /// .order(Column("name")) public func order(_ orderings: SQLOrderingTerm...) -> Self { - return order(orderings) + return order { _ in orderings } + } + + /// Creates a request with the provided *orderings*. + /// + /// // SELECT * FROM player ORDER BY name + /// var request = Player.all() + /// request = request.order(Column("name")) + /// + /// Any previous ordering is replaced: + /// + /// // SELECT * FROM player ORDER BY name + /// request + /// .order(Column("email")) + /// .reversed() + /// .order(Column("name")) + public func order(_ orderings: [SQLOrderingTerm]) -> Self { + return order { _ in orderings } } /// Creates a request with the provided *sql* used for sorting. diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index 6286c1471..ca3c50743 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -273,6 +273,8 @@ 5653EC18209873A400F46237 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */; }; 5653EC1A209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; 5653EC1B209873E600F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC19209873E600F46237 /* SQLGenerationContext.swift */; }; + 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; + 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5C20C7248700F98521 /* QueryOrdering.swift */; }; 5657AABA1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABD1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB101D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -988,6 +990,7 @@ 5653EBB320961FE800F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC15209873A400F46237 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = ""; }; 5653EC19209873E600F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; + 5656BF5C20C7248700F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1444,6 +1447,7 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EBA120961FCA00F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF5C20C7248700F98521 /* QueryOrdering.swift */, 5616AAF8207CD5A900AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -2185,6 +2189,7 @@ 56CEB55B1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D301DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 560FC52A1CB003810014AA8E /* DatabaseError.swift in Sources */, + 5656BF5E20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D011EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BB1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 560FC52B1CB003810014AA8E /* DatabaseValue.swift in Sources */, @@ -2619,6 +2624,7 @@ 56CEB55E1EAA359A00BFAF62 /* SQLOrdering.swift in Sources */, 56BF6D331DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, 56AFC9FF1CB1A8BB00F48B96 /* DatabaseValueConvertible.swift in Sources */, + 5656BF5F20C7248700F98521 /* QueryOrdering.swift in Sources */, 56D51D041EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, 566475BE1D981AD200FF74B8 /* SQLSpecificExpressible+QueryInterface.swift in Sources */, 56AFCA001CB1A8BB00F48B96 /* Record.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index fcf06e10f..1880e4601 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -99,6 +99,8 @@ 5653EB8320961FB200F46237 /* AssociationBelongsToRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */; }; 5653EC082098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; 5653EC092098737400F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC072098737400F46237 /* SQLGenerationContext.swift */; }; + 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; + 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656BF5820C7247100F98521 /* QueryOrdering.swift */; }; 5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AABE1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB111D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; @@ -658,6 +660,7 @@ 5653EB6420961FB200F46237 /* AssociationBelongsToDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToDecodableRecordTests.swift; sourceTree = ""; }; 5653EB6520961FB200F46237 /* AssociationBelongsToRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToRowScopeTests.swift; sourceTree = ""; }; 5653EC072098737400F46237 /* SQLGenerationContext.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLGenerationContext.swift; sourceTree = ""; }; + 5656BF5820C7247100F98521 /* QueryOrdering.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryOrdering.swift; sourceTree = ""; }; 5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = ""; }; 5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = ""; }; 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDataTests.swift; sourceTree = ""; }; @@ -1088,6 +1091,7 @@ 5605F18C1C6B1A8700235C62 /* QueryInterfaceQuery.swift */, 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */, 5653EB5320961F7D00F46237 /* QueryInterfaceRequest+Association.swift */, + 5656BF5820C7247100F98521 /* QueryOrdering.swift */, 5616AAF4207CD59300AC3664 /* RequestProtocols.swift */, 5605F1891C6B1A8700235C62 /* SQLCollatedExpression.swift */, 566475991D97D8A000FF74B8 /* SQLCollection.swift */, @@ -1858,6 +1862,7 @@ F3BA80201CFB288C003DC1BA /* Date.swift in Sources */, 56A8C2351D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D341DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, + 5656BF5B20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D051EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80151CFB2876003DC1BA /* DatabaseWriter.swift in Sources */, F3BA800A1CFB286A003DC1BA /* Configuration.swift in Sources */, @@ -2130,6 +2135,7 @@ F3BA807C1CFB2E61003DC1BA /* Date.swift in Sources */, 56A8C2321D1914540096E9D4 /* UUID.swift in Sources */, 56BF6D311DEF47DA006039A3 /* Fixits-0-84-0.swift in Sources */, + 5656BF5A20C7247100F98521 /* QueryOrdering.swift in Sources */, 56D51D021EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */, F3BA80711CFB2E55003DC1BA /* DatabaseWriter.swift in Sources */, F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */, From 7e6de4fbd06c0ce5e139eb0f76837c49ff740837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 22:46:24 +0200 Subject: [PATCH 334/348] Test TableRequest.orderByPrimaryKey() --- .../RecordMinimalPrimaryKeyRowIDTests.swift | 14 +++++++++++++- .../RecordMinimalPrimaryKeySingleTests.swift | 16 ++++++++++++++-- .../RecordPrimaryKeyHiddenRowIDTests.swift | 16 ++++++++++++++-- .../RecordPrimaryKeyMultipleTests.swift | 16 ++++++++++++++-- Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift | 16 ++++++++++++++-- Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift | 16 ++++++++++++++-- .../GRDBTests/RecordPrimaryKeySingleTests.swift | 16 ++++++++++++++-- ...ingleWithReplaceConflictResolutionTests.swift | 16 ++++++++++++++-- 8 files changed, 111 insertions(+), 15 deletions(-) diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 9c4e9eb64..65dd3e4ca 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -379,7 +379,19 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(fetchedRecord.id == record.id) } } - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalRowID.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalRowIDs\" ORDER BY \"id\"") + } + } + // MARK: - Fetch With Primary Key diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 53de5100e..1615624cd 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -395,8 +395,20 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.UUID == record.UUID) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = MinimalSingle.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"minimalSingles\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 1b7f0d60e..4a8ab4b90 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -462,8 +462,20 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT *, \"rowid\" FROM \"persons\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index 486610a9e..c153f6ffc 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -415,8 +415,20 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.native == record.native) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Citizenship.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"citizenships\" ORDER BY \"personName\", \"countryName\"") + } + } + + // MARK: - Exists func testExistsWithNilPrimaryKeyReturnsFalse() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 76890fa94..34f15af93 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -116,8 +116,20 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.email == record.email) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Item.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"items\" ORDER BY \"rowid\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index 8ca0f792e..df044d945 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -458,8 +458,20 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Person.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"persons\" ORDER BY \"id\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 37e7f840a..fdd2ae692 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -406,8 +406,20 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.name == record.name) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Pet.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"pets\" ORDER BY \"UUID\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index 39c99e05c..3a550c14c 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -401,8 +401,20 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { XCTAssertTrue(fetchedRecord.email == record.email) } } - - + + + // MARK: - Order By Primary Key + + func testOrderByPrimaryKey() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let request = Email.orderByPrimaryKey() + let sqlRequest = try SQLRequest(db, request: request) + XCTAssertEqual(sqlRequest.sql, "SELECT * FROM \"emails\" ORDER BY \"email\"") + } + } + + // MARK: - Fetch With Primary Key func testFetchCursorWithPrimaryKeys() throws { From 0b1bc80c4175e98fc8444ffd8deaa12c4659a265 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 22:53:05 +0200 Subject: [PATCH 335/348] Document orderByPrimaryKey --- README.md | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 19f01fe5a..51911f83a 100644 --- a/README.md +++ b/README.md @@ -2360,8 +2360,8 @@ try Document.fetchOne(db, key: 1) // Document? For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' -try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship? ``` @@ -3547,8 +3547,8 @@ You can now build requests with the following methods: `all`, `none`, `select`, // SELECT * FROM country WHERE isoCode IN ('FR', 'US') Country.filter(keys: ["FR", "US"]) - // SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' - Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) + // SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' + Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"]) // SELECT * FROM player WHERE email = 'arthur@example.com' Player.filter(key: ["email": "arthur@example.com"]) @@ -3600,6 +3600,19 @@ You can now build requests with the following methods: `all`, `none`, `select`, Player.order(scoreColumn).order(nameColumn) ``` + `orderByPrimaryKey()` sorts by primary key: + + ```swift + // SELECT * FROM player ORDER BY id + Player.orderByPrimaryKey() + + // SELECT * FROM country ORDER BY code + Country.orderByPrimaryKey() + + // SELECT * FROM citizenship ORDER BY citizenId, countryCode + Citizenship.orderByPrimaryKey() + ``` + - `reversed()` reverses the eventual orderings. ```swift @@ -3970,8 +3983,8 @@ try Document.fetchOne(db, key: 1) // Document? For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' -try Citizenship.fetchOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) // Citizenship? +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.fetchOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // Citizenship? // SELECT * FROM player WHERE email = 'arthur@example.com' try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player? @@ -3996,8 +4009,8 @@ let country = try request.fetchOne(db) // Country? let request = Country.filter(keys: ["FR", "US"]) let countries = try request.fetchAll(db) // [Country] -// SELECT * FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' -let request = Citizenship.filter(key: ["playerID": 1, "countryISOCode": "FR"]) +// SELECT * FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +let request = Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"]) let citizenship = request.fetchOne(db) // Citizenship? // SELECT * FROM player WHERE email = 'arthur@example.com' @@ -4086,8 +4099,8 @@ try Document.deleteOne(db, key: 1) For multiple-column primary keys and unique keys defined by unique indexes, provide a dictionary: ```swift -// DELETE FROM citizenship WHERE playerID = 1 AND countryISOCode = 'FR' -try Citizenship.deleteOne(db, key: ["playerID": 1, "countryISOCode": "FR"]) +// DELETE FROM citizenship WHERE citizenId = 1 AND countryCode = 'FR' +try Citizenship.deleteOne(db, key: ["citizenId": 1, "countryCode": "FR"]) // DELETE FROM player WHERE email = 'arthur@example.com' Player.deleteOne(db, key: ["email": "arthur@example.com"]) @@ -5775,7 +5788,7 @@ let controller = FetchedRecordsController( // Using SQL, and eventual arguments: let controller = FetchedRecordsController( dbQueue, - sql: "SELECT * FROM player ORDER BY name WHERE countryIsoCode = ?", + sql: "SELECT * FROM player ORDER BY name WHERE countryCode = ?", arguments: ["FR"]) ``` From 018fac8c57cb79a884c9e6084689e43a49a0a5bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 5 Jun 2018 23:07:00 +0200 Subject: [PATCH 336/348] CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b73c0ae7d..d40b830dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ It comes with new features, but also a few breaking changes, and a set of update - Request derivation protocols ([#329](https://github.com/groue/GRDB.swift/pull/329)). - Preliminary Linux support for the main framework ([#354](https://github.com/groue/GRDB.swift/pull/354)). - Automatic table name generation ([#355](https://github.com/groue/GRDB.swift/pull/355)). +- Delayed Request Ordering ([#365](https://github.com/groue/GRDB.swift/pull/365)). ### Breaking Changes From c2e624c78dacb2ee0c1f0aa67fb2be4bfa245bc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 13:52:55 +0200 Subject: [PATCH 337/348] README.md --- README.md | 61 ++++++++++++++++++------------------------------------- 1 file changed, 20 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index 51911f83a..6ee515e7d 100644 --- a/README.md +++ b/README.md @@ -28,11 +28,6 @@ Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB It comes with [up-to-date documentation](#documentation), [general articles](https://medium.com/@gwendal.roue), [sample code](#sample-code), and a lot of interesting resolved issues that may answer your eventual [questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) and foster [best practices](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22). -For more information, check out: - -- [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) The reasons why GRDB could become your favorite database library. -- [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) The architecture of a GRDB-powered application. - --- @@ -249,25 +244,25 @@ Documentation **GRDB runs on top of SQLite**: you should get familiar with the [SQLite FAQ](http://www.sqlite.org/faq.html). For general and detailed information, jump to the [SQLite Documentation](http://www.sqlite.org/docs.html). -**Reference** +#### Reference - [GRDB Reference](http://groue.github.io/GRDB.swift/docs/3.0-beta.1/index.html) (generated by [Jazzy](https://github.com/realm/jazzy)) -**Getting Started** +#### Getting Started - [Installation](#installation) - [Database Connections](#database-connections): Connect to SQLite databases -**SQLite and SQL** +#### SQLite and SQL - [SQLite API](#sqlite-api): The low-level SQLite API • [executing updates](#executing-updates) • [fetch queries](#fetch-queries) -**Records and the Query Interface** +#### Records and the Query Interface - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies. - [Query Interface](#the-query-interface): A swift way to generate SQL • [table creation](#database-schema) • [requests](#requests) -**Application Tools** +#### Application Tools - [Migrations](#migrations): Transform your database as your application evolves. - [Full-Text Search](#full-text-search): Perform efficient and customizable full-text searches. @@ -277,7 +272,7 @@ Documentation - [Encryption](#encryption): Encrypt your database with SQLCipher. - [Backup](#backup): Dump the content of a database to another. -**Good to Know** +#### Good to Know - [Avoiding SQL Injection](#avoiding-sql-injection) - [Error Handling](#error-handling) @@ -287,9 +282,21 @@ Documentation - [Concurrency](#concurrency) - [Performance](#performance) -[FAQ](#faq) +#### General Guides & Good Practices -[Sample Code](#sample-code) +- [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) +- [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) +- [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) +- [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) +- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) +- [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) +- [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) +- [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) + + +#### [FAQ](#faq) + +#### [Sample Code](#sample-code) Installation @@ -4251,20 +4258,6 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor The RowDecoder type associated with the FetchRequest does not have to be Row, DatabaseValueConvertible, or FetchableRecord. See the [Customized Decoding of Database Rows](#customized-decoding-of-database-rows) chapter for more information. -Application Tools -================= - -On top of the APIs described above, GRDB provides a toolkit for applications. While none of those are mandatory, all of them help dealing with the database: - -- [Migrations](#migrations): Transform your database as your application evolves. -- [Full-Text Search](#full-text-search): Perform efficient and customizable full-text searches. -- [Joined Queries Support](#joined-queries-support): Consume complex joined queries. -- [Database Changes Observation](#database-changes-observation): Perform post-commit and post-rollback actions. -- [FetchedRecordsController](#fetchedrecordscontroller): Automated tracking of changes in a query results, plus UITableView animations. -- [Encryption](#encryption): Encrypt your database with SQLCipher. -- [Backup](#backup): Dump the content of a database to another. - - ## Migrations **Migrations** are a convenient way to alter your database schema over time in a consistent and easy way. @@ -6170,20 +6163,6 @@ The `backup` method blocks the current thread until the destination database con When the source is a [database pool](#database-pools), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error. -Good To Know -============ - -This chapter covers general topics that you should be aware of. - -- [Avoiding SQL Injection](#avoiding-sql-injection) -- [Error Handling](#error-handling) -- [Unicode](#unicode) -- [Memory Management](#memory-management) -- [Data Protection](#data-protection) -- [Concurrency](#concurrency) -- [Performance](#performance) - - ## Avoiding SQL Injection SQL injection is a technique that lets an attacker nuke your database. From b3f1997049154c896b73c00fe05442c972159093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 13:57:44 +0200 Subject: [PATCH 338/348] README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 6ee515e7d..3e97cda24 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. -It comes with [up-to-date documentation](#documentation), [general articles](https://medium.com/@gwendal.roue), [sample code](#sample-code), and a lot of interesting resolved issues that may answer your eventual [questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) and foster [best practices](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22). +It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), [sample code](#sample-code), and a [FAQ](#faq). --- @@ -284,19 +284,19 @@ Documentation #### General Guides & Good Practices -- [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) -- [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) -- [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) -- [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) -- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) -- [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) -- [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) -- [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) +- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) +- :bulb: [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) +- :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) +- :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) +- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) +- :blue_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) +- :blue_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) +- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) -#### [FAQ](#faq) +**[FAQ](#faq)** -#### [Sample Code](#sample-code) +**[Sample Code](#sample-code)** Installation From 69c20770378e8c7cfb3feca1da8e47021e2d0f22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 13:59:07 +0200 Subject: [PATCH 339/348] README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3e97cda24..cb3ef3f41 100644 --- a/README.md +++ b/README.md @@ -288,10 +288,10 @@ Documentation - :bulb: [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) - :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) - :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) -- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) -- :blue_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) -- :blue_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) -- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) +- :green_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) +- :green_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) +- :green_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) +- :green_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) **[FAQ](#faq)** From edd294550f4abcd9a335bde0bf65d87f81abad7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 13:59:52 +0200 Subject: [PATCH 340/348] Revert "README.md" This reverts commit 69c20770378e8c7cfb3feca1da8e47021e2d0f22. --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index cb3ef3f41..3e97cda24 100644 --- a/README.md +++ b/README.md @@ -288,10 +288,10 @@ Documentation - :bulb: [Migrating From GRDB 2 to GRDB 3](Documentation/GRDB2MigrationGuide.md) - :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22) - :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion) -- :green_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) -- :green_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) -- :green_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) -- :green_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) +- :blue_book: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) +- :blue_book: [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) +- :blue_book: [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) +- :blue_book: [Unexpected SQLite with Swift](https://hackernoon.com/unexpected-sqlite-with-swift-ddc6343bcbfc) **[FAQ](#faq)** From 4bc6a77588bf78bc8d2f4a8315575409fa3aad3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 14:02:48 +0200 Subject: [PATCH 341/348] README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3e97cda24..8de7e5407 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@ Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), [sample code](#sample-code), and a [FAQ](#faq). +See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your favorite database library! + --- From 44140cb1db870de15408d130a84f5aea02875e57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 15:01:59 +0200 Subject: [PATCH 342/348] README.md --- README.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8de7e5407..a4afe6a7c 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,9 @@ GRDB provides raw access to SQL and advanced SQLite features, because one someti Compared to [SQLite.swift](http://github.com/stephencelis/SQLite.swift) or [FMDB](http://github.com/ccgus/fmdb), GRDB can spare you a lot of glue code. Compared to [Core Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/) or [Realm](http://realm.io), it can simplify your multi-threaded applications. -It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), [sample code](#sample-code), and a [FAQ](#faq). +It comes with [up-to-date documentation](#documentation), [general guides](#general-guides--good-practices), and it is [fast](https://github.com/groue/GRDB.swift/wiki/Performance). -See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your favorite database library! +See [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md) if you are looking for your favorite database library. --- @@ -63,11 +63,6 @@ Companion libraries that enhance and extend GRDB: - [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). - [GRDBObjc](https://github.com/groue/GRDBObjc): FMDB-compatible bindings to GRDB. -More than a set of tools that leverage SQLite abilities, GRDB is also: - -- **Safer**: read the blog post [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e) -- **Faster**: see [Comparing the Performances of Swift SQLite libraries](https://github.com/groue/GRDB.swift/wiki/Performance) for a comparison between raw SQLite, FMDB, SQLite.swift, Core Data, Realm, and GRDB. - ## Usage From d1c47c3364623452107c776c1d755c00cc849684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 16:12:21 +0200 Subject: [PATCH 343/348] Improve "Good Practices for Designing Record Types" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 74d9090d7..2f1b34860 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -16,11 +16,11 @@ To support this guide, we'll design a simply library application that lets the u ## Trust SQLite More Than Yourself -Even if you don't know SQLite and SQL well, you must know that SQLite is a robust database. It is very difficult to corrupt a database file. It can make sure that only valid information is persisted on disk. +SQLite is a robust database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk. -You know that in the process of developing an application, bugs happen, right? Some bugs will even ship in the wild, and affect your application users. Thanks to SQLite, those bugs will be unable to corrupt your precious users' data if you take time to define a robust database schema. +This is important because we developers write bugs, and some of them will ship in the wild, affecting your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes a robust **database schema**. -For example, if we were to define a [migration] that sets up our library database, we could write: +For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write: ```swift var migrator = DatabaseMigrator() @@ -44,7 +44,7 @@ migrator.registerMigration("createLibrary") { db in try migrator.migrate(dbQueue) ``` -1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, 'httpRequest'. +1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. 2. Each author has a unique id. 3. An author must have a name. 4. The `book.authorId` column is used to link a book to the author it belongs to. From e7bcf7c7db040c94b63f84e60557004517377def Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 16:15:44 +0200 Subject: [PATCH 344/348] Funny how time you have for tweaking stuff when you're waiting for a watch app to launch... --- .../GoodPracticesForDesigningRecordTypes.md | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 2f1b34860..bcd330f00 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -33,11 +33,11 @@ migrator.registerMigration("createLibrary") { db in try db.create(table: "book") { t in t.autoIncrementedPrimaryKey("id") - t.column("authorId", .integer) // (4) - .notNull() // (5) - .indexed() // (6) - .references("author", onDelete: .cascade) // (7) - t.column("title", .text) // (8) + t.column("title", .text) // (4) + t.column("authorId", .integer) // (5) + .notNull() // (6) + .indexed() // (7) + .references("author", onDelete: .cascade) // (8) } } @@ -47,11 +47,11 @@ try migrator.migrate(dbQueue) 1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. 2. Each author has a unique id. 3. An author must have a name. -4. The `book.authorId` column is used to link a book to the author it belongs to. -5. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. -6. The `book.authorId` column is indexed in order to ease the selection of an author's books. -7. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. -8. A book must have a title. +4. A book must have a title. +5. The `book.authorId` column is used to link a book to the author it belongs to. +6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author. +7. The `book.authorId` column is indexed in order to ease the selection of an author's books. +8. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information. Thanks to this database schema, you can be confident so no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc. @@ -59,7 +59,7 @@ Thanks to this database schema, you can be confident so no matter how wrong our > > :bulb: **Tip**: Plan early for future versions of your application, and use [migrations]. > -> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with *strings*: +> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**: > > ```swift > migrator.registerMigration("createLibrary") { db in @@ -79,7 +79,7 @@ Thanks to this database schema, you can be confident so no matter how wrong our > > By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application. > -> So make sure that migrations don't use application types and values: migrations talk to the database, only to the database, and use the database language, which is *strings*. +> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**. ## Record Types are Responsible for Their Tables From b2683eb864a89f71942a15361d33edbb1d4dda92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 17:04:42 +0200 Subject: [PATCH 345/348] Improve "Good Practices for Designing Record Types" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index bcd330f00..768552644 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -187,7 +187,7 @@ author = Author.find(123) # fetch author books = author.books # lazily fetches books on demand ``` -GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation]. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. GRDB has removed lazy loading from the list of desirable features, on purpose. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information. +GRDB does not perform lazy loading. Lazy loading either requires record to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer. This is why GRDB has removed lazy loading from the list of desirable features. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information. The consequence is that each part of your application will load the data it needs, at the moment it needs it, as below: From 729ec6714c11b3bc6c9fb2b48af01c98e30780fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 17:08:42 +0200 Subject: [PATCH 346/348] Improve "Good Practices for Designing Record Types" --- .../GoodPracticesForDesigningRecordTypes.md | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 768552644..756bae7cd 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -195,9 +195,7 @@ The consequence is that each part of your application will load the data it need ```swift let authors: [Author] = dbQueue.read { db in - Author - .order(Colum("name").collate(.localizedCaseInsensitiveCompare)) - .fetchAll(db) + Author.order(Colum("name")).fetchAll(db) } ``` @@ -210,13 +208,8 @@ The consequence is that each part of your application will load the data it need } let authorId = 123 let authorInfo: AuthorInfo? = dbQueue.read { db in - guard let author = try Author.fetchOne(db, key: authorId) else { - return nil - } - let books = try author - .books - .order(Column("publishDate").desc) - .fetchAll(db) + guard let author = try Author.fetchOne(db, key: authorId) else { return nil } + let books = try author.books.order(Column("publishDate").desc).fetchAll(db) return AuthorInfo(author: author, books: books) } ``` @@ -230,9 +223,7 @@ The consequence is that each part of your application will load the data it need } let bookId = 123 let bookInfo: BookInfo? = dbQueue.read { db in - guard let book = try Book.fetchOne(db, key: bookId) else { - return nil - } + guard let book = try Book.fetchOne(db, key: bookId) else { return nil } let author = try book.author.fetchOne(db)! return BookInfo(book: book, author: author) } From 4637930027c4501caf2ff24f25717ecd3ed10251 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Wed, 6 Jun 2018 17:09:03 +0200 Subject: [PATCH 347/348] Improve "Good Practices for Designing Record Types" --- Documentation/GoodPracticesForDesigningRecordTypes.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 756bae7cd..65a0838c5 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -159,9 +159,7 @@ struct AuthorInfo { var books: [Book] } let authorInfo: AuthorInfo? = try dbQueue.read { db in - guard let author = try Author.fetchOne(db, key: 123) else { - return nil - } + guard let author = try Author.fetchOne(db, key: 123) else { return nil } let books = try author.books.fetchAll(db) return AuthorInfo(author: author, books: books) } @@ -240,9 +238,7 @@ The consequence is that each part of your application will load the data it need // RECOMMENDED let bookId = 123 let bookInfo: BookInfo? = try dbQueue.read { db in - guard let book = try Book.fetchOne(db, key: bookId) else { - return nil - } + guard let book = try Book.fetchOne(db, key: bookId) else { return nil } let author = try book.author.fetchOne(db)! return BookInfo(book: book, author: author) } From 30fcd95f1deca5af3fca1d294224b5be2b0e99b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Thu, 7 Jun 2018 08:31:57 +0200 Subject: [PATCH 348/348] Change podspec description --- GRDB.swift.podspec | 2 +- GRDBCipher.podspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index ec712b7d5..aad819f0e 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| s.version = '2.10.0' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'A Swift application toolkit for SQLite databases.' + s.summary = 'A toolkit for SQLite databases, with a focus on application development.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } diff --git a/GRDBCipher.podspec b/GRDBCipher.podspec index d63ad4227..4262ba38b 100644 --- a/GRDBCipher.podspec +++ b/GRDBCipher.podspec @@ -3,7 +3,7 @@ Pod::Spec.new do |s| s.version = '2.10.0' s.license = { :type => 'MIT', :file => 'LICENSE' } - s.summary = 'A Swift application toolkit for SQLite databases.' + s.summary = 'A toolkit for SQLite databases, with a focus on application development.' s.homepage = 'https://github.com/groue/GRDB.swift' s.author = { 'Gwendal Roué' => 'gr@pierlis.com' } s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }

hSYU^R~d_Eu?0_O&Bf?y1gFmR76RB-wd)&D7X<9){+^LF3Wf z&Br^gF5`w3Ntkl(NB_I?N=MI2NKQa3&(d@Muq;}|p55Wt^3R^84RLmMoK%ET*`dw% z^PLJW`nXDCz>e+I(*)iz8Y%-tM}oX z8R3+@o%nT~;-B}wmD z_!(F+0r>|1pdbhIa)8yk12EWERZaRR|1>Ndj^IE?8butJvFcU7zHhREbl+7Wy5MCT zh)SJ1nnP8j*Ju*POxb3yw_N}6hdo%D{8FHn&ql*$+?a>qvZu1kBHw>jf}OZ0z9h5> zU9*h1d^N4j-pXn|OycGiUBOtFdVIKikb6I{O$o`W@Mu>~X+?X+QS&~hE6$Af74LE5 z&T?a`#$BdU`{}1{pq50zR@@)Ss=2Kf|CaJ0YGad;lwp@AkztQyQIdJC_EhEz0b5?= zw-UM+ss~1D@84Gj2fN8g6@5rtk-`mn^dPai)HX6=edYS$h|_b3a;{a-X-DbC+QaGU z@PM-ATMKa7PS<_X@!3w+33j|BwBXi8nQL4}W0Mz)-)tpD{|rl_y(b6aGmRi){BFBN zsru{zw?hq`v3QRNOSNy7BHx9(8IQ#(?cbg6lIV8b&soIH3t8$~GWP&m_T7JYA?0k5 z$tX~}{KR&ka3mT2+yJhH>#F}%dfW4QNOe&s+IFxxsrcElA7TtM#7?&7`gD`Qj(h;w z_2th9sAI`I>ZXgntsMoN4zEqhB#)cmIl#QV*p-+MFjV+lEqfle_RK8<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