mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-22 04:00:39 +00:00
Merge pull request #1852 from groue/dev/upsert-strategy
Configure whether UPSERT should update all columns, or no column.
This commit is contained in:
9 files changed
+717
-187
No files matched your search
@@ -1872,6 +1872,18 @@ public struct ColumnAssignment {
|
||||
}
|
||||
}
|
||||
|
||||
/// A strategy for updating database rows in case of upsert conflict.
|
||||
public struct UpsertUpdateStrategy: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
/// Only the specified columns are updated in the existing row.
|
||||
public static let noColumnUnlessSpecified = Self([])
|
||||
|
||||
/// All columns are updated in the existing row, unless specified otherwise.
|
||||
public static let allColumns = Self(rawValue: 1 << 0)
|
||||
}
|
||||
|
||||
extension ColumnExpression {
|
||||
/// Returns an assignment of this column to an SQL expression.
|
||||
///
|
||||
|
||||
@@ -42,6 +42,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
func upsertStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictTargetColumns: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Record>) -> [ColumnAssignment])?,
|
||||
updateCondition: ((
|
||||
_ existing: TableAlias<Record>,
|
||||
@@ -78,20 +79,22 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
sql += " DO UPDATE SET "
|
||||
let excluded = TableAlias<Record>(name: "excluded")
|
||||
var assignments = assignments?(excluded) ?? []
|
||||
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
|
||||
.union(conflictTargetColumns.map { $0.lowercased() })
|
||||
for column in persistenceContainer.columns {
|
||||
let lowercasedColumn = column.lowercased()
|
||||
if lowercaseExcludedColumns.contains(lowercasedColumn) {
|
||||
// excluded (primary key or conflict target)
|
||||
continue
|
||||
if strategy.contains(.allColumns) {
|
||||
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
|
||||
.union(conflictTargetColumns.map { $0.lowercased() })
|
||||
for column in persistenceContainer.columns {
|
||||
let lowercasedColumn = column.lowercased()
|
||||
if lowercaseExcludedColumns.contains(lowercasedColumn) {
|
||||
// excluded (primary key or conflict target)
|
||||
continue
|
||||
}
|
||||
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
|
||||
// already updated from the `assignments` argument
|
||||
continue
|
||||
}
|
||||
// overwrite
|
||||
assignments.append(Column(column).set(to: excluded[column]))
|
||||
}
|
||||
if assignments.contains(where: { $0.columnName.lowercased() == lowercasedColumn }) {
|
||||
// already updated from the `assignments` argument
|
||||
continue
|
||||
}
|
||||
// overwrite
|
||||
assignments.append(Column(column).set(to: excluded[column]))
|
||||
}
|
||||
let context = SQLGenerationContext(db)
|
||||
let updateSQL = try assignments
|
||||
|
||||
@@ -73,55 +73,52 @@ extension MutablePersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, MutablePersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -129,26 +126,36 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
|
||||
/// the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -157,6 +164,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -166,7 +174,7 @@ extension MutablePersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -250,55 +258,52 @@ extension MutablePersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, MutablePersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -307,26 +312,36 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
|
||||
/// about the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -336,6 +351,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -345,7 +361,7 @@ extension MutablePersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -369,6 +385,7 @@ extension MutablePersistableRecord {
|
||||
{
|
||||
let (inserted, _) = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: [],
|
||||
updating: .allColumns,
|
||||
doUpdate: nil,
|
||||
selection: [],
|
||||
decode: { _ in /* Nothing to decode */ })
|
||||
@@ -379,6 +396,7 @@ extension MutablePersistableRecord {
|
||||
mutating func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -390,7 +408,7 @@ extension MutablePersistableRecord {
|
||||
try aroundInsert(db) {
|
||||
success = try upsertAndFetchWithoutCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: selection,
|
||||
decode: decode)
|
||||
return success!.inserted
|
||||
@@ -409,6 +427,7 @@ extension MutablePersistableRecord {
|
||||
func upsertAndFetchWithoutCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -419,8 +438,8 @@ extension MutablePersistableRecord {
|
||||
|
||||
let dao = try DAO(db, self)
|
||||
let statement = try dao.upsertStatement(
|
||||
db,
|
||||
onConflict: conflictTarget,
|
||||
db, onConflict: conflictTarget,
|
||||
updating: strategy,
|
||||
doUpdate: assignments,
|
||||
updateCondition: nil,
|
||||
returning: selection)
|
||||
|
||||
@@ -62,8 +62,9 @@
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
|
||||
/// - ``UpsertUpdateStrategy``
|
||||
///
|
||||
/// ### Updating a Record
|
||||
///
|
||||
|
||||
@@ -73,55 +73,52 @@ extension PersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, PersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -129,26 +126,36 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See `upsertAndFetch(_:onConflict:doUpdate:)` for more information about
|
||||
/// the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -157,6 +164,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -166,7 +174,7 @@ extension PersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -250,55 +258,52 @@ extension PersistableRecord {
|
||||
/// let upsertedPlayer = try player.upsertAndFetch(db)
|
||||
/// ```
|
||||
///
|
||||
/// With `conflictTarget` and `assignments` arguments, you can further
|
||||
/// control the upsert behavior. Make sure you check
|
||||
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
|
||||
/// you can further control the upsert behavior. Make sure you check
|
||||
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
|
||||
///
|
||||
/// The conflict target are the columns of the uniqueness constraint
|
||||
/// (primary key or unique index) that triggers the upsert. If empty, all
|
||||
/// uniqueness constraint are considered.
|
||||
///
|
||||
/// The assignments describe how to update columns in case of violation of
|
||||
/// a uniqueness constraint. In the next example, we insert the new
|
||||
/// vocabulary word "jovial" if that word is not already in the dictionary.
|
||||
/// If the word is already in the dictionary, it increments the counter,
|
||||
/// does not overwrite the tainted flag, and overwrites the
|
||||
/// remaining columns:
|
||||
/// The strategy controls which columns are updated in case of
|
||||
/// uniqueness constraint violation: all columns unless specified (the
|
||||
/// default), or only the specified columns.
|
||||
///
|
||||
/// For example, compare:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE TABLE vocabulary(
|
||||
/// // word TEXT PRIMARY KEY,
|
||||
/// // kind TEXT NOT NULL,
|
||||
/// // isTainted BOOLEAN DEFAULT 0,
|
||||
/// // count INT DEFAULT 1))
|
||||
/// struct Vocabulary: Encodable, PersistableRecord {
|
||||
/// var word: String
|
||||
/// var kind: String
|
||||
/// var isTainted: Bool
|
||||
/// // In case of conflict, updates all columns, including columns added
|
||||
/// // in a future migration.
|
||||
/// let upserted = try player.upsertAndFetch(db)
|
||||
///
|
||||
/// // In case of conflict, updates all columns, including future ones,
|
||||
/// // but 'score'.
|
||||
/// let upserted = try player.upsertAndFetch(db) { _ in
|
||||
/// [Column("score").noOverwrite]
|
||||
/// }
|
||||
///
|
||||
/// // INSERT INTO vocabulary(word, kind, isTainted)
|
||||
/// // VALUES('jovial', 'adjective', 0)
|
||||
/// // ON CONFLICT(word) DO UPDATE SET \
|
||||
/// // count = count + 1,
|
||||
/// // kind = excluded.kind
|
||||
/// // RETURNING *
|
||||
/// let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
/// let upserted = try vocabulary.upsertAndFetch(
|
||||
/// db,
|
||||
/// onConflict: ["word"],
|
||||
/// doUpdate: { _ in
|
||||
/// [Column("count") += 1,
|
||||
/// Column("isTainted").noOverwrite]
|
||||
/// })
|
||||
/// // In case of conflict, do not update any column.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
///
|
||||
/// // In case of conflict, only update 'name'.
|
||||
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
/// [Column("name").set(to: excluded[Column("name")])]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: The upserted record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -307,26 +312,36 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
try upsertAndFetch(db, as: Self.self, onConflict: conflictTarget, doUpdate: assignments)
|
||||
try upsertAndFetch(
|
||||
db, as: Self.self, onConflict: conflictTarget,
|
||||
updating: strategy, doUpdate: assignments)
|
||||
}
|
||||
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
/// See ``upsertAndFetch(_:onConflict:doUpdate:)`` for more information
|
||||
/// about the `conflictTarget` and `assignments` parameters.
|
||||
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
|
||||
/// information about the `conflictTarget`, `strategy`, and
|
||||
/// `assignments` parameters.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter returnedType: The type of the returned record.
|
||||
/// - parameter conflictTarget: The conflict target.
|
||||
/// - parameter strategy: The default strategy, `.allColumns`, updates
|
||||
/// all columns in case of conflict, unless specified otherwise in the
|
||||
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
|
||||
/// update the columns assigned in the `assignments` parameter.
|
||||
/// - parameter assignments: An optional function that returns an array of
|
||||
/// ``ColumnAssignment``. In case of violation of a uniqueness
|
||||
/// constraints, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values.
|
||||
/// constraint, these assignments are performed, and remaining columns
|
||||
/// are overwritten by inserted values, or not, depending on the
|
||||
/// chosen `strategy`. To use the value that would have been inserted
|
||||
/// had the constraint not failed, use the `excluded` parameter.
|
||||
/// - returns: A record of type `returnedType`.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
@@ -336,6 +351,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
updating strategy: UpsertUpdateStrategy = .allColumns,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
@@ -345,7 +361,7 @@ extension PersistableRecord {
|
||||
try aroundSave(db) {
|
||||
success = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: T.databaseSelection,
|
||||
decode: { try T(row: $0) })
|
||||
return PersistenceSuccess(success!.inserted)
|
||||
@@ -369,6 +385,7 @@ extension PersistableRecord {
|
||||
{
|
||||
let (inserted, _) = try upsertAndFetchWithCallbacks(
|
||||
db, onConflict: [],
|
||||
updating: .allColumns,
|
||||
doUpdate: nil,
|
||||
selection: [],
|
||||
decode: { _ in /* Nothing to decode */ })
|
||||
@@ -379,6 +396,7 @@ extension PersistableRecord {
|
||||
func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
updating strategy: UpsertUpdateStrategy,
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
@@ -390,7 +408,7 @@ extension PersistableRecord {
|
||||
try aroundInsert(db) {
|
||||
success = try upsertAndFetchWithoutCallbacks(
|
||||
db, onConflict: conflictTarget,
|
||||
doUpdate: assignments,
|
||||
updating: strategy, doUpdate: assignments,
|
||||
selection: selection,
|
||||
decode: decode)
|
||||
return success!.inserted
|
||||
|
||||
@@ -24,8 +24,9 @@
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:updating:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:updating:doUpdate:)``
|
||||
/// - ``UpsertUpdateStrategy``
|
||||
///
|
||||
/// ### Saving a Record
|
||||
///
|
||||
|
||||
@@ -2210,7 +2210,7 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
try player.upsert(db)
|
||||
```
|
||||
|
||||
- `upsertAndFetch(_:onConflict:doUpdate:)` (requires [FetchableRecord] conformance)
|
||||
- `upsertAndFetch(_:onConflict:updating:doUpdate:)` (requires [FetchableRecord] conformance)
|
||||
|
||||
Inserts or updates a record, and returns the upserted record.
|
||||
|
||||
@@ -2220,7 +2220,7 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
|
||||
If empty (the default), all uniqueness constraint are considered.
|
||||
|
||||
- `doUpdate`: a closure that returns columns assignments to perform in case of conflict. Other columns are overwritten with the inserted values.
|
||||
- `doUpdate`: a closure that returns columns assignments to perform in case of conflict. Depending on the `options` parameter, other columns are overwritten with the inserted values, or not.
|
||||
|
||||
By default, all inserted columns but the primary key and the conflict target are overwritten.
|
||||
|
||||
@@ -2268,9 +2268,9 @@ For more information about batch updates, see [Update Requests](#update-requests
|
||||
})
|
||||
```
|
||||
|
||||
- `upsertAndFetch(_:as:onConflict:doUpdate:)` (does not require [FetchableRecord] conformance)
|
||||
- `upsertAndFetch(_:as:onConflict:updating:doUpdate:)` (does not require [FetchableRecord] conformance)
|
||||
|
||||
This method is identical to `upsertAndFetch(_:onConflict:doUpdate:)` described above, but you can provide a distinct [FetchableRecord] record type as a result, in order to specify the returned columns.
|
||||
This method is identical to `upsertAndFetch(_:onConflict:updating:doUpdate:)` described above, but you can provide a distinct [FetchableRecord] record type as a result, in order to specify the returned columns.
|
||||
|
||||
### Persistence Methods and the `RETURNING` clause
|
||||
|
||||
|
||||
@@ -2334,7 +2334,7 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where() throws {
|
||||
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
@@ -2351,10 +2351,10 @@ extension MutablePersistableRecordTests {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, isTainted) VALUES('jovial', 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, MutablePersistableRecord, FetchableRecord {
|
||||
@@ -2376,6 +2376,36 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db)
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT \
|
||||
DO UPDATE SET "kind" = "excluded"."kind", "isTainted" = "excluded"."isTainted" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "ambiguous", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "ambiguous")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
@@ -2490,6 +2520,191 @@ extension MutablePersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where_with_noColumnUnlessSpecified_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Test exemples of https://www.sqlite.org/lang_UPSERT.html
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, MutablePersistableRecord, FetchableRecord {
|
||||
var word: String
|
||||
var kind: String
|
||||
var isTainted: Bool
|
||||
var count: Int?
|
||||
var rowID: Int64?
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
// Don't encode count and rowID
|
||||
container["word"] = word
|
||||
container["kind"] = kind
|
||||
container["isTainted"] = isTainted
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowID = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
// Note that something is updated, so that we have
|
||||
// something to return. See <https://sqlite.org/forum/forumpost/1ead75e2c45de9a5>
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "name", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "name")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("count") += 1, // increment count
|
||||
Column("kind").set(to: excluded["kind"])] // overwrite kind
|
||||
})
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','adjective',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "count" = "count" + 1, "kind" = "excluded"."kind" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true) // Not overwritten
|
||||
XCTAssertEqual(upserted.count, 2) // incremented
|
||||
}
|
||||
|
||||
// All columns with no assignment: make sure we return something
|
||||
do {
|
||||
var vocabulary = Vocabulary(word: "jovial", kind: "ignored", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { _ in
|
||||
[]
|
||||
})
|
||||
|
||||
// Test didSave
|
||||
XCTAssertEqual(vocabulary.rowID, 1)
|
||||
|
||||
// Test SQL (the DO UPDATE clause is not empty, so that the
|
||||
// RETURNING clause could return something).
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ignored',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT);
|
||||
INSERT INTO phonebook(name,phonenumber) VALUES('Alice','ignored');
|
||||
""")
|
||||
|
||||
struct Phonebook: Codable, MutablePersistableRecord, FetchableRecord {
|
||||
var name: String
|
||||
var phonenumber: String
|
||||
}
|
||||
|
||||
var phonebook = Phonebook(name: "Alice", phonenumber: "704-555-1212")
|
||||
let upserted = try phonebook.upsertAndFetch(
|
||||
db, onConflict: ["name"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("phonenumber").set(to: excluded["phonenumber"])]
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "phonebook" ("name", "phonenumber") \
|
||||
VALUES ('Alice','704-555-1212') \
|
||||
ON CONFLICT("name") DO UPDATE SET "phonenumber" = "excluded"."phonenumber" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM phonebook")
|
||||
XCTAssertEqual(rows, [
|
||||
["name": "Alice", "phonenumber": "704-555-1212"],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.name, "Alice")
|
||||
XCTAssertEqual(upserted.phonenumber, "704-555-1212")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
|
||||
@@ -2324,7 +2324,7 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where() throws {
|
||||
func test_upsertAndFetch_do_update_set_where_with_default_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
@@ -2341,10 +2341,10 @@ extension PersistableRecordTests {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, isTainted) VALUES('jovial', 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, PersistableRecord, FetchableRecord {
|
||||
@@ -2361,6 +2361,33 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
// No column specified, no unique index specified
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "ambiguous", isTainted: true)
|
||||
let upserted = try vocabulary.upsertAndFetch(db)
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ambiguous',1) \
|
||||
ON CONFLICT \
|
||||
DO UPDATE SET "kind" = "excluded"."kind", "isTainted" = "excluded"."isTainted" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "ambiguous", "isTainted": 1, "count": 1],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "ambiguous")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 1)
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
@@ -2469,6 +2496,152 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch_do_update_set_where_with_noColumnUnlessSpecified_strategy() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
// Test exemples of https://www.sqlite.org/lang_UPSERT.html
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE vocabulary(
|
||||
word TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
isTainted BOOLEAN DEFAULT 0,
|
||||
count INT DEFAULT 1);
|
||||
INSERT INTO vocabulary(word, kind, isTainted) VALUES('jovial', 'name', 1);
|
||||
""")
|
||||
|
||||
struct Vocabulary: Decodable, PersistableRecord, FetchableRecord {
|
||||
var word: String
|
||||
var kind: String
|
||||
var isTainted: Bool
|
||||
var count: Int?
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
// Don't encode count
|
||||
container["word"] = word
|
||||
container["kind"] = kind
|
||||
container["isTainted"] = isTainted
|
||||
}
|
||||
}
|
||||
|
||||
// One column with specific assignment (count)
|
||||
// One column with no assignment (isTainted)
|
||||
// One column with default overwrite assignment (kind)
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "adjective", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("count") += 1, // increment count
|
||||
Column("kind").set(to: excluded["kind"])] // overwrite kind
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','adjective',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "count" = "count" + 1, "kind" = "excluded"."kind" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true) // Not overwritten
|
||||
XCTAssertEqual(upserted.count, 2) // incremented
|
||||
}
|
||||
|
||||
// All columns with no assignment: make sure we return something
|
||||
do {
|
||||
let vocabulary = Vocabulary(word: "jovial", kind: "ignored", isTainted: false)
|
||||
let upserted = try vocabulary.upsertAndFetch(
|
||||
db, onConflict: ["word"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { _ in
|
||||
[]
|
||||
})
|
||||
|
||||
// Test SQL (the DO UPDATE clause is not empty, so that the
|
||||
// RETURNING clause could return something).
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "vocabulary" ("word", "kind", "isTainted") \
|
||||
VALUES ('jovial','ignored',0) \
|
||||
ON CONFLICT("word") \
|
||||
DO UPDATE SET "word" = "word" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM vocabulary")
|
||||
XCTAssertEqual(rows, [
|
||||
["word": "jovial", "kind": "adjective", "isTainted": 1, "count": 2],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.word, "jovial")
|
||||
XCTAssertEqual(upserted.kind, "adjective")
|
||||
XCTAssertEqual(upserted.isTainted, true)
|
||||
XCTAssertEqual(upserted.count, 2)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE phonebook(name TEXT PRIMARY KEY, phonenumber TEXT);
|
||||
INSERT INTO phonebook(name,phonenumber) VALUES('Alice','ignored');
|
||||
""")
|
||||
|
||||
struct Phonebook: Codable, PersistableRecord, FetchableRecord {
|
||||
var name: String
|
||||
var phonenumber: String
|
||||
}
|
||||
|
||||
let phonebook = Phonebook(name: "Alice", phonenumber: "704-555-1212")
|
||||
let upserted = try phonebook.upsertAndFetch(
|
||||
db, onConflict: ["name"],
|
||||
updating: .noColumnUnlessSpecified,
|
||||
doUpdate: { excluded in
|
||||
[Column("phonenumber").set(to: excluded["phonenumber"])]
|
||||
})
|
||||
|
||||
// Test SQL
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
INSERT INTO "phonebook" ("name", "phonenumber") \
|
||||
VALUES ('Alice','704-555-1212') \
|
||||
ON CONFLICT("name") DO UPDATE SET "phonenumber" = "excluded"."phonenumber" \
|
||||
RETURNING *, "rowid"
|
||||
""")
|
||||
|
||||
// Test database state
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM phonebook")
|
||||
XCTAssertEqual(rows, [
|
||||
["name": "Alice", "phonenumber": "704-555-1212"],
|
||||
])
|
||||
|
||||
// Test upserted record
|
||||
XCTAssertEqual(upserted.name, "Alice")
|
||||
XCTAssertEqual(upserted.phonenumber, "704-555-1212")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_upsertAndFetch() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
@@ -2623,4 +2796,92 @@ extension PersistableRecordTests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_UpsertUpdateStrategy_documentation() throws {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
guard Database.sqliteLibVersionNumber >= 3035000 else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#else
|
||||
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
|
||||
throw XCTSkip("UPSERT is not available")
|
||||
}
|
||||
#endif
|
||||
|
||||
struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
static let databaseTableName = "other_player"
|
||||
var id: Int64 // The primary key
|
||||
var name: String
|
||||
var score: Int
|
||||
var bestScore: Int
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "other_player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("bestScore", .integer).notNull()
|
||||
}
|
||||
try Player(id: 1, name: "Arthur", score: 100, bestScore: 200).insert(db)
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 0)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .allColumns)
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 200)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 0)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 0)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .allColumns) { excluded in
|
||||
let bestScore = Column("bestScore")
|
||||
return [
|
||||
bestScore.set(to: max(bestScore, excluded[bestScore])),
|
||||
]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 200)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
|
||||
XCTAssertEqual(upsertedPlayer.name, "Arthur")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
let name = Column("name")
|
||||
return [name.set(to: excluded[name])]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Barbara")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 200)
|
||||
return .rollback
|
||||
}
|
||||
|
||||
try db.inSavepoint {
|
||||
let player = Player(id: 1, name: "Barbara", score: 200, bestScore: 1000)
|
||||
let upsertedPlayer = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
|
||||
let bestScore = Column("bestScore")
|
||||
return [
|
||||
bestScore.set(to: max(bestScore, excluded[bestScore])),
|
||||
]
|
||||
}
|
||||
XCTAssertEqual(upsertedPlayer.name, "Arthur")
|
||||
XCTAssertEqual(upsertedPlayer.score, 100)
|
||||
XCTAssertEqual(upsertedPlayer.bestScore, 1000)
|
||||
return .rollback
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user