Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2023-10-04 22:06:37 +02:00
commit 458b7211df
57 files changed
+4621 -273

No files matched your search

+6 -6
View File
@@ -77,7 +77,7 @@ jobs:
destination: "OS=16.0,name=iPhone 14"
name: "iOS"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
SPM:
@@ -103,7 +103,7 @@ jobs:
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
@@ -123,7 +123,7 @@ jobs:
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
@@ -143,7 +143,7 @@ jobs:
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
CustomSQLite:
@@ -163,7 +163,7 @@ jobs:
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_framework_GRDBCustomSQLiteOSX
XCFramework:
@@ -183,7 +183,7 @@ jobs:
runsOn: macOS-12
name: "Xcode 14.0.1"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: ${{ matrix.name }}
run: make test_universal_xcframework
+12
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.19.x` Releases - [6.19.0](#6190)
- `6.18.x` Releases - [6.18.0](#6180)
- `6.17.x` Releases - [6.17.0](#6170)
- `6.16.x` Releases - [6.16.0](#6160)
@@ -116,6 +117,17 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.19.0
Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/v6.18.0/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
+1 -1
View File
@@ -61,7 +61,7 @@ How you can Contribute
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
- No Swiftlint warning after a build.
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.18.0'
s.version = '6.19.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+46 -2
View File
@@ -13,6 +13,10 @@
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
@@ -54,6 +58,9 @@
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
@@ -418,6 +425,10 @@
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -458,6 +469,9 @@
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
@@ -842,6 +856,25 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5603CEB52AC862EC00CF097D /* JSON */ = {
isa = PBXGroup;
children = (
5603CEB82AC862EC00CF097D /* JSONColumn.swift */,
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */,
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */,
);
path = JSON;
sourceTree = "<group>";
};
5603CEC82AC8630300CF097D /* JSON */ = {
isa = PBXGroup;
children = (
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */,
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */,
);
name = JSON;
sourceTree = "<group>";
};
5605F1471C672E4000235C62 /* Support */ = {
isa = PBXGroup;
children = (
@@ -921,6 +954,7 @@
isa = PBXGroup;
children = (
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -948,12 +982,13 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
56677C14241D14450050755D /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
56677C14241D14450050755D /* FailureTestCase.swift */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
5603CEC82AC8630300CF097D /* JSON */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
@@ -1278,6 +1313,7 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1644,6 +1680,7 @@
566DDE0C288D763C0000DCFB /* Fixits.swift */,
56A2386F1B9C75030082EB20 /* Core */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEB52AC862EC00CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
56300B6D1C53F592005A543B /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1839,6 +1876,7 @@
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */,
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
@@ -1853,6 +1891,7 @@
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */,
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
@@ -1930,6 +1969,7 @@
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */,
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
@@ -1940,6 +1980,7 @@
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
56419C5124A51998004967E1 /* Finished.swift in Sources */,
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
@@ -2153,6 +2194,7 @@
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
@@ -2181,9 +2223,11 @@
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */,
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */,
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
+8
View File
@@ -1826,6 +1826,14 @@ extension Database {
/// The `TEXT` column type.
public static let text = ColumnType(rawValue: "TEXT")
/// The `TEXT` column type, suitable for JSON columns.
///
/// SQLite JSON functions and operators are
/// [documented](https://www.sqlite.org/json1.html#interface_overview)
/// to throw errors if any of their arguments are binary blobs.
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
+18 -10
View File
@@ -30,9 +30,22 @@ public final class DatabaseFunction: Hashable {
/// The name of the SQL function
public var name: String { identity.name }
private let identity: Identity
let pure: Bool
let isPure: Bool
private let kind: Kind
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
var functionFlags: SQLFunctionFlags {
var flags = SQLFunctionFlags(isPure: isPure)
switch kind {
case .function:
break
case .aggregate:
flags.isAggregate = true
}
return flags
}
/// Creates an SQL function.
///
@@ -76,7 +89,7 @@ public final class DatabaseFunction: Hashable {
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.pure = pure
self.isPure = pure
self.kind = .function{ (argc, argv) in
let arguments = (0..<Int(argc)).map { index in
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
@@ -140,7 +153,7 @@ public final class DatabaseFunction: Hashable {
aggregate: Aggregate.Type)
{
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
self.pure = pure
self.isPure = pure
self.kind = .aggregate { Aggregate() }
}
@@ -170,12 +183,7 @@ public final class DatabaseFunction: Hashable {
/// }
/// ```
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
switch kind {
case .aggregate:
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
.function(name, arguments.map(\.sqlExpression), flags: functionFlags)
}
/// Calls sqlite3_create_function_v2
+49
View File
@@ -1,3 +1,5 @@
import Foundation
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
// `DatabaseValueConvertible`, on purpose.
//
@@ -59,6 +61,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
///
/// - returns: A decoded value, or, if decoding is impossible, nil.
static func fromMissingColumn() -> Self?
/// Returns the `JSONDecoder` that decodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Decodable` protocol.
static func databaseJSONDecoder() -> JSONDecoder
/// Returns the `JSONEncoder` that encodes the value.
///
/// This method is dedicated to ``DatabaseValueConvertible`` types that
/// also conform to the standard `Encodable` protocol.
static func databaseJSONEncoder() -> JSONEncoder
}
extension DatabaseValueConvertible {
@@ -75,6 +89,41 @@ extension DatabaseValueConvertible {
public static func fromMissingColumn() -> Self? {
nil // failure.
}
/// Returns the `JSONDecoder` that decodes the value.
///
/// The default implementation returns a `JSONDecoder` with the
/// following properties:
///
/// - `dataDecodingStrategy`: `.base64`
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatDecodingStrategy`: `.throw`
public static func databaseJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return decoder
}
/// Returns the `JSONEncoder` that encodes the value.
///
/// The default implementation returns a `JSONEncoder` with the
/// following properties:
///
/// - `dataEncodingStrategy`: `.base64`
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
/// - `nonConformingFloatEncodingStrategy`: `.throw`
/// - `outputFormatting`: `.sortedKeys`
public static func databaseJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
return encoder
}
}
// MARK: - Conversions
@@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable {
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return try? decoder.decode(Self.self, from: data)
return try? databaseJSONDecoder().decode(Self.self, from: data)
} catch {
return nil
}
@@ -2,6 +2,7 @@ import Foundation
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var codingPath: [any CodingKey] { [] }
@@ -42,16 +43,21 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue)
} else {
try DatabaseValueEncoder(encode: encode).encode(value)
try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value)
}
}
}
private class DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
let jsonEncoder: JSONEncoder
var requiresJSON = false
init(encode: @escaping (DatabaseValue) -> Void) {
init(
jsonEncoder: JSONEncoder,
encode: @escaping (DatabaseValue) -> Void
) {
self.jsonEncoder = jsonEncoder
self.encode = encode
}
@@ -104,7 +110,7 @@ private class DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func singleValueContainer() -> SingleValueEncodingContainer {
DatabaseValueEncodingContainer(encode: encode)
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
}
func encode<T: Encodable>(_ value: T) throws {
@@ -115,13 +121,7 @@ private class DatabaseValueEncoder: Encoder {
throw JSONRequiredError()
}
} catch is JSONRequiredError {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
let jsonData = try encoder.encode(value)
let jsonData = try jsonEncoder.encode(value)
// Store JSON String in the database for easier debugging and
// database inspection. Thanks to SQLite weak typing, we won't
@@ -138,7 +138,11 @@ private class DatabaseValueEncoder: Encoder {
extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
try! DatabaseValueEncoder(
jsonEncoder: Self.databaseJSONEncoder(),
encode: { dbValue = $0 }
)
.encode(self)
return dbValue
}
}
+4 -6
View File
@@ -24,7 +24,9 @@ When a schema change is not directly supported by SQLite, or not available on th
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
### Table names should be English, singular, and camelCased
@@ -163,11 +165,6 @@ struct Player: Codable {
var score: Int
}
extension Player: Identifiable {
// Required because the primary key column is not 'id'
var id: Int64? { rowid }
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
@@ -385,6 +382,7 @@ extension Team: TableRecord {
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
@@ -74,7 +74,14 @@ extension Color: DatabaseValueConvertible { }
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
```swift
protocol DatabaseValueConvertible {
static func databaseJSONDecoder() -> JSONDecoder
static func databaseJSONEncoder() -> JSONEncoder
}
```
### Adding support for the Tagged library
@@ -144,6 +151,11 @@ This extra conformance is not required: only aim at the low-level C interface if
- ``databaseValue-1ob9k``
### Configuring the JSON format for the standard Decodable protocol
- ``databaseJSONDecoder()-7zou9``
- ``databaseJSONEncoder()-37sff``
### Fetching Values from Raw SQL
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
+2 -7
View File
@@ -93,14 +93,9 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Responding to Database Changes
### Database Tools
- <doc:DatabaseObservation>
### Full-Text Search
- <doc:FullTextSearch>
### Combine Publishers
- <doc:JSON>
- ``DatabasePublishers``
+151
View File
@@ -0,0 +1,151 @@
# JSON Support
Store and use JSON values in SQLite databases.
## Overview
SQLite and GRDB can store and fetch JSON values in database columns. Starting SQLite 3.38.0 (iOS 16+, macOS 13.2+, tvOS 17+, and watchOS 9+), JSON values can be manipulated at the database level.
## Store and fetch JSON values
### JSON columns in the database schema
It is recommended to store JSON values in text columns. In the example below, we create a ``Database/ColumnType/jsonText`` column with ``Database/create(table:options:body:)``:
```swift
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
t.column("address", .jsonText).notNull() // A JSON column
}
```
> Note: `.jsonText` and `.text` are equivalent, because both build a TEXT column in SQL. Yet the former better describes the intent of the column.
>
> Note: SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. That's the reason why it is recommended to store JSON as text.
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
>
> ```swift
> // CREATE INDEX "player_on_country"
> // ON "player"("address" ->> 'country')
> try db.create(
> index: "player_on_country",
> on: "player",
> expressions: [
> JSONColumn("address")["country"],
> ])
>
> // SELECT * FROM player
> // WHERE "address" ->> 'country' = 'FR'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .fetchAll(db)
> ```
### Strict and flexible JSON schemas
[Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) handle both strict and flexible JSON schemas.
**For strict schemas**, use `Codable` properties. They will be stored as JSON strings in the database:
```swift
struct Address: Codable {
var street: String
var city: String
var country: String
}
struct Player: Codable {
var id: String
var name: String
// Stored as a JSON string
// {"street": "...", "city": "...", "country": "..."}
var address: Address
}
extension Player: FetchableRecord, PersistableRecord { }
```
**For flexible schemas**, use `String` or `Data` properties.
In the specific case of `Data` properties, it is recommended to store them as text in the database, because SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. This encoding is automatic with ``DatabaseDataEncodingStrategy/text``:
```swift
// JSON String property
struct Player: Codable {
var id: String
var name: String
var address: String // JSON string
}
extension Player: FetchableRecord, PersistableRecord { }
// JSON Data property, saved as text in the database
struct Team: Codable {
var id: String
var color: String
var info: Data // JSON UTF8 data
}
extension Team: FetchableRecord, PersistableRecord {
// Support SQLite JSON functions and operators
// by storing JSON data as database text:
static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
}
```
## Manipulate JSON values at the database level
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting SQLite 3.38.0 (iOS 16+, macOS 13.2+, tvOS 17+, and watchOS 9+).
Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc.
See the full list below.
## JSON table-valued functions
The JSON table-valued functions `json_each` and `json_tree` are not supported.
## Topics
### JSON Values
- ``SQLJSONExpressible``
- ``JSONColumn``
### Access JSON subcomponents, and query JSON values, at the SQL level
The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` protocol.
- ``Database/jsonArrayLength(_:)``
- ``Database/jsonArrayLength(_:atPath:)``
- ``Database/jsonExtract(_:atPath:)``
- ``Database/jsonExtract(_:atPaths:)``
- ``Database/jsonType(_:)``
- ``Database/jsonType(_:atPath:)``
### Build new JSON values at the SQL level
- ``Database/json(_:)``
- ``Database/jsonArray(_:)-8xxe3``
- ``Database/jsonArray(_:)-469db``
- ``Database/jsonObject(_:)``
- ``Database/jsonQuote(_:)``
- ``Database/jsonGroupArray(_:)``
- ``Database/jsonGroupObject(key:value:)``
### Modify JSON values at the SQL level
- ``Database/jsonInsert(_:_:)``
- ``Database/jsonPatch(_:with:)``
- ``Database/jsonReplace(_:_:)``
- ``Database/jsonRemove(_:atPath:)``
- ``Database/jsonRemove(_:atPaths:)``
- ``Database/jsonSet(_:_:)``
### Validate JSON values at the SQL level
- ``Database/jsonErrorPosition(_:)``
- ``Database/jsonIsValid(_:)``
+12 -4
View File
@@ -17,16 +17,22 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
- ``PersistableRecord``
- ``TableRecord``
### Associations
### Expressions
- ``Association``
- ``Column``
- ``JSONColumn``
- ``SQLExpression``
### Query Interface Requests
### Requests
- ``CommonTableExpression``
- ``QueryInterfaceRequest``
- ``Table``
### Associations
- ``Association``
### Errors
- ``RecordError``
@@ -34,9 +40,11 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
### Supporting Types
- ``ColumnExpression``
- ``DerivableRequest``
- ``SQLExpressible``
- ``SQLJSONExpressible``
- ``SQLSpecificExpressible``
- ``SQLSubqueryable``
- ``SQLOrderingTerm``
- ``SQLSelectable``
- ``SQLSubqueryable``
@@ -61,16 +61,16 @@ Thanks to this database schema, the application will always process *consistent
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable, Identifiable {
struct Author: Codable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable, Identifiable {
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
@@ -129,7 +129,7 @@ let books = try dbQueue.read { db in
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable, Identifiable {
> struct Author: Codable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
@@ -150,6 +150,25 @@ let books = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
>
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
>
> ```swift
> struct Player: Codable {
> var id: Int64? // Optional ids are not suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
### Record Types Hide Intimate Database Details
+4 -4
View File
@@ -25,7 +25,7 @@ try db.create(table: "player") { t in
t.column("score", .integer).notNull()
}
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
@@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to
```swift
let player = try dbQueue.read { db
try Player.find(db, id: 1)
try Player.find(db, key: 1)
}
player.creationDate // optional 😕
player.modificationDate // optional 😕
@@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players
```swift
/// `Player` deals with unsaved players
struct Player: Identifiable {
struct Player {
var id: Int64? // optional
var creationDate: Date? // optional
var modificationDate: Date? // optional
@@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
```swift
// The base Player type
struct Player: Identifiable {
struct Player {
var id: Int64?
var creationDate: Date?
var modificationDate: Date?
+91
View File
@@ -0,0 +1,91 @@
/// A JSON column in a database table.
///
/// ## Overview
///
/// `JSONColumn` has benefits over ``Column`` for database columns that
/// contain JSON strings.
///
/// It behaves like a regular `Column`, with all extra conveniences and
/// behaviors of ``SQLJSONExpressible``.
///
/// For example, the sample code below directly accesses the "countryCode"
/// key of the "address" JSON column:
///
/// ```swift
/// struct Player: Codable {
/// var id: Int64
/// var name: String
/// var address: Address
/// }
///
/// struct Address: Codable {
/// var street: String
/// var city: String
/// var countryCode: String
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// enum Columns {
/// static let id = Column(CodingKeys.id)
/// static let name = Column(CodingKeys.name)
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn!
/// }
/// }
///
/// try dbQueue.write { db in
/// // In a real app, table creation should happen in a migration.
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// t.column("address", .jsonText).notNull()
/// }
///
/// // Fetch all country codes
/// // SELECT DISTINCT address ->> 'countryCode' FROM player
/// let countryCodes: [String] = try Player
/// .select(Player.Columns.address["countryCode"], as: String.self)
/// .distinct()
/// .fetchAll(db)
/// }
/// ```
///
/// > Tip: When you can not create a `JSONColumn`, you'll get the same
/// > convenient access to JSON subcomponents
/// > with ``SQLSpecificExpressible/asJSON``.
/// >
/// > For example, the above sample can be adapted as below:
/// >
/// > ```swift
/// > extension Player: FetchableRecord, PersistableRecord {
/// > // That's another valid way to define columns.
/// > // But we don't have any JSONColumn this time.
/// > enum Columns: String, ColumnExpression {
/// > case id, name, address
/// > }
/// > }
/// >
/// > try dbQueue.write { db in
/// > // Fetch all country codes
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
/// > let countryCodes: [String] = try Player
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
/// > .distinct()
/// > .fetchAll(db)
/// > }
/// > ```
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
public var name: String
/// Creates a `JSONColumn` given its name.
///
/// The name should be unqualified, such as `"score"`. Qualified name such
/// as `"player.score"` are unsupported.
public init(_ name: String) {
self.name = name
}
/// Creates a `JSONColumn` given a `CodingKey`.
public init(_ codingKey: some CodingKey) {
self.name = codingKey.stringValue
}
}
+435
View File
@@ -0,0 +1,435 @@
/// A type of SQL expression that is interpreted as a JSON value.
///
/// ## Overview
///
/// JSON values that conform to `SQLJSONExpressible` have two purposes:
///
/// - They provide Swift APIs for accessing their JSON subcomponents at
/// the SQL level.
///
/// - When used in a JSON-building function such as
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)``,
/// they are parsed and interpreted as JSON, not as plain strings.
///
/// To build a JSON value, create a ``JSONColumn``, or call the
/// ``SQLSpecificExpressible/asJSON`` property of any
/// other expression.
///
/// For example, here are some JSON values:
///
/// ```swift
/// // JSON columns:
/// JSONColumn("info")
/// Column("info").asJSON
///
/// // The JSON array [1, 2, 3]:
/// "[1, 2, 3]".databaseValue.asJSON
///
/// // A JSON value that will trigger a
/// // "malformed JSON" SQLite error when
/// // parsed by SQLite:
/// "{foo".databaseValue.asJSON
/// ```
///
/// The expressions below are not JSON values:
///
/// ```swift
/// // A plain column:
/// Column("info")
///
/// // Plain strings:
/// "[1, 2, 3]"
/// "{foo"
/// ```
///
/// ## Access JSON subcomponents
///
/// JSON values provide access to the [`->` and `->>` SQL operators](https://www.sqlite.org/json1.html)
/// and other SQLite JSON functions:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// ## Build JSON objects and arrays from JSON values
///
/// When used in a JSON-building function such as
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)-5iswr``,
/// JSON values are parsed and interpreted as JSON, not as plain strings.
///
/// In the example below, we can see how the `JSONColumn` is interpreted as
/// JSON, while the `Column` with the same name is interpreted as a
/// plain string:
///
/// ```swift
/// let elements: [any SQLExpressible] = [
/// JSONColumn("address"),
/// Column("address"),
/// ]
///
/// let array = Database.jsonArray(elements)
///
/// // SELECT JSON_ARRAY(JSON(address), address) FROM player
/// // → '[{"country":"FR"},"{\"country\":\"FR\"}"]'
/// // <--- object ---> <------ string ------>
/// let json = try Player
/// .select(array, as: String.self)
/// .fetchOne(db)
/// ```
///
/// ## Topics
///
/// ### Accessing JSON subcomponents
///
/// - ``subscript(_:)``
/// - ``jsonExtract(atPath:)``
/// - ``jsonExtract(atPaths:)``
/// - ``jsonRepresentation(atPath:)``
///
/// ### Supporting Types
///
/// - ``AnySQLJSONExpressible``
public protocol SQLJSONExpressible: SQLSpecificExpressible { }
extension ColumnExpression where Self: SQLJSONExpressible {
/// Returns an SQL column that is interpreted as a JSON value.
public var sqlExpression: SQLExpression {
.column(name).withPreferredJSONInterpretation(.jsonValue)
}
}
// This type only grants access to `SQLJSONExpressible` apis. The fact that
// it is a JSON value is embedded in its
// `sqlExpression.preferredJSONInterpretation`.
/// A type-erased ``SQLJSONExpressible``.
public struct AnySQLJSONExpressible: SQLJSONExpressible {
/// An SQL expression that is interpreted as a JSON value.
public let sqlExpression: SQLExpression
public init(_ base: some SQLJSONExpressible) {
self.init(sqlExpression: base.sqlExpression)
}
/// - Precondition: `sqlExpression` is a JSON value
init(sqlExpression: SQLExpression) {
assert(sqlExpression.preferredJSONInterpretation == .jsonValue)
self.sqlExpression = sqlExpression
}
}
extension SQLSpecificExpressible {
/// Returns an expression that is interpreted as a JSON value.
///
/// For example:
///
/// ```swift
/// let info = Column("info").asJSON
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// For more information, see ``SQLJSONExpressible``.
public var asJSON: AnySQLJSONExpressible {
AnySQLJSONExpressible(sqlExpression: sqlExpression.withPreferredJSONInterpretation(.jsonValue))
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public subscript(_ path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
Database.jsonExtract(self, atPath: path)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
Database.jsonExtract(self, atPaths: paths)
}
/// Returns a valid JSON string with the `->` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
}
}
#else
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info ->> 'firstName' FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info["firstName"], as: String.self)
/// .fetchOne(db)
///
/// // SELECT info ->> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info["address"], as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public subscript(_ path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
/// // → 'Arthur'
/// let firstName = try Player
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let address = try Player
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
Database.jsonExtract(self, atPath: path)
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
/// // → '["Arthur","Miller"]'
/// let nameComponents = try Player
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
Database.jsonExtract(self, atPaths: paths)
}
/// Returns a valid JSON string with the `->` SQL operator.
///
/// For example:
///
/// ```swift
/// let info = JSONColumn("info")
///
/// // SELECT info -> 'firstName' FROM player
/// // → '"Arthur"'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
/// .fetchOne(db)
///
/// // SELECT info -> 'address' FROM player
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
/// let name = try Player
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
/// .fetchOne(db)
/// ```
///
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or an JSON object field label, or an array index.
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
}
}
// TODO: Enable when those apis are ready.
// @available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
// extension ColumnExpression where Self: SQLJSONExpressible {
// /// Updates a columns with the `JSON_PATCH` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_PATCH(address, '{"country": "FR"}')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonPatch(#"{"country": "FR"}"#)
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
// public func jsonPatch(
// with patch: some SQLExpressible)
// -> ColumnAssignment
// {
// .init(columnName: name, value: Database.jsonPatch(self, with: patch))
// }
//
// /// Updates a columns with the `JSON_REMOVE` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonRemove(atPath: "$.country")
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - Parameters:
// /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
// public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment {
// .init(columnName: name, value: Database.jsonRemove(self, atPath: path))
// }
//
// /// Updates a columns with the `JSON_REMOVE` SQL function.
// ///
// /// For example:
// ///
// /// ```swift
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country', '$.city')
// /// try Player.updateAll(db, [
// /// JSONColumn("address").jsonRemove(atPatsh: ["$.country", "$.city"])
// /// ])
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
// ///
// /// - Parameters:
// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
// public func jsonRemove<C>(atPaths paths: C)
// -> ColumnAssignment
// where C: Collection, C.Element: SQLExpressible
// {
// .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths))
// }
//
// }
#endif
+777
View File
@@ -0,0 +1,777 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.json(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
public static func json(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON", [value.sqlExpression])
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element == any SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
/// Database.jsonArrayLength("[1,2,3,4]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
///
/// - Parameters:
/// - value: A JSON array.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonArrayLength(
_ value: some SQLExpressible,
atPath path: some SQLExpressible)
-> SQLExpression
{
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonInsert<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonReplace<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonSet<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
/// key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.jsonObject(["e": 5])),
/// ])
///
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.json(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
public static func jsonObject<C>(_ elements: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
public static func jsonPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression])
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_VALID` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_VALID('{"x":35') → 0
/// Database.jsonIsValid(#"{"x":35"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
/// The `JSON_QUOTE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_QUOTE('[1]') → '"[1]"'
/// Database.jsonQuote("[1]")
///
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
/// Database.jsonQuote(Database.json("[1]"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
}
}
#else
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.json(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
public static func json(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON", [value.sqlExpression])
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonArray<C>(_ values: C) -> SQLExpression
where C: Collection, C.Element == any SQLExpressible
{
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
/// Database.jsonArrayLength("[1,2,3,4]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
}
/// The number of elements in a JSON array, as returned by the
/// `JSON_ARRAY_LENGTH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
///
/// - Parameters:
/// - value: A JSON array.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonArrayLength(
_ value: some SQLExpressible,
atPath path: some SQLExpressible)
-> SQLExpression
{
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_ERROR_POSITION` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_ERROR_POSITION(info)
/// Database.jsonErrorPosition(Column("info"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ERROR_POSITION", [value.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonInsert<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonReplace<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonSet<C>(
_ value: some SQLExpressible,
_ assignments: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
/// key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.jsonObject(["e": 5])),
/// ])
///
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonObject([
/// "c": Database.json(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
public static func jsonObject<C>(_ elements: C)
-> SQLExpression
where C: Collection,
C.Element == (key: String, value: any SQLExpressible)
{
.function("JSON_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSON_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
public static func jsonPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
-> SQLExpression
where C: Collection, C.Element: SQLExpressible
{
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression])
}
/// The `JSON_TYPE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSON_VALID` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_VALID('{"x":35') → 0
/// Database.jsonIsValid(#"{"x":35"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
/// Returns a valid JSON string with the `JSON_QUOTE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSON_QUOTE('[1]') → '"[1]"'
/// Database.jsonQuote("[1]")
///
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
/// Database.jsonQuote(Database.json("[1]"))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_ARRAY` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupArray(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_ARRAY", [value.sqlExpression.jsonBuilderExpression])
}
/// The `JSON_GROUP_OBJECT` SQL function.
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonGroupObject(key: some SQLExpressible, value: some SQLExpressible) -> SQLExpression {
.function("JSON_GROUP_OBJECT", [key.sqlExpression, value.sqlExpression.jsonBuilderExpression])
}
}
#endif
@@ -127,7 +127,7 @@ extension AssociationToMany {
/// }
/// ```
public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -174,7 +174,7 @@ extension AssociationToMany {
/// }
/// ```
public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -221,7 +221,7 @@ extension AssociationToMany {
/// }
/// ```
public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -271,7 +271,7 @@ extension AssociationToMany {
/// }
/// ```
public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
@@ -321,7 +321,7 @@ extension AssociationToMany {
/// }
/// ```
public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression]))
let aggregate = makeAggregate(.function("TOTAL", [expression.sqlExpression]))
if let column = expression as? any ColumnExpression {
let name = key.singularizedName
// Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)`
@@ -442,7 +442,11 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// make it impractical to define `filter(id:)`, `fetchOne(_:key:)`,
// `deleteAll(_:ids:)` etc.
if let recordType = RowDecoder.self as? any EncodableRecord.Type {
if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
if Sequence.Element.self == Data.self || Sequence.Element.self == Optional<Data>.self {
let strategy = recordType.databaseDataEncodingStrategy
let keys = keys.compactMap { ($0 as! Data?).flatMap(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
} else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
let strategy = recordType.databaseDateEncodingStrategy
let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue }
return filter(rawKeys: keys)
+17
View File
@@ -27,6 +27,7 @@ public protocol ColumnExpression: SQLSpecificExpressible {
}
extension ColumnExpression {
/// Returns an SQL column.
public var sqlExpression: SQLExpression {
.column(name)
}
@@ -65,11 +66,27 @@ extension ColumnExpression where Self == Column {
/// A column in a database table.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// var score: Int
/// }
///
/// let maximumScore = try dbQueue.read { db in
/// // SELECT MAX(score) FROM player
/// try Player
/// .select(max(Column("score")), as: Int.self)
/// .fetchOne(db)
/// }
/// ```
///
/// ## Topics
///
/// ### Standard Columns
///
/// - ``rowID-3bn70``
/// - ``rank``
///
/// ### Creating A Column
///
+410 -138
View File
@@ -37,6 +37,25 @@
public struct SQLExpression {
private var impl: Impl
/// The preferred interpretation of the expression in JSON
/// building contexts (see `jsonBuilderExpression`).
///
/// ```swift
/// // Considering:
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → [[1,2,3]]
///
/// // Compare an expression with preferredJSONInterpretation = .unspecified:
/// // JSON_ARRAY("info")
/// Database.jsonArray([Column("info")])
///
/// // ...with an expression with preferredJSONInterpretation = .jsonValue:
/// // JSON_ARRAY(JSON("info"))
/// Database.jsonArray([Column("info").jsonValue])
/// Database.jsonArray([JSONColumn("info")])
/// ```
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
/// The private implementation of the public `SQLExpression`.
private enum Impl {
/// A column.
@@ -146,7 +165,7 @@ public struct SQLExpression {
///
/// <function>(<argument>, ...)
/// <function>(DISTINCT <argument>)
case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression])
case function(String, flags: SQLFunctionFlags, arguments: [SQLExpression])
/// An expression that checks for zero or positive values.
///
@@ -178,6 +197,90 @@ public struct SQLExpression {
/// - For views, it is true iff any column is not null.
/// - For CTEs, it is not implemented yet.
case qualifiedExists(TableAlias, isNegated: Bool)
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Impl {
switch self {
case .databaseValue,
.qualifiedColumn,
.qualifiedFastPrimaryKey,
.qualifiedExists,
.subquery,
.exists:
return self
case let .column(name):
return .qualifiedColumn(name, alias)
case let .rowValue(expressions):
return .rowValue(expressions.map { $0.qualified(with: alias) })
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .between(
expression: expression,
lowerBound: lowerBound,
upperBound: upperBound,
isNegated: isNegated):
return .between(
expression: expression.qualified(with: alias),
lowerBound: lowerBound.qualified(with: alias),
upperBound: upperBound.qualified(with: alias),
isNegated: isNegated)
case let .binary(op, lhs, rhs):
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .escapableBinary(op, lhs, rhs, escape):
return .escapableBinary(
op,
lhs.qualified(with: alias),
rhs.qualified(with: alias),
escape: escape?.qualified(with: alias))
case let .associativeBinary(op, expressions):
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
case let .in(expression, collection, isNegated: isNegated):
return .in(
expression.qualified(with: alias),
collection.qualified(with: alias),
isNegated: isNegated
)
case let .unary(op, expression):
return .unary(op, expression.qualified(with: alias))
case let .compare(op, lhs, rhs):
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .tableMatch(a, expression):
return .tableMatch(a, expression.qualified(with: alias))
case let .not(expression):
return .not(expression.qualified(with: alias))
case let .collated(expression, collationName):
return .collated(expression.qualified(with: alias), collationName)
case .countAll:
return .countAll
case let .function(name, flags: flags, arguments: arguments):
return .function(
name,
flags: flags,
arguments: arguments.map { $0.qualified(with: alias) })
case let .isEmpty(expression, isNegated: isNegated):
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
case .fastPrimaryKey:
return .qualifiedFastPrimaryKey(alias)
}
}
}
/// `BooleanTest` supports truthiness tests.
@@ -344,11 +447,22 @@ public struct SQLExpression {
/// The SQL operator
let sql: String
/// Creates a binary operator
/// A boolean value indicating if the operator is known to return a
/// JSON value.
///
/// BinaryOperator("-")
init(_ sql: String) {
/// A false value does not provide any information.
let isJSONValue: Bool
/// Creates a binary operator.
///
/// For example:
///
/// ```
/// BinaryOperator("-")
/// ```
init(_ sql: String, isJSONValue: Bool = false) {
self.sql = sql
self.isJSONValue = isJSONValue
}
/// The `<` binary operator
@@ -377,6 +491,14 @@ public struct SQLExpression {
/// The `>>` bitwise right shift operator
static let rightShift = BinaryOperator(">>")
// Not guarded by availability checks, but only available for SQLite 3.38+
/// The `->` SQL operator
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
// Not guarded by availability checks, but only available for SQLite 3.38+
/// The `->>` SQL operator
static let jsonExtractSQL = BinaryOperator("->>")
}
/// `EscapableBinaryOperator` is an SQLite binary operator that accepts an
@@ -444,6 +566,36 @@ public struct SQLExpression {
/// The `~` unary operator
static let bitwiseNot = UnaryOperator("~")
}
/// Describes the interpretation of an expression in a JSON
/// building context.
enum JSONInterpretation {
/// JSON interpretation is deferred to SQLite:
///
/// ```swift
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
/// Database.jsonArray(["[1, 2, 3]"])
///
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
/// Database.jsonArray([Database.json("[1, 2, 3]")])
///
/// // JSON_ARRAY("info")
/// Database.jsonArray([Column("info")])
/// ```
case deferredToSQLite
/// Expression is interpreted as a JSON value:
///
/// ```swift
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
/// Database.jsonArray(["[1, 2, 3]"].jsonValue)
///
/// // JSON_ARRAY(JSON("info"))
/// Database.jsonArray([Column("info").jsonValue])
/// Database.jsonArray([JSONColumn("info")])
/// ```
case jsonValue
}
}
// MARK: - Creating Expressions
@@ -763,41 +915,31 @@ extension SQLExpression {
///
/// COUNT(<expression>)
static func count(_ expression: SQLExpression) -> Self {
aggregate("COUNT", [expression])
function("COUNT", [expression])
}
/// The `COUNT(DISTINCT)` function.
///
/// COUNT(DISTINCT <expression>)
static func countDistinct(_ expression: SQLExpression) -> Self {
distinctAggregate("COUNT", expression)
function("COUNT", [expression], flags: .init(isAggregate: true, isDistinct: true))
}
/// A function call.
///
/// <function>(<argument>, ...)
///
/// - warning: for aggregate functions, call one of:
/// - `SQLExpression.aggregate(_:_:)`,
/// - `SQLExpression.distinctAggregate(_:_:)`,
/// - `SQLExpression.countDistinct(_:)`
/// - `SQLExpression.countAll`.
static func function(_ name: String, _ arguments: [SQLExpression]) -> Self {
self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments))
.init(impl: .function(
name,
flags: .defaultFlags(for: name, argumentCount: arguments.count),
arguments: arguments))
}
/// An aggregate function call.
/// A function call with explicit flags.
///
/// <aggregate>(<argument>, ...)
static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self {
self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments))
}
/// A distinct aggregate function call.
///
/// <aggregate>(DISTINCT <argument>)
static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self {
self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument]))
/// <function>(<argument>, ...)
static func function(_ name: String, _ arguments: [SQLExpression], flags: SQLFunctionFlags) -> Self {
.init(impl: .function(name, flags: flags, arguments: arguments))
}
/// An expression that checks for zero or positive values.
@@ -843,6 +985,21 @@ extension SQLExpression {
}
}
// MARK: - Deriving Expressions
extension SQLExpression {
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> Self {
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
}
func withPreferredJSONInterpretation(_ interpretation: JSONInterpretation) -> Self {
.init(impl: impl, preferredJSONInterpretation: interpretation)
}
}
// MARK: - Expressions Information
extension SQLExpression {
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
///
@@ -906,7 +1063,7 @@ extension SQLExpression {
case let .collated(expression, _):
return try expression.column(db, for: alias, acceptsBijection: acceptsBijection)
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
case let .function(name, flags: flags, arguments: arguments) where !flags.isAggregate:
guard acceptsBijection else {
return nil
}
@@ -1101,11 +1258,11 @@ extension SQLExpression {
case .countAll:
return "COUNT(*)"
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
assert(!distinct || aggregate, "distinct requires aggregate")
assert(!distinct || arguments.count == 1, "distinct requires a single argument")
case let .function(name, flags: flags, arguments: arguments):
assert(!flags.isDistinct || flags.isAggregate, "distinct requires aggregate")
assert(!flags.isDistinct || arguments.count == 1, "distinct requires a single argument")
return try name
+ (distinct ? "(DISTINCT " : "(")
+ (flags.isDistinct ? "(DISTINCT " : "(")
+ arguments.map { try $0.sql(context) }.joined(separator: ", ")
+ ")"
@@ -1516,17 +1673,6 @@ extension SQLExpression {
}
}
private static let knownPureFunctions = [
"ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL",
"IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD",
"LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM",
"NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND",
"RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID",
"SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM",
"TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB",
]
/// Returns true if the expression has a unique value when SQLite runs
/// a request.
///
@@ -1567,13 +1713,8 @@ extension SQLExpression {
let .collated(expression, _):
return expression.isConstantInRequest
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
let name = name.uppercased()
guard ((name == "MAX" || name == "MIN") && arguments.count > 1)
|| Self.knownPureFunctions.contains(name)
else {
return false // Don't know - assume not constant
}
case let .function(_, flags: flags, arguments: arguments)
where flags.isPure && !flags.isAggregate:
return arguments.allSatisfy(\.isConstantInRequest)
@@ -1582,84 +1723,6 @@ extension SQLExpression {
}
}
/// Returns a qualified expression
func qualified(with alias: TableAlias) -> SQLExpression {
switch impl {
case .databaseValue,
.qualifiedColumn,
.qualifiedFastPrimaryKey,
.qualifiedExists,
.subquery,
.exists:
return self
case let .column(name):
return .qualifiedColumn(name, alias)
case let .rowValue(expressions):
assert(!expressions.isEmpty)
return .rowValue(expressions.map { $0.qualified(with: alias) })!
case let .literal(sqlLiteral):
return .literal(sqlLiteral.qualified(with: alias))
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
return .between(
expression: expression.qualified(with: alias),
lowerBound: lowerBound.qualified(with: alias),
upperBound: upperBound.qualified(with: alias),
isNegated: isNegated)
case let .binary(op, lhs, rhs):
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .escapableBinary(op, lhs, rhs, escape):
return .escapableBinary(
op,
lhs.qualified(with: alias),
rhs.qualified(with: alias),
escape: escape?.qualified(with: alias))
case let .associativeBinary(op, expressions):
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
case let .in(expression, collection, isNegated: isNegated):
return .in(
expression.qualified(with: alias),
collection.qualified(with: alias),
isNegated: isNegated
)
case let .unary(op, expression):
return .unary(op, expression.qualified(with: alias))
case let .compare(op, lhs, rhs):
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
case let .tableMatch(a, expression):
return .tableMatch(a, expression.qualified(with: alias))
case let .not(expression):
return .not(expression.qualified(with: alias))
case let .collated(expression, collationName):
return .collated(expression.qualified(with: alias), collationName)
case .countAll:
return .countAll
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct,
arguments: arguments.map { $0.qualified(with: alias) }))
case let .isEmpty(expression, isNegated: isNegated):
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
case .fastPrimaryKey:
return .qualifiedFastPrimaryKey(alias)
}
}
/// Returns true if the expression is an aggregate.
///
/// When in doubt, returns false.
@@ -1709,8 +1772,10 @@ extension SQLExpression {
return false
case .countAll,
.function(_, aggregate: true, distinct: _, arguments: _):
case .countAll:
return true
case let .function(_, flags: flags, arguments: _) where flags.isAggregate:
return true
default:
@@ -1719,17 +1784,223 @@ extension SQLExpression {
}
}
// MARK: - Function Flags
/// Information about a function
struct SQLFunctionFlags {
/// A boolean value indicating if a function is known to be pure.
///
/// A false value does not provide any information.
var isPure = false
/// A boolean value indicating if a function is known to be
/// an aggregate.
///
/// A false value does not provide any information.
var isAggregate = false
/// A boolean value indicating if the function should have `DISTINCT`
/// in its SQL generation (as in `COUNT(DISTINCT ...)`).
var isDistinct = false
/// A boolean value indicating if a function is known to return a
/// JSON value.
///
/// A false value does not provide any information.
var isJSONValue = false
}
extension SQLFunctionFlags {
// TODO: add missing pure functions:
// https://www.sqlite.org/lang_aggfunc.html
// https://www.sqlite.org/lang_datefunc.html
// https://www.sqlite.org/lang_mathfunc.html
private static let knownPureFunctions: Set<String> = [
"ABS",
"CHAR",
"COALESCE",
"GLOB",
"HEX",
"IFNULL",
"IIF",
"INSTR",
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"LENGTH",
"LIKE",
"LIKELIHOOD",
"LIKELY",
"LOAD_EXTENSION",
"LOWER",
"LTRIM",
"NULLIF",
"PRINTF",
"QUOTE",
"REPLACE",
"ROUND",
"RTRIM",
"SOUNDEX",
"SQLITE_COMPILEOPTION_GET",
"SQLITE_COMPILEOPTION_USED",
"SQLITE_SOURCE_ID",
"SQLITE_VERSION",
"SUBSTR",
"TRIM",
"TYPEOF",
"UNICODE",
"UNLIKELY",
"UPPER",
"ZEROBLOB",
]
private static let knownAggregateFunctions: Set<String> = [
"AVG",
"COUNT",
"GROUP_CONCAT",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"MAX", // when single argument
"MIN", // when single argument
"SUM",
"TOTAL",
]
private static let knownFunctionsReturningJSONValue: Set<String> = [
"JSON",
"JSON_ARRAY",
"JSON_GROUP_ARRAY",
"JSON_GROUP_OBJECT",
"JSON_INSERT",
"JSON_OBJECT",
"JSON_PATCH",
"JSON_REMOVE",
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
]
/// Infers flags from the function name and number of arguments.
static func defaultFlags(for functionName: String, argumentCount: Int) -> Self {
var flags = SQLFunctionFlags()
let name = functionName.uppercased()
flags.isPure = Self.knownPureFunctions.contains(name)
if (name == "MAX" || name == "MIN") && argumentCount > 1 {
flags.isPure = true
} else {
flags.isAggregate = Self.knownAggregateFunctions.contains(name.uppercased())
}
if name == "JSON_EXTRACT" && argumentCount > 2 {
flags.isJSONValue = true
} else {
flags.isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
}
return flags
}
}
// MARK: - JSON
extension SQLExpression {
/// A boolean value indicating if the expression is known to be a
/// JSON value.
///
/// A false value does not provide any information.
///
/// For examples:
///
/// ```swift
/// // isJSONValue is true:
/// //
/// // NULL
/// // JSON('[1, 2, 3]')
/// // info -> 'address'
/// DatabaseValue.null
/// Database.json("[1, 2, 3]")
/// JSONColumn("info").jsonRepresentation(forKey: "address")
///
/// // isJSONValue is false
/// //
/// // '[1, 2, 3]'
/// // info
/// // info ->> 'address'
/// [1, 2, 3].databaseValue
/// JSONColumn("info")
/// JSONColumn("info")["address"]
/// ```
var isJSONValue: Bool {
switch impl {
case .databaseValue(.null):
return true
case let .binary(op, _, _):
return op.isJSONValue
case let .collated(expression, _):
return expression.isJSONValue
case let .function(_, flags: flags, arguments: _):
return flags.isJSONValue
default:
return false
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
case .deferredToSQLite:
return self
case .jsonValue:
if isJSONValue {
return self
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
}
#else
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
case .deferredToSQLite:
return self
case .jsonValue:
if isJSONValue {
return self
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
}
#endif
}
// MARK: - SQLExpressible
/// A type that can be used as an SQL expression.
///
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
///
/// ## Topics
///
/// ### Supporting Type
///
/// - ``SQLExpression``
public protocol SQLExpressible {
/// Returns an SQL expression.
var sqlExpression: SQLExpression { get }
@@ -1754,11 +2025,6 @@ extension SQLExpressible where Self == Column {
///
/// ## Topics
///
/// ### Column Expressions
///
/// - ``Column``
/// - ``ColumnExpression``
///
/// ### Applying a Collation
///
/// - ``collating(_:)-2mr78``
@@ -1766,6 +2032,8 @@ extension SQLExpressible where Self == Column {
///
/// ### SQL Functions & Operators
///
/// See also JSON functions in <doc:JSON>.
///
/// - ``abs(_:)-5l6xp``
/// - ``average(_:)``
/// - ``capitalized``
@@ -1786,6 +2054,10 @@ extension SQLExpressible where Self == Column {
/// - ``uppercased``
/// - ``SQLDateModifier``
///
/// ### Interpreting an expression as JSON
///
/// - ``asJSON``
///
/// ### Creating Ordering Terms
///
/// - ``asc``
+5 -5
View File
@@ -19,7 +19,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// average(Column("length"))
/// ```
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregate("AVG", [value.sqlExpression])
.function("AVG", [value.sqlExpression])
}
/// The `COUNT` SQL function.
@@ -81,7 +81,7 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// max(Column("score"))
/// ```
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregate("MAX", [value.sqlExpression])
.function("MAX", [value.sqlExpression])
}
/// The `MIN` SQL function.
@@ -93,7 +93,7 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// min(Column("score"))
/// ```
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregate("MIN", [value.sqlExpression])
.function("MIN", [value.sqlExpression])
}
/// The `SUM` SQL function.
@@ -109,7 +109,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregate("SUM", [value.sqlExpression])
.function("SUM", [value.sqlExpression])
}
/// The `TOTAL` SQL function.
@@ -125,7 +125,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregate("TOTAL", [value.sqlExpression])
.function("TOTAL", [value.sqlExpression])
}
// MARK: - String functions
@@ -431,6 +431,15 @@ public class TableAlias {
expression.sqlExpression.qualified(with: self)
}
public subscript(_ expression: some SQLJSONExpressible &
SQLSpecificExpressible &
SQLSelectable &
SQLOrderingTerm)
-> AnySQLJSONExpressible
{
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
}
/// Returns an SQL ordering term that refers to the aliased table.
///
/// For example, let's sort books by author name first, and then by title:
@@ -1,31 +1,33 @@
struct SQLIndexGenerator {
let name: String
let table: String
let columns: [String]
let expressions: [SQLExpression]
let options: IndexOptions
let condition: SQLExpression?
func sql(_ db: Database) throws -> String {
var chunks: [String] = []
chunks.append("CREATE")
var sql: SQL = "CREATE"
if options.contains(.unique) {
chunks.append("UNIQUE")
sql += " UNIQUE"
}
chunks.append("INDEX")
sql += " INDEX"
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
sql += " IF NOT EXISTS"
}
chunks.append(name.quotedDatabaseIdentifier)
chunks.append("ON")
chunks.append("""
\(table.quotedDatabaseIdentifier)(\
\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
)
""")
sql += " \(identifier: name) ON \(identifier: table)("
sql += expressions.map { SQL($0) }.joined(separator: ", ")
sql += ")"
if let condition {
try chunks.append("WHERE \(condition.quotedSQL(db))")
sql += " WHERE \(condition)"
}
return chunks.joined(separator: " ")
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
return try sql.sql(context)
}
}
@@ -33,7 +35,7 @@ extension SQLIndexGenerator {
init(index: IndexDefinition) {
name = index.name
table = index.table
columns = index.columns
expressions = index.expressions
options = index.options
condition = index.condition
}
@@ -406,14 +406,14 @@ extension SQLTableGenerator {
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
columns: columnNames,
expressions: columnNames.map { .column($0) },
options: indexOptions,
condition: nil)
case .unique:
indexGenerator = SQLIndexGenerator(
name: Database.defaultIndexName(on: originTable, columns: columnNames),
table: originTable,
columns: columnNames,
expressions: columnNames.map { .column($0) },
options: indexOptions.union([.unique]),
condition: nil)
}
@@ -559,7 +559,7 @@ public final class ColumnDefinition {
return IndexDefinition(
name: "\(table)_on_\(name)",
table: table,
columns: [name],
expressions: [.column(name)],
options: options,
condition: nil)
}
@@ -433,7 +433,7 @@ extension Database {
try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)")
}
/// Creates an index.
/// Creates an index on the specified table and columns.
///
/// For example:
///
@@ -443,12 +443,8 @@ extension Database {
/// ```
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use a raw SQL
/// query:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
/// and use specific collations. To create such an index, use
/// ``create(index:on:expressions:options:condition:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
@@ -481,7 +477,7 @@ extension Database {
try create(index: name, on: table, columns: columns, options: options, condition: condition)
}
/// Creates an index.
/// Creates an index on the specified table and columns.
///
/// For example:
///
@@ -526,7 +522,7 @@ extension Database {
let index = IndexDefinition(
name: name,
table: table,
columns: columns,
expressions: columns.map { .column($0) },
options: options,
condition: condition?.sqlExpression)
let generator = SQLIndexGenerator(index: index)
@@ -534,7 +530,58 @@ extension Database {
try execute(sql: sql)
}
/// Creates an index on the specified table and columns.
/// Creates an index on the specified table and expressions.
///
/// This method can generally create indexes on expressions (see
/// <https://www.sqlite.org/expridx.html>):
///
/// ```swift
/// // CREATE INDEX txy ON t(x+y)
/// try db.create(
/// index: "txy",
/// on: "t",
/// expressions: [Column("x") + Column("y")])
/// ```
///
/// In particular, you can specify the collation on indexed
/// columns (see <https://www.sqlite.org/lang_createindex.html#collations>):
///
/// ```swift
/// // CREATE INDEX index_player_name ON player(name COLLATE NOCASE)
/// try db.create(
/// index: "index_player_name",
/// on: "player",
/// expressions: [Column("name").collating(.nocase)])
/// ```
///
/// - parameters:
/// - name: The index name.
/// - table: The name of the indexed table.
/// - expressions: The indexed expressions.
/// - options: Index creation options.
/// - condition: If not nil, creates a partial index
/// (see <https://www.sqlite.org/partialindex.html>).
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(
index name: String,
on table: String,
expressions: [any SQLExpressible],
options: IndexOptions = [],
condition: (any SQLExpressible)? = nil)
throws
{
let index = IndexDefinition(
name: name,
table: table,
expressions: expressions.map { $0.sqlExpression },
options: options,
condition: condition?.sqlExpression)
let generator = SQLIndexGenerator(index: index)
let sql = try generator.sql(self)
try execute(sql: sql)
}
/// Creates an index with a default name on the specified table and columns.
///
/// The created index is named after the table and the column name(s):
///
@@ -554,12 +601,8 @@ extension Database {
/// ``create(index:on:columns:options:condition:)`` instead.
///
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
/// and use specific collations. To create such an index, use a raw SQL
/// query:
///
/// ```swift
/// try db.execute(sql: "CREATE INDEX ...")
/// ```
/// and use specific collations. To create such an index, use
/// ``create(index:on:expressions:options:condition:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
///
@@ -1,7 +1,7 @@
struct IndexDefinition {
let name: String
let table: String
let columns: [String]
let expressions: [SQLExpression]
let options: IndexOptions
let condition: SQLExpression?
}
+3 -1
View File
@@ -128,7 +128,9 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
}
fileprivate func encode<T>(_ value: T, forKey key: any CodingKey) throws where T: Encodable {
if let date = value as? Date {
if let data = value as? Data {
persist(Record.databaseDataEncodingStrategy.encode(data), forKey: key)
} else if let date = value as? Date {
persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key)
} else if let uuid = value as? UUID {
persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key)
+68
View File
@@ -20,11 +20,13 @@ import Foundation // For JSONEncoder
/// ### Configuring Persistence for the Standard Encodable Protocol
///
/// - ``databaseColumnEncodingStrategy-5sx4v``
/// - ``databaseDataEncodingStrategy-9y0c7``
/// - ``databaseDateEncodingStrategy-2gtc1``
/// - ``databaseEncodingUserInfo-8upii``
/// - ``databaseJSONEncoder(for:)-6x62c``
/// - ``databaseUUIDEncodingStrategy-2t96q``
/// - ``DatabaseColumnEncodingStrategy``
/// - ``DatabaseDataEncodingStrategy``
/// - ``DatabaseDateEncodingStrategy``
/// - ``DatabaseUUIDEncodingStrategy``
///
@@ -115,6 +117,24 @@ public protocol EncodableRecord {
/// ``encode(to:)-1mrt`` implementation.
static func databaseJSONEncoder(for column: String) -> JSONEncoder
/// The strategy for encoding `Data` columns.
///
/// This property is dedicated to ``EncodableRecord`` types that also
/// conform to the standard `Encodable` protocol and use the default
/// ``encode(to:)-1mrt`` implementation.
///
/// For example:
///
/// ```swift
/// struct Player: EncodableRecord, Encodable {
/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
///
/// // Encoded as SQL text. Data must contain valid UTF8 bytes.
/// var jsonData: Data
/// }
/// ```
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get }
/// The strategy for encoding `Date` columns.
///
/// This property is dedicated to ``EncodableRecord`` types that also
@@ -199,6 +219,12 @@ extension EncodableRecord {
return encoder
}
/// Returns the default strategy for encoding `Data` columns:
/// ``DatabaseDataEncodingStrategy/deferredToData``.
public static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy {
.deferredToData
}
/// Returns the default strategy for encoding `Date` columns:
/// ``DatabaseDateEncodingStrategy/deferredToDate``.
public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy {
@@ -423,6 +449,48 @@ extension Row {
}
}
// MARK: - DatabaseDataEncodingStrategy
/// `DatabaseDataEncodingStrategy` specifies how `EncodableRecord` types that
/// also adopt the standard `Encodable` protocol encode their `Data` properties
/// in the default <doc:/documentation/GRDB/EncodableRecord/encode(to:)-1mrt>
/// implementation.
///
/// For example:
///
/// ```swift
/// struct Player: EncodableRecord, Encodable {
/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
///
/// // Encoded as SQL text. Data must contain valid UTF8 bytes.
/// var jsonData: Data
/// }
/// ```
public enum DatabaseDataEncodingStrategy {
/// Encodes `Data` columns as SQL blob.
case deferredToData
/// Encodes `Data` columns as SQL text. Data must contain valid UTF8 bytes.
case text
/// Encodes `Data` column as the result of the user-provided function.
case custom((Data) -> (any DatabaseValueConvertible)?)
func encode(_ data: Data) -> DatabaseValue {
switch self {
case .deferredToData:
return data.databaseValue
case .text:
guard let string = String(data: data, encoding: .utf8) else {
fatalError("Invalid UTF8 data")
}
return string.databaseValue
case .custom(let format):
return format(data)?.databaseValue ?? .null
}
}
}
// MARK: - DatabaseDateEncodingStrategy
/// `DatabaseDateEncodingStrategy` specifies how `EncodableRecord` types that
+112 -5
View File
@@ -51,6 +51,7 @@ extension FetchableRecord where Self: Decodable {
/// The behavior of the decoder depends on the decoded type. See:
///
/// - ``FetchableRecord/databaseColumnDecodingStrategy-6uefz``
/// - ``FetchableRecord/databaseDataDecodingStrategy-71bh1``
/// - ``FetchableRecord/databaseDateDecodingStrategy-78y03``
/// - ``FetchableRecord/databaseDecodingUserInfo-77jim``
/// - ``FetchableRecord/databaseJSONDecoder(for:)-7lmxd``
@@ -258,7 +259,11 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
{
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
if type == Data.self {
return try R.databaseDataDecodingStrategy.decodeIfPresent(
fromRow: row,
atUncheckedIndex: index) as! T?
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decodeIfPresent(
fromRow: row,
atUncheckedIndex: index) as! T?
@@ -303,7 +308,9 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
{
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
if type == Data.self {
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T
@@ -546,9 +553,10 @@ extension ColumnDecoder: SingleValueDecodingContainer {
func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) }
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows decoding Date from String, or DatabaseValue from NULL.
if type == Date.self {
// TODO: not tested
if type == Data.self {
return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if type == Date.self {
return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T
} else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type {
return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T
@@ -566,6 +574,105 @@ private let iso8601Formatter: ISO8601DateFormatter = {
return formatter
}()
extension DatabaseDataDecodingStrategy {
fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data? {
if let sqliteStatement = row.sqliteStatement {
return try decodeIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decodeIfPresent(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
fileprivate func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Data {
if let sqliteStatement = row.sqliteStatement {
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: CInt(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
} else {
return try decode(
fromDatabaseValue: row[index],
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
/// - precondition: value is not NULL
fileprivate func decode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
assert(sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL, "unexpected NULL value")
switch self {
case .deferredToData:
return Data(sqliteStatement: sqliteStatement, index: index)
case .custom(let format):
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
guard let data = format(dbValue) else {
throw RowDecodingError.valueMismatch(
Data.self,
context: context(),
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
}
return data
}
}
fileprivate func decodeIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: CInt,
context: @autoclosure () -> RowDecodingContext)
throws -> Data?
{
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return try decode(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
}
fileprivate func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
if let data = dataFromDatabaseValue(dbValue) {
return data
} else {
throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue)
}
}
fileprivate func decodeIfPresent(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Data?
{
if dbValue.isNull {
return nil
} else if let data = dataFromDatabaseValue(dbValue) {
return data
} else {
throw RowDecodingError.valueMismatch(Data.self, context: context(), databaseValue: dbValue)
}
}
// Returns nil if decoding fails
private func dataFromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
switch self {
case .deferredToData:
return Data.fromDatabaseValue(dbValue)
case .custom(let format):
return format(dbValue)
}
}
}
extension DatabaseDateDecodingStrategy {
fileprivate func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Date? {
if let sqliteStatement = row.sqliteStatement {
+64
View File
@@ -89,10 +89,12 @@ import Foundation
/// ### Configuring Row Decoding for the Standard Decodable Protocol
///
/// - ``databaseColumnDecodingStrategy-6uefz``
/// - ``databaseDataDecodingStrategy-71bh1``
/// - ``databaseDateDecodingStrategy-78y03``
/// - ``databaseDecodingUserInfo-77jim``
/// - ``databaseJSONDecoder(for:)-7lmxd``
/// - ``DatabaseColumnDecodingStrategy``
/// - ``DatabaseDataDecodingStrategy``
/// - ``DatabaseDateDecodingStrategy``
///
/// ### Supporting Types
@@ -153,6 +155,29 @@ public protocol FetchableRecord {
/// ``init(row:)-4ptlh`` implementation.
static func databaseJSONDecoder(for column: String) -> JSONDecoder
/// The strategy for decoding `Data` columns.
///
/// This property is dedicated to ``FetchableRecord`` types that also
/// conform to the standard `Decodable` protocol and use the default
/// ``init(row:)-4ptlh`` implementation.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue
/// guard let base64Data = Data.fromDatabaseValue(dbValue) else {
/// return nil
/// }
/// return Data(base64Encoded: base64Data)
/// }
///
/// // Decoded from both database base64 strings and blobs
/// var myData: Data
/// }
/// ```
static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get }
/// The strategy for decoding `Date` columns.
///
/// This property is dedicated to ``FetchableRecord`` types that also
@@ -216,6 +241,12 @@ extension FetchableRecord {
return decoder
}
/// The default strategy for decoding `Data` columns is
/// ``DatabaseDataDecodingStrategy/deferredToData``.
public static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy {
.deferredToData
}
/// The default strategy for decoding `Date` columns is
/// ``DatabaseDateDecodingStrategy/deferredToDate``.
public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy {
@@ -823,6 +854,39 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
}
}
// MARK: - DatabaseDataDecodingStrategy
/// `DatabaseDataDecodingStrategy` specifies how `FetchableRecord` types that
/// also adopt the standard `Decodable` protocol decode their
/// `Data` properties.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, Decodable {
/// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue
/// guard let base64Data = Data.fromDatabaseValue(dbValue) else {
/// return nil
/// }
/// return Data(base64Encoded: base64Data)
/// }
///
/// // Decoded from both database base64 strings and blobs
/// var myData: Data
/// }
/// ```
public enum DatabaseDataDecodingStrategy {
/// Decodes `Data` columns from SQL blobs and UTF8 text.
case deferredToData
/// Decodes `Data` columns according to the user-provided function.
///
/// If the database value does not contain a suitable value, the function
/// must return nil (GRDB will interpret this nil result as a conversion
/// error, and react accordingly).
case custom((DatabaseValue) -> Data?)
}
// MARK: - DatabaseDateDecodingStrategy
/// `DatabaseDateDecodingStrategy` specifies how `FetchableRecord` types that
@@ -91,6 +91,7 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -122,6 +123,7 @@ extension MutablePersistableRecord {
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -264,6 +266,7 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -296,6 +299,7 @@ extension MutablePersistableRecord {
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -87,6 +87,7 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -121,6 +122,7 @@ extension MutablePersistableRecord {
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -209,6 +211,7 @@ extension MutablePersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -244,6 +247,7 @@ extension MutablePersistableRecord {
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -218,6 +218,7 @@ extension MutablePersistableRecord {
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -241,6 +242,7 @@ extension MutablePersistableRecord {
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -267,6 +269,7 @@ extension MutablePersistableRecord {
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -294,6 +297,7 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -478,6 +482,7 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -514,6 +519,7 @@ extension MutablePersistableRecord {
fetch: fetch)
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -565,6 +571,7 @@ extension MutablePersistableRecord {
}
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -593,6 +600,7 @@ extension MutablePersistableRecord {
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -781,6 +789,7 @@ extension MutablePersistableRecord {
fetch: fetch)
}
// TODO: GRDB7 make it unable to return an optional
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
@@ -56,6 +56,7 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -198,6 +199,7 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
+2
View File
@@ -39,6 +39,7 @@ extension PersistableRecord {
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -127,6 +128,7 @@ extension PersistableRecord {
return success.returned
}
#else
// TODO: GRDB7 make it unable to return an optional
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
+46 -2
View File
@@ -13,6 +13,10 @@
56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B80257404A300B4925B /* CommonTableExpression.swift */; };
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */; };
560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233D027243A9100529DF3 /* SharedValueObservation.swift */; };
5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */; };
5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */; };
5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC12AC862F800CF097D /* JSONColumn.swift */; };
5603CED52AC8643800CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */; };
56043296228F00A9009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */; };
560432A6228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
@@ -33,6 +37,9 @@
561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; };
561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; };
561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
561F38DB2AC8914D0051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */; };
561F38F22AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
562205FA1E420E49005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
562205FB1E420E49005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
562205FC1E420E49005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
@@ -434,6 +441,10 @@
56012B80257404A300B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
560233CC2724339A00529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
560233D027243A9100529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
5603CEC12AC862F800CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
56043295228F00A9009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
560432A5228F167A009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
5604484C25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
@@ -470,6 +481,9 @@
561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
@@ -855,6 +869,25 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
5603CEBE2AC862F800CF097D /* JSON */ = {
isa = PBXGroup;
children = (
5603CEC12AC862F800CF097D /* JSONColumn.swift */,
5603CEC02AC862F800CF097D /* SQLJSONExpressible.swift */,
5603CEBF2AC862F800CF097D /* SQLJSONFunctions.swift */,
);
path = JSON;
sourceTree = "<group>";
};
5603CECB2AC8632A00CF097D /* JSON */ = {
isa = PBXGroup;
children = (
561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */,
5603CECC2AC8633B00CF097D /* JSONExpressionsTests.swift */,
);
name = JSON;
sourceTree = "<group>";
};
5605F1471C672E4000235C62 /* Support */ = {
isa = PBXGroup;
children = (
@@ -933,6 +966,7 @@
560B3FA41C19DFF800C58EC7 /* PersistableRecord */ = {
isa = PBXGroup;
children = (
561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */,
@@ -967,12 +1001,13 @@
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
isa = PBXGroup;
children = (
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
562EA81E1F17B26F00FA528C /* Compilation */,
56A238111B9C74A90082EB20 /* Core */,
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */,
5698AC3E1DA2BEBB0056AF8C /* FTS */,
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
5603CECB2AC8632A00CF097D /* JSON */,
56A238231B9C74A90082EB20 /* Migrations */,
569978D31B539038005EBEED /* Private */,
56300B5C1C53C38F005A543B /* QueryInterface */,
@@ -1296,6 +1331,7 @@
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
isa = PBXGroup;
children = (
561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
5665FA1C2129D807004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
@@ -1647,6 +1683,7 @@
566DDE11288D76400000DCFB /* Fixits.swift */,
56A2386F1B9C75030082EB20 /* Core */,
5698AC291D9E5A480056AF8C /* FTS */,
5603CEBE2AC862F800CF097D /* JSON */,
56A238911B9C750B0082EB20 /* Migration */,
5656A8252295BD56001FF3FF /* QueryInterface */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1984,6 +2021,7 @@
F3BA807F1CFB2E61003DC1BA /* NSString.swift in Sources */,
56F89DFA2A57EAB9002FE2AA /* ColumnDefinition.swift in Sources */,
56F89E1C2A585E0D002FE2AA /* SQLTableGenerator.swift in Sources */,
5603CEC52AC862F800CF097D /* SQLJSONExpressible.swift in Sources */,
560233D127243A9200529DF3 /* SharedValueObservation.swift in Sources */,
5656A8592295BD56001FF3FF /* SQLGenerationContext.swift in Sources */,
5690C3421D23E82A00E59934 /* Data.swift in Sources */,
@@ -2012,9 +2050,11 @@
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
5603CEC62AC862F800CF097D /* JSONColumn.swift in Sources */,
5656A88F2295BD56001FF3FF /* Column.swift in Sources */,
564CE5B721B8FBEB00652B19 /* DatabaseRegionObservation.swift in Sources */,
5656A8612295BD56001FF3FF /* TableRecord+Association.swift in Sources */,
5603CEC42AC862F800CF097D /* SQLJSONFunctions.swift in Sources */,
F3BA808C1CFB2E75003DC1BA /* DatabaseMigrator.swift in Sources */,
563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */,
5613ED6121A95E6100DC7A68 /* ValueObservation.swift in Sources */,
@@ -2042,6 +2082,7 @@
F3BA80CC1CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */,
F3BA81101CFB3057003DC1BA /* Row+FoundationTests.swift in Sources */,
F3BA812C1CFB3064003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
561F38DB2AC8914D0051EEE9 /* JSONColumnTests.swift in Sources */,
5698AC991DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
5653EB6C20961FB200F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
@@ -2083,6 +2124,7 @@
F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */,
56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
561F38F22AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */,
F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */,
F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */,
@@ -2210,6 +2252,7 @@
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
563B533B267E2FA4009549B5 /* TableTests.swift in Sources */,
5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
561F38F62AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */,
@@ -2253,6 +2296,7 @@
F3BA812D1CFB3064003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */,
5698AC831DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
F3BA811B1CFB305F003DC1BA /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */,
5603CED52AC8643800CF097D /* JSONExpressionsTests.swift in Sources */,
F3BA811A1CFB305F003DC1BA /* Record+QueryInterfaceRequestTests.swift in Sources */,
F3BA81111CFB3057003DC1BA /* StatementArguments+FoundationTests.swift in Sources */,
F3BA81371CFB3064003DC1BA /* RecordInitializersTests.swift in Sources */,
+39 -13
View File
@@ -15,7 +15,7 @@
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: September 1, 2023 • [version 6.18.0](https://github.com/groue/GRDB.swift/tree/v6.18.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Latest release**: October 4, 2023 • [version 6.19.0](https://github.com/groue/GRDB.swift/tree/v6.19.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
@@ -2502,7 +2502,7 @@ try Player.deleteAll(db, ids: [1, 2, 3])
> **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments:
>
> ```swift
> // Those methods are not type-checked
> // Available on non-Identifiable types
> try Player.fetchOne(db, key: 1)
> try Player.fetchOne(db, key: ["email": "arthur@example.com"])
> try Country.fetchAll(db, keys: ["FR", "US"])
@@ -2515,6 +2515,26 @@ try Player.deleteAll(db, ids: [1, 2, 3])
> try Player.deleteAll(db, keys: [1, 2, 3])
> ```
> **Note**: It is not recommended to use `Identifiable` on record types that use an auto-incremented primary key:
>
> ```swift
> // AVOID declaring Identifiable conformance when key is auto-incremented
> struct Player {
> var id: Int64? // Not an id suitable for Identifiable
> var name: String
> var score: Int
> }
>
> extension Player: FetchableRecord, MutablePersistableRecord {
> // Update auto-incremented id upon successful insertion
> mutating func didInsert(_ inserted: InsertionSuccess) {
> id = inserted.rowID
> }
> }
> ```
>
> For a detailed rationale, please see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
Some database tables have a single-column primary key which is not called "id":
```swift
@@ -2571,7 +2591,7 @@ For more information about Codable records, see:
- [JSON Columns]
- [Column Names Coding Strategies]
- [Date and UUID Coding Strategies]
- [Data, Date, and UUID Coding Strategies]
- [The userInfo Dictionary]
- [Tip: Derive Columns from Coding Keys](#tip-derive-columns-from-coding-keys)
@@ -2646,9 +2666,9 @@ protocol EncodableRecord {
See [DatabaseColumnDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumndecodingstrategy) and [DatabaseColumnEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumnencodingstrategy/) to learn about all available strategies.
### Date and UUID Coding Strategies
### Data, Date, and UUID Coding Strategies
By default, [Codable Records] encode and decode their Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters.
By default, [Codable Records] encode and decode their Data properties as blobs, and Date and UUID properties as described in the general [Date and DateComponents](#date-and-datecomponents) and [UUID](#uuid) chapters.
To sum up: dates encode themselves in the "YYYY-MM-DD HH:MM:SS.SSS" format, in the UTC time zone, and decode a variety of date formats and timestamps. UUIDs encode themselves as 16-bytes data blobs, and decode both 16-bytes data blobs and strings such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
@@ -2656,27 +2676,29 @@ Those behaviors can be overridden:
```swift
protocol FetchableRecord {
static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get }
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
}
protocol EncodableRecord {
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get }
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
}
```
See [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies.
See [DatabaseDataDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatadecodingstrategy/), [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDataEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedataencodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies.
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
Customized date and uuid handling apply:
Customized coding strategies apply:
- When encoding and decoding database rows to and from records (fetching and persistence methods).
- In requests by single-column primary key: `fetchOne(_:id:)`, `filter(id:)`, `deleteAll(_:keys:)`, etc.
*They do not apply* in other requests based on date or uuid values.
*They do not apply* in other requests based on data, date, or uuid values.
So make sure that dates and uuids are properly encoded in your requests. For example:
So make sure that those are properly encoded in your requests. For example:
```swift
struct Player: Codable, FetchableRecord, PersistableRecord, Identifiable {
@@ -3449,11 +3471,11 @@ This is the list of record methods, along with their required protocols. The [Re
| **[Codable Records]** | | |
| `Type.databaseDecodingUserInfo` | [FetchableRecord] | [*](#the-userinfo-dictionary) |
| `Type.databaseJSONDecoder(for:)` | [FetchableRecord] | [*](#json-columns) |
| `Type.databaseDateDecodingStrategy` | [FetchableRecord] | [*](#date-and-uuid-coding-strategies) |
| `Type.databaseDateDecodingStrategy` | [FetchableRecord] | [*](#data-date-and-uuid-coding-strategies) |
| `Type.databaseEncodingUserInfo` | [EncodableRecord] | [*](#the-userinfo-dictionary) |
| `Type.databaseJSONEncoder(for:)` | [EncodableRecord] | [*](#json-columns) |
| `Type.databaseDateEncodingStrategy` | [EncodableRecord] | [*](#date-and-uuid-coding-strategies) |
| `Type.databaseUUIDEncodingStrategy` | [EncodableRecord] | [*](#date-and-uuid-coding-strategies) |
| `Type.databaseDateEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) |
| `Type.databaseUUIDEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) |
| **Define [Associations]** | | |
| `Type.belongsTo(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) |
| `Type.hasMany(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) |
@@ -6213,6 +6235,10 @@ This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/document
This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter).
#### Date and UUID Coding Strategies
This chapter has been renamed [Data, Date, and UUID Coding Strategies].
#### Dealing with External Connections
This chapter has been superseded by the [Sharing a Database] guide.
@@ -6308,7 +6334,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Common Table Expressions]: Documentation/CommonTableExpressions.md
[Conflict Resolution]: #conflict-resolution
[Column Names Coding Strategies]: #column-names-coding-strategies
[Date and UUID Coding Strategies]: #date-and-uuid-coding-strategies
[Data, Date, and UUID Coding Strategies]: #data-date-and-uuid-coding-strategies
[Fetching from Requests]: #fetching-from-requests
[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests
[Full-Text Search]: Documentation/FullTextSearch.md
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.18.0</string>
<string>6.19.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+17
View File
@@ -12,4 +12,21 @@ post_install do |installer|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
end
end
# TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged.
# https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516
installer.aggregate_targets.each do |target|
target.xcconfigs.each do |variant, xcconfig|
xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
xcconfig_path = config.base_configuration_reference.real_path
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
end
end
+17
View File
@@ -11,4 +11,21 @@ post_install do |installer|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] = "$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1"
end
end
# TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged.
# https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516
installer.aggregate_targets.each do |target|
target.xcconfigs.each do |variant, xcconfig|
xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
xcconfig_path = config.base_configuration_reference.real_path
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
end
end
@@ -3,10 +3,18 @@
archiveVersion = 1;
classes = {
};
objectVersion = 51;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */; };
561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */; };
561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
561F38FA2AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
561F38FB2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F38FC2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
56419D6724A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; };
56419D6824A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; };
56419D6924A54062004967E1 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9D24A54053004967E1 /* ResultCodeTests.swift */; };
@@ -459,6 +467,10 @@
/* Begin PBXFileReference section */
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
56419C9C24A54053004967E1 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
56419C9D24A54053004967E1 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
56419C9E24A54053004967E1 /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = "<group>"; };
@@ -827,6 +839,8 @@
56419CE824A54059004967E1 /* DatabaseCollationTests.swift */,
56419D1124A5405C004967E1 /* DatabaseConfigurationTests.swift */,
56419CA424A54054004967E1 /* DatabaseCursorTests.swift */,
561F38F72AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
56419CCE24A54057004967E1 /* DatabaseDateDecodingStrategyTests.swift */,
56419CE424A54058004967E1 /* DatabaseDateEncodingStrategyTests.swift */,
56419CAF24A54054004967E1 /* DatabaseErrorTests.swift */,
@@ -911,6 +925,8 @@
56419CDE24A54058004967E1 /* IndexInfoTests.swift */,
56419CF024A54059004967E1 /* InflectionsTests.swift */,
56419D0024A5405A004967E1 /* JoinSupportTests.swift */,
561F38DC2AC891710051EEE9 /* JSONColumnTests.swift */,
5603CECE2AC8636E00CF097D /* JSONExpressionsTests.swift */,
56419CDC24A54058004967E1 /* MapCursorTests.swift */,
56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */,
56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */,
@@ -1226,6 +1242,7 @@
56419DF324A54062004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
56419E6724A54062004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56419E4D24A54062004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */,
561F38F92AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56419E6B24A54062004967E1 /* ValueObservationFetchTests.swift in Sources */,
56419D8524A54062004967E1 /* FTS4RecordTests.swift in Sources */,
5641A1B224A540D6004967E1 /* Next.swift in Sources */,
@@ -1257,6 +1274,7 @@
56419ED924A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
56419EAB24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
56419D7724A54062004967E1 /* DatabaseCursorTests.swift in Sources */,
5603CECF2AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */,
56419E1524A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */,
56419EC724A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
@@ -1267,6 +1285,7 @@
56419DA524A54062004967E1 /* QueryInterfacePromiseTests.swift in Sources */,
56419EE324A54063004967E1 /* Row+FoundationTests.swift in Sources */,
56419E7124A54062004967E1 /* DatabaseTests.swift in Sources */,
561F38DD2AC891710051EEE9 /* JSONColumnTests.swift in Sources */,
56419E9524A54063004967E1 /* PrefixWhileCursorTests.swift in Sources */,
56419E2F24A54062004967E1 /* JoinSupportTests.swift in Sources */,
56419E0524A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */,
@@ -1383,6 +1402,7 @@
56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
561F38FB2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */,
56419EFB24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */,
56419E3D24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */,
@@ -1452,6 +1472,7 @@
56419DF424A54062004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
56419E6824A54062004967E1 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
56419E4E24A54062004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */,
561F38FA2AC9CE6D0051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56419E6C24A54062004967E1 /* ValueObservationFetchTests.swift in Sources */,
56419D8624A54062004967E1 /* FTS4RecordTests.swift in Sources */,
5641A1B324A540D6004967E1 /* Next.swift in Sources */,
@@ -1483,6 +1504,7 @@
56419EDA24A54063004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
56419EAC24A54063004967E1 /* DatabaseValueTests.swift in Sources */,
56419D7824A54062004967E1 /* DatabaseCursorTests.swift in Sources */,
5603CED02AC8636E00CF097D /* JSONExpressionsTests.swift in Sources */,
56419E1624A54062004967E1 /* AssociationChainRowScopesTests.swift in Sources */,
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */,
56419EC824A54063004967E1 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
@@ -1493,6 +1515,7 @@
56419DA624A54062004967E1 /* QueryInterfacePromiseTests.swift in Sources */,
56419EE424A54063004967E1 /* Row+FoundationTests.swift in Sources */,
56419E7224A54062004967E1 /* DatabaseTests.swift in Sources */,
561F38DE2AC891710051EEE9 /* JSONColumnTests.swift in Sources */,
56419E9624A54063004967E1 /* PrefixWhileCursorTests.swift in Sources */,
56419E3024A54062004967E1 /* JoinSupportTests.swift in Sources */,
56419E0624A54062004967E1 /* AssociationParallelSQLTests.swift in Sources */,
@@ -1609,6 +1632,7 @@
56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
561F38FC2AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */,
56419EFC24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */,
56419E3E24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */,
+17
View File
@@ -23,4 +23,21 @@ post_install do |installer|
config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3'
end
end
# TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged.
# https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516
installer.aggregate_targets.each do |target|
target.xcconfigs.each do |variant, xcconfig|
xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
xcconfig_path = config.base_configuration_reference.real_path
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
end
end
@@ -3,10 +3,18 @@
archiveVersion = 1;
classes = {
};
objectVersion = 51;
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */; };
561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; };
561F38E42AC891890051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38E02AC891890051EEE9 /* JSONColumnTests.swift */; };
561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
561F39012AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
561F39022AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
56419FC824A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; };
56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; };
56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; };
@@ -475,6 +483,10 @@
/* Begin PBXFileReference section */
04298D834C818285823558AB /* Pods-GRDBTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTests.release.xcconfig"; path = "Target Support Files/Pods-GRDBTests/Pods-GRDBTests.release.xcconfig"; sourceTree = "<group>"; };
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
561F38E02AC891890051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = "<group>"; };
56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = "<group>"; };
56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
@@ -856,6 +868,8 @@
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */,
56419F7024A5409A004967E1 /* DatabaseConfigurationTests.swift */,
56419F2324A54095004967E1 /* DatabaseCursorTests.swift */,
561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
561F38FD2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
56419FBE24A540A0004967E1 /* DatabaseDateDecodingStrategyTests.swift */,
56419F2824A54095004967E1 /* DatabaseDateEncodingStrategyTests.swift */,
56419F5824A54098004967E1 /* DatabaseErrorTests.swift */,
@@ -942,6 +956,8 @@
56419FA824A5409E004967E1 /* IndexInfoTests.swift */,
56419F3824A54096004967E1 /* InflectionsTests.swift */,
56419F6D24A5409A004967E1 /* JoinSupportTests.swift */,
561F38E02AC891890051EEE9 /* JSONColumnTests.swift */,
561F38DF2AC891890051EEE9 /* JSONExpressionsTests.swift */,
56419F7B24A5409B004967E1 /* MapCursorTests.swift */,
56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */,
56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */,
@@ -1345,6 +1361,7 @@
5641A08224A540A1004967E1 /* AssociationAggregateTests.swift in Sources */,
5641A12424A540A1004967E1 /* DatabaseTraceTests.swift in Sources */,
56419FE224A540A1004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */,
561F38E12AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */,
5641A07624A540A1004967E1 /* CompilationProtocolTests.swift in Sources */,
5641A14624A540A2004967E1 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5641A03C24A540A1004967E1 /* AssociationBelongsToSQLTests.swift in Sources */,
@@ -1355,6 +1372,7 @@
5641A0F424A540A1004967E1 /* ColumnInfoTests.swift in Sources */,
5641A07A24A540A1004967E1 /* QueryInterfacePromiseTests.swift in Sources */,
5641A0E824A540A1004967E1 /* AssociationParallelSQLTests.swift in Sources */,
561F39012AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56419FE024A540A1004967E1 /* AssociationChainSQLTests.swift in Sources */,
5641A03E24A540A1004967E1 /* InflectionsTests.swift in Sources */,
5641A06224A540A1004967E1 /* DropWhileCursorTests.swift in Sources */,
@@ -1398,6 +1416,7 @@
56419FE624A540A1004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
5641A04424A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
5641A14024A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
561F38FF2AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
5641A08A24A540A1004967E1 /* EncryptionTests.swift in Sources */,
5641A11E24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
56419FEC24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
@@ -1432,6 +1451,7 @@
5641A05624A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */,
5641A12224A540A1004967E1 /* FTS5PatternTests.swift in Sources */,
5641A0F624A540A1004967E1 /* FTS5WrapperTokenizerTests.swift in Sources */,
561F38E32AC891890051EEE9 /* JSONColumnTests.swift in Sources */,
5641A15C24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
5641A03024A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
5641A00224A540A1004967E1 /* PersistableRecordTests.swift in Sources */,
@@ -1578,6 +1598,7 @@
5641A08324A540A1004967E1 /* AssociationAggregateTests.swift in Sources */,
5641A12524A540A1004967E1 /* DatabaseTraceTests.swift in Sources */,
56419FE324A540A1004967E1 /* AssociationBelongsToRowScopeTests.swift in Sources */,
561F38E22AC891890051EEE9 /* JSONExpressionsTests.swift in Sources */,
5641A07724A540A1004967E1 /* CompilationProtocolTests.swift in Sources */,
5641A14724A540A2004967E1 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
5641A03D24A540A1004967E1 /* AssociationBelongsToSQLTests.swift in Sources */,
@@ -1588,6 +1609,7 @@
5641A0F524A540A1004967E1 /* ColumnInfoTests.swift in Sources */,
5641A07B24A540A1004967E1 /* QueryInterfacePromiseTests.swift in Sources */,
5641A0E924A540A1004967E1 /* AssociationParallelSQLTests.swift in Sources */,
561F39022AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
56419FE124A540A1004967E1 /* AssociationChainSQLTests.swift in Sources */,
5641A03F24A540A1004967E1 /* InflectionsTests.swift in Sources */,
5641A06324A540A1004967E1 /* DropWhileCursorTests.swift in Sources */,
@@ -1631,6 +1653,7 @@
56419FE724A540A1004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
5641A04524A540A1004967E1 /* FTS3TokenizerTests.swift in Sources */,
5641A14124A540A2004967E1 /* RecordPrimaryKeyRowIDTests.swift in Sources */,
561F39002AC9CE870051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
5641A08B24A540A1004967E1 /* EncryptionTests.swift in Sources */,
5641A11F24A540A1004967E1 /* IndexInfoTests.swift in Sources */,
56419FED24A540A1004967E1 /* FTS4TableBuilderTests.swift in Sources */,
@@ -1665,6 +1688,7 @@
5641A05724A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */,
5641A12324A540A1004967E1 /* FTS5PatternTests.swift in Sources */,
5641A0F724A540A1004967E1 /* FTS5WrapperTokenizerTests.swift in Sources */,
561F38E42AC891890051EEE9 /* JSONColumnTests.swift in Sources */,
5641A15D24A540A2004967E1 /* AssociationHasOneSQLDerivationTests.swift in Sources */,
5641A03124A540A1004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
5641A00324A540A1004967E1 /* PersistableRecordTests.swift in Sources */,
+17
View File
@@ -23,4 +23,21 @@ post_install do |installer|
config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3'
end
end
# TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged.
# https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516
installer.aggregate_targets.each do |target|
target.xcconfigs.each do |variant, xcconfig|
xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
xcconfig_path = config.base_configuration_reference.real_path
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
end
end
@@ -0,0 +1,139 @@
import Foundation
import XCTest
@testable import GRDB // TODO: remove @testable when RowDecodingError is public
private protocol StrategyProvider {
static var strategy: DatabaseDataDecodingStrategy { get }
}
private enum StrategyDeferredToData: StrategyProvider {
static let strategy: DatabaseDataDecodingStrategy = .deferredToData
}
private enum StrategyCustom: StrategyProvider {
static let strategy: DatabaseDataDecodingStrategy = .custom { dbValue in
if dbValue == "invalid".databaseValue {
return nil
}
return "foo".data(using: .utf8)!
}
}
private struct RecordWithData<Strategy: StrategyProvider>: FetchableRecord, Decodable {
static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy }
var data: Data
}
private struct RecordWithOptionalData<Strategy: StrategyProvider>: FetchableRecord, Decodable {
static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy }
var data: Data?
}
class DatabaseDataDecodingStrategyTests: GRDBTestCase {
/// test the conversion from a database value to a data extracted from a record
private func test<T: FetchableRecord>(
_ db: Database,
record: T.Type,
data: (T) -> Data?,
databaseValue: (any DatabaseValueConvertible)?,
with test: (Data?) -> Void) throws
{
let request = SQLRequest<Void>(sql: "SELECT ? AS data", arguments: [databaseValue])
do {
// test decoding straight from SQLite
let record = try T.fetchOne(db, request)!
test(data(record))
}
do {
// test decoding from copied row
let record = try T(row: Row.fetchOne(db, request)!)
test(data(record))
}
}
/// test the conversion from a database value to a data with a given strategy
private func test<Strategy: StrategyProvider>(
_ db: Database,
strategy: Strategy.Type,
databaseValue: some DatabaseValueConvertible,
_ test: (Data) -> Void)
throws
{
try self.test(db, record: RecordWithData<Strategy>.self, data: { $0.data }, databaseValue: databaseValue, with: { test($0!) })
try self.test(db, record: RecordWithOptionalData<Strategy>.self, data: { $0.data }, databaseValue: databaseValue, with: { test($0!) })
}
private func testNullDecoding<Strategy: StrategyProvider>(_ db: Database, strategy: Strategy.Type) throws {
try self.test(db, record: RecordWithOptionalData<Strategy>.self, data: { $0.data }, databaseValue: nil) { data in
XCTAssertNil(data)
}
}
}
// MARK: - deferredToData
extension DatabaseDataDecodingStrategyTests {
func testDeferredToData() throws {
try makeDatabaseQueue().read { db in
// Null
try testNullDecoding(db, strategy: StrategyDeferredToData.self)
// Empty string
try test(db, strategy: StrategyDeferredToData.self, databaseValue: "") { data in
XCTAssertEqual(data, Data())
}
// String
try test(db, strategy: StrategyDeferredToData.self, databaseValue: "foo") { data in
XCTAssertEqual(data, "foo".data(using: .utf8))
}
// Empty blob
try test(db, strategy: StrategyDeferredToData.self, databaseValue: Data()) { data in
XCTAssertEqual(data, Data())
}
// Blob
try test(db, strategy: StrategyDeferredToData.self, databaseValue: "foo".data(using: .utf8)) { data in
XCTAssertEqual(data, "foo".data(using: .utf8))
}
}
}
}
// MARK: - custom((DatabaseValue) -> Data?
extension DatabaseDataDecodingStrategyTests {
func testCustom() throws {
try makeDatabaseQueue().read { db in
// Null
try testNullDecoding(db, strategy: StrategyCustom.self)
// Data
try test(db, strategy: StrategyCustom.self, databaseValue: "valid") { data in
XCTAssertEqual(data, "foo".data(using: .utf8)!)
}
// error
do {
try test(db, strategy: StrategyCustom.self, databaseValue: "invalid") { data in
XCTFail("Unexpected Data")
}
} catch let error as RowDecodingError {
switch error {
case .valueMismatch:
XCTAssertEqual(error.description, """
could not decode Data from database value "invalid" - \
column: "data", \
column index: 0, \
row: [data:"invalid"], \
sql: `SELECT ? AS data`, \
arguments: ["invalid"]
""")
default:
XCTFail("Unexpected Error")
}
}
}
}
}
@@ -0,0 +1,309 @@
import XCTest
import Foundation
@testable import GRDB
private protocol StrategyProvider {
static var strategy: DatabaseDataEncodingStrategy { get }
}
private enum StrategyDeferredToData: StrategyProvider {
static let strategy: DatabaseDataEncodingStrategy = .deferredToData
}
private enum StrategyTextUTF8: StrategyProvider {
static let strategy: DatabaseDataEncodingStrategy = .text
}
private enum StrategyCustom: StrategyProvider {
static let strategy: DatabaseDataEncodingStrategy = .custom { _ in "custom" }
}
private struct RecordWithData<Strategy: StrategyProvider>: EncodableRecord, Encodable {
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy }
var data: Data
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension RecordWithData: Identifiable {
var id: Data { data }
}
private struct RecordWithOptionalData<Strategy: StrategyProvider>: EncodableRecord, Encodable {
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy }
var data: Data?
}
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
extension RecordWithOptionalData: Identifiable {
var id: Data? { data }
}
class DatabaseDataEncodingStrategyTests: GRDBTestCase {
let testedDatas = [
"foo".data(using: .utf8)!,
Data(),
]
private func test<T: EncodableRecord>(
record: T,
expectedStorage: DatabaseValue.Storage)
throws
{
var container = PersistenceContainer()
try record.encode(to: &container)
if let dbValue = container["data"]?.databaseValue {
XCTAssertEqual(dbValue.storage, expectedStorage)
} else {
XCTAssertEqual(.null, expectedStorage)
}
}
private func test<Strategy: StrategyProvider>(
strategy: Strategy.Type,
encodesData data: Data,
as value: some DatabaseValueConvertible)
throws
{
try test(record: RecordWithData<Strategy>(data: data), expectedStorage: value.databaseValue.storage)
try test(record: RecordWithOptionalData<Strategy>(data: data), expectedStorage: value.databaseValue.storage)
}
private func testNullEncoding<Strategy: StrategyProvider>(strategy: Strategy.Type) throws {
try test(record: RecordWithOptionalData<Strategy>(data: nil), expectedStorage: .null)
}
}
// MARK: - deferredToData
extension DatabaseDataEncodingStrategyTests {
func testDeferredToData() throws {
try testNullEncoding(strategy: StrategyDeferredToData.self)
for (data, value) in zip(testedDatas, [
"foo".data(using: .utf8)!,
Data(),
]) { try test(strategy: StrategyDeferredToData.self, encodesData: data, as: value) }
}
}
// MARK: - text(UTF8)
extension DatabaseDataEncodingStrategyTests {
func testTextUTF8() throws {
try testNullEncoding(strategy: StrategyTextUTF8.self)
for (data, value) in zip(testedDatas, [
"foo",
"",
]) { try test(strategy: StrategyTextUTF8.self, encodesData: data, as: value) }
}
}
// MARK: - custom((Data) -> DatabaseValueConvertible?)
extension DatabaseDataEncodingStrategyTests {
func testCustom() throws {
try testNullEncoding(strategy: StrategyCustom.self)
for (data, value) in zip(testedDatas, [
"custom",
"custom",
]) { try test(strategy: StrategyCustom.self, encodesData: data, as: value) }
}
}
// MARK: - Filter
extension DatabaseDataEncodingStrategyTests {
func testFilterKey() throws {
try makeDatabaseQueue().write { db in
try db.create(table: "t") { $0.primaryKey("id", .blob) }
do {
let request = Table<RecordWithData<StrategyDeferredToData>>("t").filter(key: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = x'666f6f'
""")
}
do {
let request = Table<RecordWithData<StrategyDeferredToData>>("t").filter(keys: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'')
""")
}
do {
let request = Table<RecordWithData<StrategyTextUTF8>>("t").filter(key: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = 'foo'
""")
}
do {
let request = Table<RecordWithData<StrategyTextUTF8>>("t").filter(keys: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN ('foo', '')
""")
}
}
}
func testFilterID() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Identifiable not available")
}
try makeDatabaseQueue().write { db in
try db.create(table: "t") { $0.primaryKey("id", .blob) }
do {
let request = Table<RecordWithData<StrategyDeferredToData>>("t").filter(id: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = x'666f6f'
""")
}
do {
let request = Table<RecordWithData<StrategyDeferredToData>>("t").filter(ids: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'')
""")
}
do {
let request = Table<RecordWithData<StrategyTextUTF8>>("t").filter(id: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = 'foo'
""")
}
do {
let request = Table<RecordWithData<StrategyTextUTF8>>("t").filter(ids: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN ('foo', '')
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyDeferredToData>>("t").filter(id: nil)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE 0
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyDeferredToData>>("t").filter(id: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = x'666f6f'
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyDeferredToData>>("t").filter(ids: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN (x'666f6f', x'')
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyTextUTF8>>("t").filter(id: nil)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE 0
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyTextUTF8>>("t").filter(id: testedDatas[0])
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" = 'foo'
""")
}
do {
let request = Table<RecordWithOptionalData<StrategyTextUTF8>>("t").filter(ids: testedDatas)
try assertEqualSQL(db, request, """
SELECT * FROM "t" WHERE "id" IN ('foo', '')
""")
}
}
}
func testDeleteID() throws {
guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else {
throw XCTSkip("Identifiable not available")
}
try makeDatabaseQueue().write { db in
try db.create(table: "t") { $0.primaryKey("id", .blob) }
do {
try Table<RecordWithData<StrategyDeferredToData>>("t").deleteOne(db, id: testedDatas[0])
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" = x'666f6f'
""")
}
do {
try Table<RecordWithData<StrategyDeferredToData>>("t").deleteAll(db, ids: testedDatas)
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" IN (x'666f6f', x'')
""")
}
do {
try Table<RecordWithData<StrategyTextUTF8>>("t").deleteOne(db, id: testedDatas[0])
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" = 'foo'
""")
}
do {
try Table<RecordWithData<StrategyTextUTF8>>("t").deleteAll(db, ids: testedDatas)
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" IN ('foo', '')
""")
}
do {
sqlQueries.removeAll()
try Table<RecordWithOptionalData<StrategyDeferredToData>>("t").deleteOne(db, id: nil)
XCTAssertNil(lastSQLQuery) // Database not hit
}
do {
try Table<RecordWithOptionalData<StrategyDeferredToData>>("t").deleteOne(db, id: testedDatas[0])
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" = x'666f6f'
""")
}
do {
try Table<RecordWithOptionalData<StrategyDeferredToData>>("t").deleteAll(db, ids: testedDatas)
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" IN (x'666f6f', x'')
""")
}
do {
sqlQueries.removeAll()
try Table<RecordWithOptionalData<StrategyTextUTF8>>("t").deleteOne(db, id: nil)
XCTAssertNil(lastSQLQuery) // Database not hit
}
do {
try Table<RecordWithOptionalData<StrategyTextUTF8>>("t").deleteOne(db, id: testedDatas[0])
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" = 'foo'
""")
}
do {
try Table<RecordWithOptionalData<StrategyTextUTF8>>("t").deleteAll(db, ids: testedDatas)
XCTAssertEqual(lastSQLQuery, """
DELETE FROM "t" WHERE "id" IN ('foo', '')
""")
}
}
}
}
@@ -326,4 +326,57 @@ class DatabaseValueConvertibleDecodableTests: GRDBTestCase {
XCTAssertEqual(value, .foo)
}
}
func testDatabaseValueConvertibleImplementationDerivedFromDecodableWithCustomJsonDecoder() throws {
struct Value: Decodable, DatabaseValueConvertible {
let duration: Double
var databaseValue: DatabaseValue {
preconditionFailure("not tested")
}
public static func databaseJSONDecoder() -> JSONDecoder {
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .convertFromString(
positiveInfinity: "+InF",
negativeInfinity: "-InF",
nan: "NaN"
)
return decoder
}
}
do {
// Success from DatabaseValue
let value = Value.fromDatabaseValue(#"{ "duration": "+InF" }"#.databaseValue)!
XCTAssertEqual(value.duration, Double.infinity)
let value2 = Value.fromDatabaseValue(#"{ "duration": "-InF" }"#.databaseValue)!
XCTAssertEqual(value2.duration, -Double.infinity)
let value3 = Value.fromDatabaseValue(#"{ "duration": "NaN" }"#.databaseValue)!
XCTAssertTrue(value3.duration.isNaN)
}
do {
// Success from database
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let value = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "+InF" }'"#)!
XCTAssertEqual(value.duration, Double.infinity)
let value2 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "-InF" }'"#)!
XCTAssertEqual(value2.duration, -Double.infinity)
let value3 = try Value.fetchOne(db, sql: #"SELECT '{ "duration": "NaN" }'"#)!
XCTAssertTrue(value3.duration.isNaN)
}
}
do {
// Failure from DatabaseValue
let value = Value.fromDatabaseValue("infinity".databaseValue)
XCTAssertNil(value)
}
}
}
@@ -304,4 +304,39 @@ extension DatabaseValueConvertibleEncodableTests {
let encodedUUID = UUID.fromDatabaseValue(dbValue)!
XCTAssertEqual(encodedUUID, value.uuid)
}
func testDatabaseValueConvertibleImplementationDerivedFromEncodableWithCustomJsonEncoder() throws {
struct Value: Encodable, DatabaseValueConvertible {
let duration: Double
static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Value? {
preconditionFailure("not tested")
}
public static func databaseJSONEncoder() -> JSONEncoder {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .convertToString(
positiveInfinity: "+InF",
negativeInfinity: "-InF",
nan: "NaN"
)
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
return encoder
}
}
do {
let dbValue = Value(duration: .infinity).databaseValue
XCTAssertEqual(dbValue.storage.value as! String, #"{"duration":"+InF"}"#)
let dbValue2 = Value(duration: -Double.infinity).databaseValue
XCTAssertEqual(dbValue2.storage.value as! String, #"{"duration":"-InF"}"#)
let dbValue3 = Value(duration: .nan).databaseValue
XCTAssertEqual(dbValue3.storage.value as! String, #"{"duration":"NaN"}"#)
}
}
}
+14 -1
View File
@@ -159,6 +159,19 @@ class GRDBTestCase: XCTestCase {
assertEqualSQL(lastSQLQuery!, sql, file: file, line: line)
}
// Compare SQL strings.
func assertEqualSQL(
_ db: Database,
_ expression: some SQLExpressible,
_ sql: String,
file: StaticString = #file,
line: UInt = #line)
throws
{
let request: SQLRequest<Row> = "SELECT \(expression)"
try assertEqualSQL(db, request, "SELECT \(sql)", file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
func assertEqualSQL(
_ databaseReader: some DatabaseReader,
@@ -172,7 +185,7 @@ class GRDBTestCase: XCTestCase {
try assertEqualSQL(db, request, sql, file: file, line: line)
}
}
func sql(
_ databaseReader: some DatabaseReader,
_ request: some FetchRequest)
+94
View File
@@ -0,0 +1,94 @@
import XCTest
import GRDB
final class JSONColumnTests: GRDBTestCase {
func test_JSONColumn_derived_from_CodingKey() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3038000 else {
throw XCTSkip("JSON support is not available")
}
#else
guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else {
throw XCTSkip("JSON support is not available")
}
#endif
struct Player: Codable, TableRecord, FetchableRecord, PersistableRecord {
var id: Int64
var info: Data
enum CodingKeys: String, CodingKey {
case id
case info = "info_json"
}
enum Columns {
static let id = Column(CodingKeys.id)
static let info = JSONColumn(CodingKeys.info)
}
static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.info]
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("info_json", .jsonText)
}
try assertEqualSQL(db, Player.all(), """
SELECT "id", "info_json" FROM "player"
""")
}
}
func test_extraction() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3038000 else {
throw XCTSkip("JSON support is not available")
}
#else
guard #available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) else {
throw XCTSkip("JSON support is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("info", .jsonText)
}
let player = Table("player")
let info = JSONColumn("info")
try assertEqualSQL(db, player.select(info["score"]), """
SELECT "info" ->> 'score' FROM "player"
""")
try assertEqualSQL(db, player.select(info["$.score"]), """
SELECT "info" ->> '$.score' FROM "player"
""")
try assertEqualSQL(db, player.select(info.jsonExtract(atPath: "$.score")), """
SELECT JSON_EXTRACT("info", '$.score') FROM "player"
""")
try assertEqualSQL(db, player.select(info.jsonExtract(atPaths: ["$.score", "$.bonus"])), """
SELECT JSON_EXTRACT("info", '$.score', '$.bonus') FROM "player"
""")
try assertEqualSQL(db, player.select(info.jsonRepresentation(atPath: "score")), """
SELECT "info" -> 'score' FROM "player"
""")
try assertEqualSQL(db, player.select(info.jsonRepresentation(atPath: "$.score")), """
SELECT "info" -> '$.score' FROM "player"
""")
}
}
}
File diff suppressed because it is too large. Load diff
+10 -1
View File
@@ -961,8 +961,14 @@ class TableDefinitionTests: GRDBTestCase {
try db.create(index: "test_on_a_b_2", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists])
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b_2\" ON \"test\"(\"a\", \"b\")")
try db.create(index: "test_on_a_plus_b", on: "test", expressions: [Column("a") + Column("b")], options: [.unique, .ifNotExists])
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_plus_b\" ON \"test\"(\"a\" + \"b\")")
try db.create(index: "test_on_a_nocase", on: "test", expressions: [Column("a").collating(.nocase)], options: [.unique, .ifNotExists])
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_nocase\" ON \"test\"(\"a\" COLLATE NOCASE)")
// Sanity check
XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2"])
XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a", "test_on_a_b", "test_on_a_b_2", "test_on_a_nocase"])
}
}
@@ -1001,6 +1007,9 @@ class TableDefinitionTests: GRDBTestCase {
try db.create(index: "test_on_a_b", on: "test", columns: ["a", "b"], options: [.unique, .ifNotExists], condition: Column("a") == 1)
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_b\" ON \"test\"(\"a\", \"b\") WHERE \"a\" = 1")
try db.create(index: "test_on_a_plus_b", on: "test", expressions: [Column("a") + Column("b")], options: [.unique, .ifNotExists], condition: Column("a") == 1)
assertEqualSQL(lastSQLQuery!, "CREATE UNIQUE INDEX IF NOT EXISTS \"test_on_a_plus_b\" ON \"test\"(\"a\" + \"b\") WHERE \"a\" = 1")
// Sanity check
XCTAssertEqual(try Set(db.indexes(on: "test").map(\.name)), ["test_on_a_b"])
}