mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-29 04:24:21 +00:00
[BREAKING] databaseDataEncodingStrategy depends on the column
This commit is contained in:
1 parent
662daabc32
commit
2767dd5456
8 files changed
+71
-34
No files matched your search
@@ -23,3 +23,9 @@ CSQLite was renamed GRDBSQLite.
|
||||
---
|
||||
|
||||
ValueObservation requires Sendable values
|
||||
|
||||
---
|
||||
|
||||
Strategies
|
||||
|
||||
- databaseDataEncodingStrategy(for:)
|
||||
@@ -92,7 +92,9 @@ struct Team: Codable {
|
||||
extension Team: FetchableRecord, PersistableRecord {
|
||||
// Support SQLite JSON functions and operators
|
||||
// by storing JSON data as database text:
|
||||
static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
|
||||
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
|
||||
.text
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -452,45 +452,64 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
// `deleteAll(_:ids:)` etc.
|
||||
if let recordType = RowDecoder.self as? any EncodableRecord.Type {
|
||||
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)
|
||||
let datas = keys.compactMap { ($0 as! Data?) }
|
||||
if datas.isEmpty {
|
||||
// Don't hit the database
|
||||
return none()
|
||||
}
|
||||
|
||||
return filterWhenConnected(keys: { [databaseTableName] db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
let column = primaryKey.columns[0]
|
||||
let strategy = recordType.databaseDataEncodingStrategy(for: column)
|
||||
let expressions = datas.map { strategy.encode($0).sqlExpression }
|
||||
return expressions
|
||||
})
|
||||
} else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
|
||||
let dates = keys.compactMap { ($0 as! Date?) }
|
||||
if dates.isEmpty {
|
||||
// Don't hit the database
|
||||
return none()
|
||||
}
|
||||
let strategy = recordType.databaseDateEncodingStrategy
|
||||
let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue }
|
||||
return filter(rawKeys: keys)
|
||||
let expressions = dates.map { strategy.encode($0).sqlExpression }
|
||||
return filterWhenConnected(keys: { _ in expressions })
|
||||
} else if Sequence.Element.self == UUID.self || Sequence.Element.self == Optional<UUID>.self {
|
||||
let uuids = keys.compactMap { ($0 as! UUID?) }
|
||||
if uuids.isEmpty {
|
||||
// Don't hit the database
|
||||
return none()
|
||||
}
|
||||
let strategy = recordType.databaseUUIDEncodingStrategy
|
||||
let keys = keys.map { ($0 as! UUID?).map(strategy.encode)?.databaseValue }
|
||||
return filter(rawKeys: keys)
|
||||
let expressions = uuids.map { strategy.encode($0).sqlExpression }
|
||||
return filterWhenConnected(keys: { _ in expressions })
|
||||
}
|
||||
}
|
||||
|
||||
return filter(rawKeys: keys)
|
||||
let expressions = keys.map { $0.sqlExpression }
|
||||
if expressions.isEmpty {
|
||||
// Don't hit the database
|
||||
return none()
|
||||
}
|
||||
return filterWhenConnected(keys: { _ in expressions })
|
||||
}
|
||||
|
||||
/// Creates a request filtered by primary key.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE ... id IN (1, 2, 3)
|
||||
/// let request = try Player...filter(rawKeys: [1, 2, 3])
|
||||
/// let request = try Player...filterWhenConnected(keys: { db in [1, 2, 3] })
|
||||
///
|
||||
/// - parameter keys: A collection of primary keys
|
||||
func filter<Keys>(rawKeys: Keys) -> Self
|
||||
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
|
||||
{
|
||||
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
|
||||
// change the SQLite results anyway.
|
||||
let expressions = rawKeys.map {
|
||||
$0.databaseValue.sqlExpression
|
||||
}
|
||||
|
||||
if expressions.isEmpty {
|
||||
// Don't hit the database
|
||||
return none()
|
||||
}
|
||||
|
||||
fileprivate func filterWhenConnected(keys: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
|
||||
let databaseTableName = self.databaseTableName
|
||||
return filterWhenConnected { db in
|
||||
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
|
||||
// change the SQLite results anyway.
|
||||
let expressions = try keys(db)
|
||||
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
|
||||
@@ -118,7 +118,9 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
|
||||
fileprivate func encode<T>(_ value: T, forKey key: any CodingKey) throws where T: Encodable {
|
||||
if let data = value as? Data {
|
||||
persist(Record.databaseDataEncodingStrategy.encode(data), forKey: key)
|
||||
let column = keyEncodingStrategy.column(forKey: key)
|
||||
let dbValue = Record.databaseDataEncodingStrategy(for: column).encode(data)
|
||||
_persistenceContainer[column] = dbValue
|
||||
} else if let date = value as? Date {
|
||||
persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key)
|
||||
} else if let uuid = value as? UUID {
|
||||
|
||||
@@ -20,8 +20,7 @@ import Foundation // For JSONEncoder
|
||||
/// ### Configuring Persistence for the Standard Encodable Protocol
|
||||
///
|
||||
/// - ``databaseColumnEncodingStrategy-5sx4v``
|
||||
/// - ``databaseDataEncodingStrategy-9y0c7``
|
||||
/// - ``databaseDateEncodingStrategy-2gtc1``
|
||||
/// - ``databaseDataEncodingStrategy(for:)``
|
||||
/// - ``databaseEncodingUserInfo-8upii``
|
||||
/// - ``databaseJSONEncoder(for:)-6x62c``
|
||||
/// - ``databaseUUIDEncodingStrategy-2t96q``
|
||||
@@ -146,13 +145,15 @@ public protocol EncodableRecord {
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: EncodableRecord, Encodable {
|
||||
/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
|
||||
/// static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
|
||||
/// .text
|
||||
/// }
|
||||
///
|
||||
/// // Encoded as SQL text. Data must contain valid UTF8 bytes.
|
||||
/// var jsonData: Data
|
||||
/// }
|
||||
/// ```
|
||||
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get }
|
||||
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy
|
||||
|
||||
/// The strategy for encoding `Date` columns.
|
||||
///
|
||||
@@ -240,7 +241,7 @@ extension EncodableRecord {
|
||||
|
||||
/// Returns the default strategy for encoding `Data` columns:
|
||||
/// ``DatabaseDataEncodingStrategy/deferredToData``.
|
||||
public static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy {
|
||||
public static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
|
||||
.deferredToData
|
||||
}
|
||||
|
||||
@@ -354,7 +355,9 @@ extension EncodableRecord {
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: EncodableRecord, Encodable {
|
||||
/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
|
||||
/// static func databaseDataEncodingStrategy(for column: Column) -> DatabaseDataEncodingStrategy {
|
||||
/// .text
|
||||
/// }
|
||||
///
|
||||
/// // Encoded as SQL text. Data must contain valid UTF8 bytes.
|
||||
/// var jsonData: Data
|
||||
|
||||
@@ -2685,7 +2685,7 @@ protocol FetchableRecord {
|
||||
}
|
||||
|
||||
protocol EncodableRecord {
|
||||
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get }
|
||||
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy
|
||||
static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
|
||||
static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
|
||||
}
|
||||
|
||||
@@ -91,6 +91,7 @@
|
||||
- [ ] GRDB7: warn when user calls a sync database access from a task, with `withUnsafeCurrentTask`.
|
||||
- [ ] GRDB7: Remove Database.commit(), and other manual transaction methods, and replace with documentation about the way to deal with custom transactions and Task-cancelled functions.
|
||||
- [ ] GRDB7 consider replacing global record strategies with functions that accept a column: think JSON/JSONB, etc.
|
||||
- [X] databaseDataEncodingStrategy
|
||||
- [ ] GRDB7 JSONB https://hachyderm.io/@jason_abbott/111908186742242971#.
|
||||
- [X] GRDB7: stop exporting CSQLite https://github.com/groue/GRDB.swift/issues/642#issuecomment-1937347696
|
||||
- [ ] GRDB7: AsyncValueObservation: experiment with an immediate scheduler that does not hop to the main queue.
|
||||
|
||||
@@ -19,7 +19,9 @@ private enum StrategyCustom: StrategyProvider {
|
||||
}
|
||||
|
||||
private struct RecordWithData<Strategy: StrategyProvider>: EncodableRecord, Encodable {
|
||||
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy }
|
||||
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
|
||||
Strategy.strategy
|
||||
}
|
||||
var data: Data
|
||||
}
|
||||
|
||||
@@ -29,7 +31,9 @@ extension RecordWithData: Identifiable {
|
||||
}
|
||||
|
||||
private struct RecordWithOptionalData<Strategy: StrategyProvider>: EncodableRecord, Encodable {
|
||||
static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy }
|
||||
static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy {
|
||||
Strategy.strategy
|
||||
}
|
||||
var data: Data?
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user